darkhttpd/devel/test_auth.py

55 lines
1.8 KiB
Python
Raw Normal View History

2021-01-17 08:52:47 +03:00
#!/usr/bin/env python3
2020-07-01 14:00:46 +03:00
# This is run by the "run-tests" script.
import unittest
import os
import random
import base64
2021-01-17 08:52:47 +03:00
from test import WWWROOT, TestHelper, Conn, parse, random_bytes
2020-07-01 14:00:46 +03:00
class TestAuth(TestHelper):
def setUp(self):
self.datalen = 2345
2021-01-17 08:52:47 +03:00
self.data = random_bytes(self.datalen)
2020-07-01 14:00:46 +03:00
self.url = '/data.jpeg'
self.fn = WWWROOT + self.url
2021-01-17 08:52:47 +03:00
with open(self.fn, 'wb') as f:
2020-07-01 14:00:46 +03:00
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')
2021-01-17 08:52:47 +03:00
self.assertEqual(hdrs['WWW-Authenticate'],
2020-07-01 14:00:46 +03:00
'Basic realm="User Visible Realm"')
def test_with_auth(self):
resp = self.get(self.url, req_hdrs={
2021-01-17 08:52:47 +03:00
'Authorization':
'Basic ' + base64.b64encode(b'myuser:mypass').decode('utf-8')})
2020-07-01 14:00:46 +03:00
status, hdrs, body = parse(resp)
self.assertContains(status, '200 OK')
2021-01-17 08:52:47 +03:00
self.assertEqual(hdrs["Accept-Ranges"], "bytes")
self.assertEqual(hdrs["Content-Length"], str(self.datalen))
self.assertEqual(hdrs["Content-Type"], "image/jpeg")
2020-07-01 14:00:46 +03:00
self.assertContains(hdrs["Server"], "darkhttpd/")
2021-01-17 08:55:09 +03:00
assert body == self.data, [self.url, resp, status, hdrs, body]
2021-01-17 08:52:47 +03:00
self.assertEqual(body, self.data)
2020-07-01 14:00:46 +03:00
2021-01-17 08:55:09 +03:00
def test_wrong_auth(self):
resp = self.get(self.url, req_hdrs={
'Authorization':
'Basic ' + base64.b64encode(b'myuser:wrongpass').decode('utf-8')})
status, hdrs, body = parse(resp)
self.assertContains(status, '401 Unauthorized')
self.assertEqual(hdrs['WWW-Authenticate'],
'Basic realm="User Visible Realm"')
self.assertContains(hdrs['Server'], 'darkhttpd/')
2020-07-01 14:00:46 +03:00
if __name__ == '__main__':
unittest.main()
# vim:set ts=4 sw=4 et: