manager_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package connection
  2. import (
  3. "reflect"
  4. "testing"
  5. )
  6. const TestClient = "MockClient"
  7. var GetCalledNumber int
  8. var CloseCalledNumber int
  9. type MockClient struct {
  10. selector *ConSelector
  11. mockCon string
  12. }
  13. func (m *MockClient) CfgValidate(m2 map[string]interface{}) error {
  14. return nil
  15. }
  16. func (m *MockClient) GetClient() (interface{}, error) {
  17. GetCalledNumber = 1
  18. m.mockCon = "MockClient"
  19. return m.mockCon, nil
  20. }
  21. func (m *MockClient) CloseClient() error {
  22. CloseCalledNumber = 1
  23. m.mockCon = ""
  24. return nil
  25. }
  26. func TestManager(t *testing.T) {
  27. registerClientFactory("mqtt", func(super *ConSelector) Client {
  28. return &MockClient{selector: super}
  29. })
  30. conSelector := "mqtt.mqtt_conf1"
  31. connection, err := GetConnection(conSelector)
  32. if err != nil {
  33. t.Errorf("GetConnection Error")
  34. }
  35. value := connection.(string)
  36. if !reflect.DeepEqual(value, TestClient) {
  37. t.Errorf("Error")
  38. }
  39. connection, err = GetConnection(conSelector)
  40. if err != nil {
  41. t.Errorf("GetConnection Error")
  42. }
  43. wrapper := m.clientMap[conSelector]
  44. if !reflect.DeepEqual(wrapper.refCnt, uint32(2)) {
  45. t.Errorf("Error, ectual=%v, want=%v", wrapper.refCnt, 2)
  46. }
  47. connection, err = GetConnection(conSelector)
  48. if err != nil {
  49. t.Errorf("GetConnection Error")
  50. }
  51. if !reflect.DeepEqual(wrapper.refCnt, uint32(3)) {
  52. t.Errorf("Error")
  53. }
  54. ReleaseConnection(conSelector)
  55. if !reflect.DeepEqual(wrapper.refCnt, uint32(2)) {
  56. t.Errorf("Error")
  57. }
  58. ReleaseConnection(conSelector)
  59. if !reflect.DeepEqual(wrapper.refCnt, uint32(1)) {
  60. t.Errorf("Error")
  61. }
  62. ReleaseConnection(conSelector)
  63. if !reflect.DeepEqual(wrapper.refCnt, uint32(0)) {
  64. t.Errorf("Error")
  65. }
  66. if _, ok := m.clientMap[conSelector]; ok {
  67. t.Errorf("Error")
  68. }
  69. if !reflect.DeepEqual(GetCalledNumber, CloseCalledNumber) || !reflect.DeepEqual(GetCalledNumber, 1) {
  70. t.Errorf("Error")
  71. }
  72. }