github.com/imwally/hashma@v0.0.0-20171123180615-7a06cd6eac6b/hashma_test.go (about) 1 package main 2 3 import ( 4 "testing" 5 "fmt" 6 "sync" 7 "io/ioutil" 8 ) 9 10 var ( 11 algorithms = []string{ 12 "md5", 13 "sha1", 14 "sha256", 15 "sha512", 16 } 17 18 data = []byte{ 19 0x54, 0x68, 0x65, 0x20, 0x73, 0x6B, 0x79, 0x20, 20 0x61, 0x62, 0x6F, 0x76, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 21 0x6F, 0x72, 0x74, 0x20, 0x77, 0x61, 0x73, 0x20, 0x74, 0x68, 0x65, 22 0x20, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x20, 0x6F, 0x66, 0x20, 0x74, 23 0x65, 0x6C, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6F, 0x6E, 0x2C, 0x20, 24 0x74, 0x75, 0x6E, 0x65, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x61, 0x20, 25 0x64, 0x65, 0x61, 0x64, 0x20, 0x63, 0x68, 0x61, 0x6E, 0x6E, 0x65, 26 0x6C, 0x2E, 27 } 28 29 MD5hash = "c736b509feee0cb9a4f8d606d5f6050d" 30 SHA1hash = "49ceb59827e0c76fcf94d5da80b8f4bc0dc94b15" 31 SHA256hash = "5041821981ec48d8db280ff293c35de17ef5dbfbac25adc81ff272d0fc22b2ae" 32 SHA512hash = "53164b83c1e27d6f0f4175fb3f0a8c668ad7afe8e9f423ed8fe5311c80556e7be33449369947bb0c29bd6702c90ab08a004a767802d309fb04726f2a799ee1b3" 33 34 // Load a lager external file to test benchmarks. 35 file = "debian-live-8.2.0-amd64-gnome-desktop.iso" 36 ) 37 38 func TestMD5Hasher(t *testing.T) { 39 md5 := hasher(data, "md5") 40 if md5 != MD5hash { 41 t.Error(`MD5 failed.`) 42 } 43 } 44 45 func TestSHA1Hasher(t *testing.T) { 46 sha1 := hasher(data, "sha1") 47 if sha1 != SHA1hash { 48 t.Error(`SHA1 failed.`) 49 } 50 } 51 52 func TestSHA256Hasher(t *testing.T) { 53 sha256 := hasher(data, "sha256") 54 if sha256 != SHA256hash { 55 t.Error(`SHA256 failed.`) 56 } 57 } 58 59 func TestSHA512Hasher(t *testing.T) { 60 sha512 := hasher(data, "sha512") 61 if sha512 != SHA512hash { 62 t.Error(`SHA512 failed.`) 63 } 64 } 65 66 func TestFindHashesWithNoCheckSum(t *testing.T) { 67 hashchan := make(chan string) 68 69 var wg sync.WaitGroup 70 for _, algo := range algorithms { 71 wg.Add(1) 72 go func(algo string) { 73 defer wg.Done() 74 hashchan <- hasher(data, algo) 75 }(algo) 76 } 77 78 go func() { 79 wg.Wait() 80 close(hashchan) 81 }() 82 83 for hash := range hashchan { 84 if findHash("test", hash) { 85 fmt.Printf("%s", hash) 86 } 87 } 88 } 89 90 91 func BenchmarkSequentialHasher(t *testing.B) { 92 fileBytes, err := ioutil.ReadFile(file) 93 if err != nil { 94 t.Error(err) 95 } 96 97 fmt.Println() 98 for _, algo := range algorithms { 99 hash := hasher(fileBytes, algo) 100 fmt.Printf("%s\n", hash) 101 } 102 } 103 104 func BenchmarkConcurrentHasher(t *testing.B) { 105 fileBytes, err := ioutil.ReadFile(file) 106 if err != nil { 107 t.Error(err) 108 } 109 110 hashchan := make(chan string) 111 var wg sync.WaitGroup 112 for _, algo := range algorithms { 113 wg.Add(1) 114 go func(algo string) { 115 defer wg.Done() 116 hashchan <- hasher(fileBytes, algo) 117 }(algo) 118 } 119 120 go func() { 121 wg.Wait() 122 close(hashchan) 123 }() 124 125 fmt.Println() 126 for hash := range hashchan { 127 fmt.Printf("%s\n", hash) 128 } 129 }