concurrency: add func, test, and bm test (mock and stub)
This commit is contained in:
parent
05226985c7
commit
93d9a14858
12
concurrency/concurrency.go
Normal file
12
concurrency/concurrency.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package concurrency
|
||||||
|
|
||||||
|
type WebsiteChecker func(string) bool
|
||||||
|
|
||||||
|
func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
|
||||||
|
results := make(map[string]bool)
|
||||||
|
|
||||||
|
for _, url := range urls {
|
||||||
|
results[url] = wc(url)
|
||||||
|
}
|
||||||
|
return results
|
||||||
|
}
|
47
concurrency/concurrency_test.go
Normal file
47
concurrency/concurrency_test.go
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
package concurrency
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mockWebsiteChecker(url string) bool {
|
||||||
|
return url != "waat://furhurterwe.geds"
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckWebsites(t *testing.T) {
|
||||||
|
websites := []string{
|
||||||
|
"http://google.com",
|
||||||
|
"http://blog.abc.com",
|
||||||
|
"waat://furhurterwe.geds",
|
||||||
|
}
|
||||||
|
|
||||||
|
want := map[string]bool{
|
||||||
|
"http://google.com": true,
|
||||||
|
"http://blog.abc.com": true,
|
||||||
|
"waat://furhurterwe.geds": false,
|
||||||
|
}
|
||||||
|
|
||||||
|
got := CheckWebsites(mockWebsiteChecker, websites)
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("wanted %v, got %v", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func slowStubWebsiteChecker(_ string) bool {
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCheckWebsites(b *testing.B) {
|
||||||
|
urls := make([]string, 100)
|
||||||
|
for i := 0; i < len(urls); i++ {
|
||||||
|
urls[i] = "a url"
|
||||||
|
}
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
CheckWebsites(slowStubWebsiteChecker, urls)
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user