From 91766058d76044fa7e07f75c586bc7f89b868328 Mon Sep 17 00:00:00 2001 From: xengineering Date: Fri, 30 Jun 2023 11:57:34 +0200 Subject: Add unit test for routing function --- xmpp/router_test.go | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 xmpp/router_test.go diff --git a/xmpp/router_test.go b/xmpp/router_test.go new file mode 100644 index 0000000..ea13712 --- /dev/null +++ b/xmpp/router_test.go @@ -0,0 +1,69 @@ +package xmpp + +import ( + "encoding/xml" + "testing" + "strings" +) + +// routerTest contains a single test case for the xmpp.router. The XML element +// is given as a string and the value int describes the expected value of a +// test variable inside the corresponding unit test. See TestRouter for +// details. +type routerTest struct { + xml string + value int +} + +// TestRouter tests the xmpp/router.go file. The central functionality is the +// route() function. To test this a fake routing table is created inside this +// test with XML element handler function produced by the factory function +// defined below. each handler simply sets the value of the testpoint variable +// to the value mentioned by the test point. That way the routing can be +// validated. +func TestRouter(t *testing.T) { + var testpoint int + + factory := func(tp *int, i int) func([]xml.Token) { + return func([]xml.Token) { + *tp = i + } + } + + tests := []routerTest{ + routerTest{``, 1}, + routerTest{``, 2}, + routerTest{``, 3}, + routerTest{``, 4}, + routerTest{``, 5}, + } + + testRouting := routingTable{ + {xml.Name{``, `a`}, factory(&testpoint, 1)}, + {xml.Name{``, `b`}, factory(&testpoint, 2)}, + {xml.Name{``, `c`}, factory(&testpoint, 3)}, + {xml.Name{`https://xengineering.eu`, `b`}, factory(&testpoint, 4)}, + {xml.Name{`https://xengineering.eu`, `a`}, factory(&testpoint, 5)}, + } + + for _, v := range tests { + testpoint = 0 + + r := strings.NewReader(v.xml) + d := xml.NewDecoder(r) + tokens := make([]xml.Token, 0) + for { + token, err := d.Token() + if err != nil { + break + } + tokens = append(tokens, xml.CopyToken(token)) + } + + route(tokens, testRouting) + + if testpoint != v.value { + t.Fatalf("XML element was not routed correctly!\n") + } + } +} -- cgit v1.2.3-70-g09d2