app_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. if !app.loadLanguages() {
  30. t.Fatal("Couldn't load languages!")
  31. }
  32. testLanguageCode := "dan"
  33. testLanguage := "Danish"
  34. fromMap, ok := app.Languages[testLanguageCode]
  35. if !ok {
  36. t.Fatalf("There's no key '%s'!", testLanguageCode)
  37. }
  38. if fromMap != testLanguage {
  39. t.Fatalf("Value of key '%s' isn't '%s'", testLanguageCode, testLanguage)
  40. }
  41. }
  42. func TestLogin(t *testing.T) {
  43. loginResponse := `{
  44. "Name": "admin",
  45. "Sid": "00000000-0000-0000-0001-000000000001",
  46. "AccessToken": "fde0f7ed-d585-48ec-a0a9-397aea195ccd"
  47. }`
  48. server := fakeServer(http.StatusOK, loginResponse)
  49. defer server.Close()
  50. var app Application
  51. app.setBaseURL(server.URL)
  52. status, err := app.login()
  53. if !status || err != nil {
  54. t.Fatalf("Status: %v, error: %s", status, err)
  55. }
  56. }
  57. func TestLoginBadURL(t *testing.T) {
  58. var app Application
  59. app.setBaseURL("badURL")
  60. status, err := app.login()
  61. if status || err == nil {
  62. t.Fatalf("Status: %v, error: %s", status, err)
  63. }
  64. }
  65. func TestLoginWrongStatus(t *testing.T) {
  66. server := fakeServer(http.StatusBadRequest, "")
  67. defer server.Close()
  68. var app Application
  69. app.setBaseURL(server.URL)
  70. status, err := app.login()
  71. if status || err == nil {
  72. t.Fatalf("Status: %v, error: %s", status, err)
  73. }
  74. }