storage_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. package rangeplugin
  5. import (
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. var leasefile string = `02:00:00:00:00:00 10.0.0.0 2000-01-01T00:00:00Z
  15. 02:00:00:00:00:01 10.0.0.1 2000-01-01T00:00:00Z
  16. 02:00:00:00:00:02 10.0.0.2 2000-01-01T00:00:00Z
  17. 02:00:00:00:00:03 10.0.0.3 2000-01-01T00:00:00Z
  18. 02:00:00:00:00:04 10.0.0.4 2000-01-01T00:00:00Z
  19. 02:00:00:00:00:05 10.0.0.5 2000-01-01T00:00:00Z
  20. `
  21. var expire = time.Date(2000, 01, 01, 00, 00, 00, 00, time.UTC)
  22. var records = []struct {
  23. mac string
  24. ip *Record
  25. }{
  26. {"02:00:00:00:00:00", &Record{net.IPv4(10, 0, 0, 0), expire}},
  27. {"02:00:00:00:00:01", &Record{net.IPv4(10, 0, 0, 1), expire}},
  28. {"02:00:00:00:00:02", &Record{net.IPv4(10, 0, 0, 2), expire}},
  29. {"02:00:00:00:00:03", &Record{net.IPv4(10, 0, 0, 3), expire}},
  30. {"02:00:00:00:00:04", &Record{net.IPv4(10, 0, 0, 4), expire}},
  31. {"02:00:00:00:00:05", &Record{net.IPv4(10, 0, 0, 5), expire}},
  32. }
  33. func TestLoadRecords(t *testing.T) {
  34. parsedRec, err := loadRecords(strings.NewReader(leasefile))
  35. if err != nil {
  36. t.Fatalf("Failed to load records from file: %v", err)
  37. }
  38. mapRec := make(map[string]*Record)
  39. for _, rec := range records {
  40. mapRec[rec.mac] = rec.ip
  41. }
  42. assert.Equal(t, mapRec, parsedRec, "Loaded records differ from what's in the file")
  43. }
  44. func TestWriteRecords(t *testing.T) {
  45. tmpfile, err := ioutil.TempFile("", "coredhcptest")
  46. if err != nil {
  47. t.Skipf("Could not setup file-based test: %v", err)
  48. }
  49. defer os.Remove(tmpfile.Name())
  50. defer tmpfile.Close()
  51. pl := PluginState{}
  52. if err := pl.registerBackingFile(tmpfile.Name()); err != nil {
  53. t.Fatalf("Could not setup file")
  54. }
  55. defer pl.leasefile.Close()
  56. for _, rec := range records {
  57. hwaddr, err := net.ParseMAC(rec.mac)
  58. if err != nil {
  59. // bug in testdata
  60. panic(err)
  61. }
  62. if err := pl.saveIPAddress(hwaddr, rec.ip); err != nil {
  63. t.Errorf("Failed to save ip for %s: %v", hwaddr, err)
  64. }
  65. }
  66. if _, err := tmpfile.Seek(0, 0); err != nil {
  67. t.Fatal(err)
  68. }
  69. written, err := ioutil.ReadAll(tmpfile)
  70. if err != nil {
  71. t.Fatalf("Could not read back temp file")
  72. }
  73. assert.Equal(t, leasefile, string(written), "Data written to the file doesn't match records")
  74. }