1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
|
"""Test the pyzor.server module
"""
import io
import sys
import time
import logging
import unittest
try:
import socketserver as SocketServer
except ImportError:
import SocketServer
from datetime import datetime, timedelta
try:
from unittest.mock import patch
except ImportError:
from mock import patch
import pyzor.server
import pyzor.engines.common
class MockServer:
"""Mocks the pyzor.server.Server class"""
def __init__(self):
self.log = logging.getLogger("pyzord")
self.usage_log = logging.getLogger("pyzord-usage")
self.log.addHandler(logging.NullHandler())
self.usage_log.addHandler(logging.NullHandler())
self.forwarder = None
self.one_step = False
class MockDatagramRequestHandler:
"""Mock the SocketServer.DatagramRequestHand."""
def __init__(self, headers, database=None, acl=None, accounts=None):
"""Initiates an request handler and set's the data in `headers` as
the request. Also set's the database, acl and accounts for the
MockServer.
This will be set as base class for RequestHandler.
"""
self.rfile = io.BytesIO()
self.wfile = io.BytesIO()
for i, j in headers.items():
self.rfile.write(("%s: %s\n" % (i, j)).encode("utf8"))
self.rfile.seek(0)
self.packet = None
self.client_address = ["127.0.0.1"]
# Setup MockServer data
self.server = MockServer()
self.server.database = database
if acl:
self.server.acl = acl
else:
self.server.acl = {
pyzor.anonymous_user: (
"check",
"report",
"ping",
"pong",
"info",
"whitelist",
)
}
self.server.accounts = accounts
self.handle()
def handle(self):
pass
class RequestHandlerTest(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.real_drh = SocketServer.DatagramRequestHandler
SocketServer.DatagramRequestHandler = MockDatagramRequestHandler
pyzor.server.RequestHandler.__bases__ = (MockDatagramRequestHandler,)
# setup the basic values for request and response
self.request = {
"User": pyzor.anonymous_user,
"Time": str(int(time.time())),
"PV": str(pyzor.proto_version),
"Thread": "3597",
}
self.expected_response = {
"Code": "200",
"Diag": "OK",
"PV": str(pyzor.proto_version),
"Thread": "3597",
}
def tearDown(self):
unittest.TestCase.tearDown(self)
SocketServer.DatagramRequestHandler = self.real_drh
pyzor.server.RequestHandler.__bases__ = (self.real_drh,)
patch.stopall()
def check_response(self, handler):
"""Checks if the response from the handler is equal to
the expected response.
"""
handler.wfile.seek(0)
response = handler.wfile.read()
response = response.decode("utf8").replace("\n\n", "\n")
result = {}
try:
for line in response.splitlines():
key = line.split(":", 1)[0].strip()
value = line.split(":")[1].strip()
result[key] = value
except (IndexError, TypeError) as e:
self.fail("Error parsing %r: %s" % (response, e))
self.assertEqual(result, self.expected_response)
def timestamp(self, time_obj):
if not time_obj:
return 0
else:
return str(int(time.mktime(time_obj.timetuple())))
def test_ping(self):
"""Tests the ping command handler"""
self.request["Op"] = "ping"
handler = pyzor.server.RequestHandler(self.request)
self.check_response(handler)
def test_pong(self):
"""Tests the pong command handler"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {digest: pyzor.engines.common.Record(24, 42)}
self.request["Op"] = "pong"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.expected_response["Count"] = str(sys.maxsize)
self.expected_response["WL-Count"] = "0"
self.check_response(handler)
def test_check(self):
"""Tests the check command handler"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {digest: pyzor.engines.common.Record(24, 42)}
self.request["Op"] = "check"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.expected_response["Count"] = "24"
self.expected_response["WL-Count"] = "42"
self.check_response(handler)
def test_check_new(self):
"""Tests the check command handler with a new record"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {}
self.request["Op"] = "check"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.expected_response["Count"] = "0"
self.expected_response["WL-Count"] = "0"
self.check_response(handler)
def test_info(self):
"""Tests the info command handler"""
entered = datetime.now() - timedelta(days=10)
updated = datetime.now()
wl_entered = datetime.now() - timedelta(days=20)
wl_updated = datetime.now() - timedelta(days=2)
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {
digest: pyzor.engines.common.Record(
24, 42, entered, updated, wl_entered, wl_updated
)
}
self.request["Op"] = "info"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.expected_response["Count"] = "24"
self.expected_response["WL-Count"] = "42"
self.expected_response["Entered"] = self.timestamp(entered)
self.expected_response["Updated"] = self.timestamp(updated)
self.expected_response["WL-Entered"] = self.timestamp(wl_entered)
self.expected_response["WL-Updated"] = self.timestamp(wl_updated)
self.check_response(handler)
def test_info_new(self):
"""Tests the info command handler with a new record"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {}
self.request["Op"] = "info"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.expected_response["Count"] = "0"
self.expected_response["WL-Count"] = "0"
self.expected_response["Entered"] = "0"
self.expected_response["Updated"] = "0"
self.expected_response["WL-Entered"] = "0"
self.expected_response["WL-Updated"] = "0"
self.check_response(handler)
def test_report(self):
"""Tests the report command handler"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {digest: pyzor.engines.common.Record(24, 42)}
self.request["Op"] = "report"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.check_response(handler)
self.assertEqual(database[digest].r_count, 25)
def test_report_new(self):
"""Tests the report command handler with a new record"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {}
self.request["Op"] = "report"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.check_response(handler)
self.assertEqual(database[digest].r_count, 1)
def test_whitelist(self):
"""Tests the whitelist command handler"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {digest: pyzor.engines.common.Record(24, 42)}
self.request["Op"] = "whitelist"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.check_response(handler)
self.assertEqual(database[digest].wl_count, 43)
def test_whitelist_new(self):
"""Tests the whitelist command handler with a new record"""
digest = "2aedaac999d71421c9ee49b9d81f627a7bc570aa"
database = {}
self.request["Op"] = "whitelist"
self.request["Op-Digest"] = digest
handler = pyzor.server.RequestHandler(self.request, database)
self.check_response(handler)
self.assertEqual(database[digest].wl_count, 1)
def test_handle_no_version(self):
"""Tests handling an request with no version specified"""
self.request["Op"] = "ping"
del self.request["PV"]
handler = pyzor.server.RequestHandler(self.request)
self.expected_response["Code"] = "400"
self.expected_response["Diag"] = "Bad request"
self.check_response(handler)
def test_handle_unsupported_version(self):
"""Tests handling an request with an unsupported version specified"""
self.request["Op"] = "ping"
self.request["PV"] = str(pyzor.proto_version + 2)
handler = pyzor.server.RequestHandler(self.request)
self.expected_response["Code"] = "505"
self.expected_response["Diag"] = "Version Not Supported"
self.check_response(handler)
def test_handle_not_implemented(self):
"""Tests handling an request with an unimplemented command"""
self.request["Op"] = "notimplemented"
acl = {pyzor.anonymous_user: "notimplemented"}
handler = pyzor.server.RequestHandler(self.request, acl=acl)
self.expected_response["Code"] = "501"
self.expected_response["Diag"] = "Not implemented"
self.check_response(handler)
def test_handle_unauthorized(self):
"""Tests handling an request with an unauthorized command"""
self.request["Op"] = "report"
acl = {pyzor.anonymous_user: ("ping", "check")}
handler = pyzor.server.RequestHandler(self.request, acl=acl)
self.expected_response["Code"] = "403"
self.expected_response["Diag"] = "Forbidden"
self.check_response(handler)
def test_handle_account(self):
"""Tests handling an request where user is not anonymous"""
self.request["Op"] = "ping"
self.request["User"] = "testuser"
acl = {"testuser": ("ping", "check")}
accounts = {"testuser": "testkey"}
mock_vs = lambda x, y: None
real_vs = pyzor.account.verify_signature
pyzor.account.verify_signature = mock_vs
try:
handler = pyzor.server.RequestHandler(
self.request, acl=acl, accounts=accounts
)
self.check_response(handler)
finally:
pyzor.account.verify_signature = real_vs
def test_handle_unknown_account(self):
"""Tests handling an request where user is unkwown"""
self.request["Op"] = "ping"
self.request["User"] = "testuser"
acl = {"testuser": ("ping", "check")}
accounts = {}
self.expected_response["Code"] = "401"
self.expected_response["Diag"] = "Unauthorized"
def mock_vs(x, y):
pass
real_vs = pyzor.account.verify_signature
pyzor.account.verify_signature = mock_vs
try:
handler = pyzor.server.RequestHandler(
self.request, acl=acl, accounts=accounts
)
self.check_response(handler)
finally:
pyzor.account.verify_signature = real_vs
def test_handle_invalid_signature(self):
"""Tests handling an request where user key is invalid"""
self.request["Op"] = "ping"
self.request["User"] = "testuser"
acl = {"testuser": ("ping", "check")}
accounts = {"testuser": ("ping", "check")}
self.expected_response["Code"] = "401"
self.expected_response["Diag"] = "Unauthorized"
def mock_vs(x, y):
raise pyzor.SignatureError("Invalid signature.")
real_vs = pyzor.account.verify_signature
pyzor.account.verify_signature = mock_vs
try:
handler = pyzor.server.RequestHandler(
self.request, acl=acl, accounts=accounts
)
self.check_response(handler)
finally:
pyzor.account.verify_signature = real_vs
def test_invalid_pv(self):
self.request["Op"] = "ping"
self.request["PV"] = "ab2.13"
handler = pyzor.server.RequestHandler(self.request)
self.expected_response["Code"] = "400"
self.expected_response["Diag"] = "Bad request"
self.check_response(handler)
def test_uncaught_exception(self):
patch(
"pyzor.server.RequestHandler._really_handle", side_effect=Exception("test")
).start()
self.request["Op"] = "ping"
handler = pyzor.server.RequestHandler(self.request)
self.expected_response["Code"] = "500"
self.expected_response["Diag"] = "Internal Server Error"
del self.expected_response["Thread"]
self.check_response(handler)
class ServerTest(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.mock_config = patch("pyzor.config").start()
def tearDown(self):
unittest.TestCase.tearDown(self)
patch.stopall()
def test_server(self):
pyzor.server.Server(("127.0.0.1", 24441), {}, "passwd_fn", "access_fn", None)
def suite():
"""Gather all the tests from this module in a test suite."""
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(RequestHandlerTest))
test_suite.addTest(unittest.makeSuite(ServerTest))
return test_suite
if __name__ == "__main__":
unittest.main()
|