plugin_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package knmi
  2. import (
  3. "encoding/xml"
  4. "math/rand"
  5. "net/url"
  6. "testing"
  7. "time"
  8. )
  9. func TestFetch(t *testing.T) {
  10. p := plugin{}
  11. p.config.ForecastURL = "ftp://ftp.knmi.nl/pub_weerberichten/basisverwachting.xml"
  12. u, _ := url.Parse(p.config.ForecastURL)
  13. t.Run("wrongdomain", func(t *testing.T) {
  14. fu2 := u.Scheme + "://wrongdomain." + randomword() + ".com" + u.Path
  15. _, err := p.fetch(fu2)
  16. if err == nil {
  17. t.Errorf("Using %s, expected error, got nil", fu2)
  18. }
  19. })
  20. t.Run("wrongpath", func(t *testing.T) {
  21. fu2 := u.Scheme + "://" + u.Host + "/" + randomword() + ".wrongpath"
  22. _, err := p.fetch(fu2)
  23. if err == nil {
  24. t.Errorf("Using %s, expected error, got nil", fu2)
  25. }
  26. })
  27. t.Run("good", func(t *testing.T) {
  28. // fetch from valid source
  29. data, err := p.fetch(p.config.ForecastURL)
  30. if err != nil {
  31. t.Errorf("Using %s, expected nil, got err: %s", p.config.ForecastURL, err)
  32. }
  33. // parse data that is supposed to be valid
  34. fc := knmiForecast{}
  35. err = xml.Unmarshal(data, &fc)
  36. if err != nil {
  37. t.Errorf("Expected nil, got err from parsing fetched data: %s", err)
  38. }
  39. })
  40. }
  41. func randomword() string {
  42. var word [8]byte
  43. const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  44. rng := rand.New(rand.NewSource(time.Now().UnixNano()))
  45. for i := 0; i < len(word); i++ {
  46. word[i] = letters[rng.Intn(len(letters))]
  47. }
  48. return string(word[:])
  49. }