memcache_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. Copyright 2011 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package memcache provides a client for the memcached cache server.
  14. package memcache
  15. import (
  16. "net"
  17. "testing"
  18. )
  19. const testServer = "localhost:11211"
  20. func setup(t *testing.T) bool {
  21. c, err := net.Dial("tcp", testServer)
  22. if err != nil {
  23. t.Logf("skipping test; no server running at %s", testServer)
  24. return false
  25. }
  26. c.Write([]byte("flush_all\r\n"))
  27. c.Close()
  28. return true
  29. }
  30. func TestMemcache(t *testing.T) {
  31. if !setup(t) {
  32. return
  33. }
  34. c := New(testServer)
  35. foo := &Item{Key: "foo", Value: []byte("fooval"), Flags: 123}
  36. if err := c.Set(foo); err != nil {
  37. t.Fatalf("first set(foo): %v", err)
  38. }
  39. if err := c.Set(foo); err != nil {
  40. t.Fatalf("second set(foo): %v", err)
  41. }
  42. it, err := c.Get("foo")
  43. if err != nil {
  44. t.Fatalf("get(foo): %v", err)
  45. }
  46. if it.Key != "foo" {
  47. t.Errorf("get(foo) Key = %q, want foo", it.Key)
  48. }
  49. if string(it.Value) != "fooval" {
  50. t.Errorf("get(foo) Value = %q, want fooval", string(it.Value))
  51. }
  52. if it.Flags != 123 {
  53. t.Errorf("get(foo) Flags = %v, want 123", it.Flags)
  54. }
  55. bar := &Item{Key: "bar", Value: []byte("barval")}
  56. if err := c.Add(bar); err != nil {
  57. t.Fatalf("first add(foo): %v", err)
  58. }
  59. if err := c.Add(bar); err != ErrNotStored {
  60. t.Fatalf("second add(foo) want ErrNotStored, got %v", err)
  61. }
  62. m, err := c.GetMulti([]string{"foo", "bar"})
  63. if err != nil {
  64. t.Fatalf("GetMulti: %v", err)
  65. }
  66. if g, e := len(m), 2; g != e {
  67. t.Errorf("GetMulti: got len(map) = %d, want = %d", g, e)
  68. }
  69. if _, ok := m["foo"]; !ok {
  70. t.Fatalf("GetMulti: didn't get key 'foo'")
  71. }
  72. if _, ok := m["bar"]; !ok {
  73. t.Fatalf("GetMulti: didn't get key 'bar'")
  74. }
  75. if g, e := string(m["foo"].Value), "fooval"; g != e {
  76. t.Errorf("GetMulti: foo: got %q, want %q", g, e)
  77. }
  78. if g, e := string(m["bar"].Value), "barval"; g != e {
  79. t.Errorf("GetMulti: bar: got %q, want %q", g, e)
  80. }
  81. }