app_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. )
  9. func fakeServer(statusCode int, data string) *httptest.Server {
  10. function := func(w http.ResponseWriter, r *http.Request) {
  11. w.Header().Set("Content-Type", "application/json")
  12. w.WriteHeader(statusCode)
  13. fmt.Fprint(w, data)
  14. }
  15. return httptest.NewServer(http.HandlerFunc(function))
  16. }
  17. func TestSetBaseURL(t *testing.T) {
  18. toTest := []string{"http://test.com:880/test/", "http://test.com:880/test"}
  19. var app Application
  20. for _, testCase := range toTest {
  21. app.setBaseURL(testCase)
  22. if strings.HasSuffix(app.BaseURL, "//") || !strings.HasSuffix(app.BaseURL, "/") {
  23. t.Errorf("URL has been malformed: %s", app.BaseURL)
  24. }
  25. }
  26. }
  27. func TestLoadLanguages(t *testing.T) {
  28. var app Application
  29. app.loadLanguages()
  30. testLanguageCode := "dan"
  31. testLanguage := "Danish"
  32. fromMap, ok := app.Languages[testLanguageCode]
  33. if !ok {
  34. t.Fatalf("There's no key '%s'!", testLanguageCode)
  35. }
  36. if fromMap != testLanguage {
  37. t.Fatalf("Value of key '%s' isn't '%s'", testLanguageCode, testLanguage)
  38. }
  39. }
  40. func TestLogin(t *testing.T) {
  41. loginResponse := `{
  42. "Name": "admin",
  43. "Sid": "00000000-0000-0000-0001-000000000001",
  44. "AccessToken": "fde0f7ed-d585-48ec-a0a9-397aea195ccd"
  45. }`
  46. server := fakeServer(http.StatusOK, loginResponse)
  47. defer server.Close()
  48. var app Application
  49. app.setBaseURL(server.URL)
  50. status, err := app.login()
  51. if !status || err != nil {
  52. t.Fatalf("Status: %v, error: %s", status, err)
  53. }
  54. }
  55. func TestLoginBadURL(t *testing.T) {
  56. var app Application
  57. app.setBaseURL("badURL")
  58. status, err := app.login()
  59. if status || err == nil {
  60. t.Fatalf("Status: %v, error: %s", status, err)
  61. }
  62. }
  63. func TestLoginWrongStatus(t *testing.T) {
  64. server := fakeServer(http.StatusBadRequest, "")
  65. defer server.Close()
  66. var app Application
  67. app.setBaseURL(server.URL)
  68. status, err := app.login()
  69. if status || err == nil {
  70. t.Fatalf("Status: %v, error: %s", status, err)
  71. }
  72. }