requestlog.py (1539B)
1 # This Source Code Form is subject to the terms of the Mozilla Public 2 # License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 # You can obtain one at http://mozilla.org/MPL/2.0/. 4 5 import os 6 from urllib.request import urlopen 7 8 import mozhttpd 9 import mozunit 10 import pytest 11 12 13 def log_requests(enabled): 14 """Decorator to change the log_requests parameter for MozHttpd.""" 15 param_id = "enabled" if enabled else "disabled" 16 return pytest.mark.parametrize("log_requests", [enabled], ids=[param_id]) 17 18 19 @pytest.fixture(name="docroot") 20 def fixture_docroot(): 21 """Return a docroot path.""" 22 return os.path.dirname(os.path.abspath(__file__)) 23 24 25 @pytest.fixture(name="request_log") 26 def fixture_request_log(docroot, log_requests): 27 """Yields the request log of a started MozHttpd server.""" 28 httpd = mozhttpd.MozHttpd( 29 port=0, 30 docroot=docroot, 31 log_requests=log_requests, 32 ) 33 httpd.start(block=False) 34 35 url = "http://{host}:{port}/".format( 36 host="127.0.0.1", 37 port=httpd.httpd.server_port, 38 ) 39 f = urlopen(url) 40 f.read() 41 42 yield httpd.request_log 43 44 httpd.stop() 45 46 47 @log_requests(True) 48 def test_logging_enabled(request_log): 49 assert len(request_log) == 1 50 log_entry = request_log[0] 51 assert log_entry["method"] == "GET" 52 assert log_entry["path"] == "/" 53 assert type(log_entry["time"]) is float 54 55 56 @log_requests(False) 57 def test_logging_disabled(request_log): 58 assert len(request_log) == 0 59 60 61 if __name__ == "__main__": 62 mozunit.main()