Add tests for --auth.
authorEmil Mikulic <emikulic@gmail.com>
Wed, 1 Jul 2020 11:00:46 +0000 (21:00 +1000)
committerEmil Mikulic <emikulic@gmail.com>
Wed, 1 Jul 2020 11:22:17 +0000 (21:22 +1000)
devel/run-tests
devel/test_auth.py [new file with mode: 0755]

index 8e2bfde..df61c37 100755 (executable)
@@ -106,6 +106,19 @@ runtests() {
   kill $PID
   wait $PID
 
+  echo "===> run --auth tests"
+  # Wrong flags:
+  ./a.out . --auth >/dev/null 2>/dev/null
+  ./a.out . --auth missing_colon >/dev/null 2>/dev/null
+  # Correct flags:
+  ./a.out $DIR --port $PORT --auth myuser:mypass \
+    >>test.out.stdout 2>>test.out.stderr &
+  PID=$!
+  kill -0 $PID || exit 1
+  python test_auth.py
+  kill $PID
+  wait $PID
+
   if [[ -s test.out.stderr ]]; then
     echo "FAIL: stderr should have been empty."
     exit 1
diff --git a/devel/test_auth.py b/devel/test_auth.py
new file mode 100755 (executable)
index 0000000..a478b4e
--- /dev/null
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+# This is run by the "run-tests" script.
+import unittest
+import os
+import random
+import base64
+from test import WWWROOT, TestHelper, Conn, parse
+
+class TestAuth(TestHelper):
+    def setUp(self):
+        self.datalen = 2345
+        self.data = ''.join(
+            [chr(random.randint(0,255)) for _ in xrange(self.datalen)])
+        self.url = '/data.jpeg'
+        self.fn = WWWROOT + self.url
+        with open(self.fn, 'w') as f:
+            f.write(self.data)
+
+    def tearDown(self):
+        os.unlink(self.fn)
+
+    def test_no_auth(self):
+        resp = self.get(self.url)
+        status, hdrs, body = parse(resp)
+        self.assertContains(status, '401 Unauthorized')
+        self.assertEquals(hdrs['WWW-Authenticate'],
+            'Basic realm="User Visible Realm"')
+
+    def test_with_auth(self):
+        resp = self.get(self.url, req_hdrs={
+            'Authorization': 'Basic '+base64.b64encode('myuser:mypass')})
+        status, hdrs, body = parse(resp)
+        self.assertContains(status, '200 OK')
+        self.assertEquals(hdrs["Accept-Ranges"], "bytes")
+        self.assertEquals(hdrs["Content-Length"], str(self.datalen))
+        self.assertEquals(hdrs["Content-Type"], "image/jpeg")
+        self.assertContains(hdrs["Server"], "darkhttpd/")
+        assert body == self.data, [url, resp, status, hdrs, body]
+        self.assertEquals(body, self.data)
+
+if __name__ == '__main__':
+    unittest.main()
+
+# vim:set ts=4 sw=4 et: