common_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package protocol
  5. import (
  6. "io"
  7. "time"
  8. )
  9. type TestModel struct {
  10. data []byte
  11. repo string
  12. name string
  13. offset int64
  14. size int
  15. closedCh chan bool
  16. }
  17. func newTestModel() *TestModel {
  18. return &TestModel{
  19. closedCh: make(chan bool),
  20. }
  21. }
  22. func (t *TestModel) Index(nodeID NodeID, repo string, files []FileInfo) {
  23. }
  24. func (t *TestModel) IndexUpdate(nodeID NodeID, repo string, files []FileInfo) {
  25. }
  26. func (t *TestModel) Request(nodeID NodeID, repo, name string, offset int64, size int) ([]byte, error) {
  27. t.repo = repo
  28. t.name = name
  29. t.offset = offset
  30. t.size = size
  31. return t.data, nil
  32. }
  33. func (t *TestModel) Close(nodeID NodeID, err error) {
  34. close(t.closedCh)
  35. }
  36. func (t *TestModel) ClusterConfig(nodeID NodeID, config ClusterConfigMessage) {
  37. }
  38. func (t *TestModel) isClosed() bool {
  39. select {
  40. case <-t.closedCh:
  41. return true
  42. case <-time.After(1 * time.Second):
  43. return false // Timeout
  44. }
  45. }
  46. type ErrPipe struct {
  47. io.PipeWriter
  48. written int
  49. max int
  50. err error
  51. closed bool
  52. }
  53. func (e *ErrPipe) Write(data []byte) (int, error) {
  54. if e.closed {
  55. return 0, e.err
  56. }
  57. if e.written+len(data) > e.max {
  58. n, _ := e.PipeWriter.Write(data[:e.max-e.written])
  59. e.PipeWriter.CloseWithError(e.err)
  60. e.closed = true
  61. return n, e.err
  62. }
  63. return e.PipeWriter.Write(data)
  64. }