Skip to content

Commit

Permalink
add webapp unit tests
Browse files Browse the repository at this point in the history
Signed-off-by: Nahshon Unna-Tsameret <nahsh.ut@gmail.com>
  • Loading branch information
nunnatsa committed Mar 24, 2021
1 parent 84dfb48 commit 49cd661
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 0 deletions.
42 changes: 42 additions & 0 deletions webapp/frontend_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package webapp

import (
"net/http"
"net/http/httptest"
"testing"
)

func TestEmbed(t *testing.T) {
file, err := indexTemplate.Open("index.gohtml")
if err != nil {
t.Fatal(err)
}

stat, err := file.Stat()
if err != nil {
t.Fatal(err)
}

if stat.Size() == 0 {
t.Fatal("should not be empty")
}
}

func TestIndexPage_ServeHTTP(t *testing.T) {
expected := "hello there"
ip := indexPage(expected)
req := httptest.NewRequest(http.MethodGet, "/", nil)

rr := httptest.NewRecorder()
ip.ServeHTTP(rr, req)

if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}

if rr.Body.String() != expected {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), expected)
}
}
66 changes: 66 additions & 0 deletions webapp/websocket_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package webapp

import (
"github.com/gorilla/websocket"
"github.com/nunnatsa/piHatDraw/notifier"
"net/http/httptest"
"strings"
"testing"
)

func TestWebApplication_register(t *testing.T) {
n := notifier.NewNotifier()
ce := make(chan ClientEvent)

wa := NewWebApplication(n, 8080, ce)
server := httptest.NewServer(wa.GetMux())
defer server.Close()

url := "ws" + strings.TrimPrefix(server.URL, "http") + "/api/canvas/register"

numClients := ClientEventRegistered(10)
sockets := make([]*websocket.Conn, 0, numClients)
message := "another message"

for i := ClientEventRegistered(1) ; i <= numClients; i++ {
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
t.Fatalf("%v", err)
}
defer ws.Close()

sockets = append(sockets, ws)

clientEvent := <-ce
subscriberID, ok := clientEvent.(ClientEventRegistered)
if !ok {
t.Fatal("wrong client event type")
}
if subscriberID != i {
t.Fatalf("wrong subscriberId; shoud be %d but it's %d", i, subscriberID)
}

n.NotifyOne(uint64(subscriberID), []byte(message))

_, p, err := ws.ReadMessage()
if err != nil {
t.Fatalf("%v", err)
}
if string(p) != message {
t.Fatalf("bad message")
}
}

message = "hello there"
n.NotifyAll([]byte(message))

for _, ws := range sockets {
_, p, err := ws.ReadMessage()
if err != nil {
t.Fatalf("%v", err)
}
if string(p) != message {
t.Fatalf("bad message")
}
}
}

0 comments on commit 49cd661

Please sign in to comment.