app_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. if !app.checkLanguage(testLanguageCode) {
  42. t.Fatalf("checkLanguage returned false for %s", testLanguageCode)
  43. }
  44. }
  45. func TestLogin(t *testing.T) {
  46. loginResponse := `{
  47. "Name": "admin",
  48. "Sid": "00000000-0000-0000-0001-000000000001",
  49. "AccessToken": "fde0f7ed-d585-48ec-a0a9-397aea195ccd"
  50. }`
  51. server := fakeServer(http.StatusOK, loginResponse)
  52. defer server.Close()
  53. var app Application
  54. app.setBaseURL(server.URL)
  55. status, err := app.login()
  56. if !status || err != nil {
  57. t.Fatalf("Status: %v, error: %s", status, err)
  58. }
  59. }
  60. func TestLoginBadURL(t *testing.T) {
  61. var app Application
  62. app.setBaseURL("badURL")
  63. status, err := app.login()
  64. if status || err == nil {
  65. t.Fatalf("Status: %v, error: %s", status, err)
  66. }
  67. }
  68. func TestLoginWrongStatus(t *testing.T) {
  69. server := fakeServer(http.StatusBadRequest, "")
  70. defer server.Close()
  71. var app Application
  72. app.setBaseURL(server.URL)
  73. status, err := app.login()
  74. if status || err == nil {
  75. t.Fatalf("Status: %v, error: %s", status, err)
  76. }
  77. }