testing - How to test Golang channels / go-routines -


i have type contains byte of data, , takes channel post new data there. other code can read last written byte of data using read function.

edit: actual, runnable code, see https://github.com/ariejan/i6502/pull/3 files acia6551.go , acia6551_test.go. tests results can viewed here: https://travis-ci.org/ariejan/i6502/jobs/32862705

i have following:

// emulates serial interface chip of kind. type unit struct {   // channel used others use, bytes written here placed in rxchar   rx chan byte    // internal store of last byte written.   rxchar byte // internal storage }  // used internally read data store in rxchar func (u *unit) read() byte {   return u.rxchar }  // create new unit , go-routing listen rx bytes func newunit(rx chan byte) *unit {   unit := &unit{rx: rx}    go func() {     {       select {       case data := <-unit.rx:         unit.rxdata = data         fmt.printf("posted 0x%02x\n", data)       }     }   }()    return unit } 

my test looks this:

func testunitrx(t *testing.t) {   rx := make(chan byte)   u := newunit(rx)    // post byte rx channel   // prints "posted 0x42", you'd expect   rx <- 0x42    // using testing   // should read last byte, 0x42 fails.   fmt.println("reading value...")   assert.equal(t, 0x42, u.read())  } 

at first figured "reading value" happened before go-routing got around writing data. "posted" message printed before "reading".

so, 2 questions remain:

  • is best way handle incoming stream of bytes (at 9600 baud ;-))
  • if right way, how can test or wrong code?

guessing pieces posted here, doesn't have guaranteeing order of operations when accessing stored data. can use mutex around data shared between goroutines.

a better option here use buffered channels of length 1 write, store, , read bytes.

it's idea test program -race use race detector.

since looks "stream" like, may want buffering, , @ examples of how io.reader , io.writer interfaces used.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -