| 1 | package observer |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | "testing" |
| 6 | ) |
| 7 | |
| 8 | func TestPropertyInitialValue(t *testing.T) { |
| 9 | prop := NewProperty(10) |
| 10 | if val := prop.Value(); val != 10 { |
| 11 | t.Fatalf("Expecting 10 but got %#v\n", val) |
| 12 | } |
| 13 | stream := prop.Observe() |
| 14 | for i := 0; i <= 100; i++ { |
| 15 | if val := stream.Value(); val != 10 { |
| 16 | t.Fatalf("Expecting 10 but got %#v\n", val) |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | func TestPropertyInitialObserve(t *testing.T) { |
| 22 | prop := NewProperty(10) |
| 23 | var prevStream Stream |
| 24 | for i := 0; i <= 100; i++ { |
| 25 | stream := prop.Observe() |
| 26 | if stream == prevStream { |
| 27 | t.Fatalf("Expecting different stream\n") |
| 28 | } |
| 29 | if val := stream.Value(); val != 10 { |
| 30 | t.Fatalf("Expecting 10 but got %#v\n", val) |
| 31 | } |
| 32 | prevStream = stream |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | func TestPropertyObserveAfterUpdate(t *testing.T) { |
| 37 | prop := NewProperty(10) |
| 38 | if val := prop.Value(); val != 10 { |
| 39 | t.Fatalf("Expecting 10 but got %#v\n", val) |
| 40 | } |
| 41 | prop.Update(15) |
| 42 | if val := prop.Value(); val != 15 { |
| 43 | t.Fatalf("Expecting 15 but got %#v\n", val) |
| 44 | } |
| 45 | stream := prop.Observe() |
| 46 | if val := stream.Value(); val != 15 { |
| 47 | t.Fatalf("Expecting 15 but got %#v\n", val) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func TestPropertyMultipleConcurrentReaders(t *testing.T) { |
| 52 | initial := 1000 |
| 53 | final := 2000 |
| 54 | prop := NewProperty(initial) |
| 55 | var cherrs []chan error |
| 56 | for i := 0; i < 1000; i++ { |
| 57 | cherr := make(chan error, 1) |
| 58 | cherrs = append(cherrs, cherr) |
| 59 | go testStreamRead(prop.Observe(), initial, final, cherr) |
| 60 | } |
| 61 | done := make(chan bool) |
| 62 | go func(prop Property, initial, final int, done chan bool) { |
| 63 | defer close(done) |
| 64 | for i := initial + 1; i <= final; i++ { |
| 65 | prop.Update(i) |
| 66 | } |
| 67 | }(prop, initial, final, done) |
| 68 | for _, cherr := range cherrs { |
| 69 | if err := <-cherr; err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | } |
| 73 | <-done |
| 74 | } |
| 75 | |
| 76 | func TestPropertyMultipleConcurrentReadersWriters(t *testing.T) { |
| 77 | wg := &sync.WaitGroup{} |
| 78 | writer := func(prop Property, times int) { |
| 79 | defer wg.Done() |
| 80 | for i := 0; i <= times; i++ { |
| 81 | val := prop.Value().(int) |
| 82 | prop.Update(val + 1) |
| 83 | prop.Observe() |
| 84 | } |
| 85 | } |
| 86 | prop := NewProperty(0) |
| 87 | times := 1000 |
| 88 | for i := 0; i < 1000; i++ { |
| 89 | wg.Add(1) |
| 90 | go writer(prop, times) |
| 91 | } |
| 92 | wg.Wait() |
| 93 | } |