def test_healthcheck_queued(self): type(self.mock_redir).log_enabled = True type(self.mock_request).queued = 1 if sys.version_info[0] < 3: type(self.mock_request).uri = '/vault-redirector-health' type(self.mock_request).path = '/vault-redirector-health' expected = 'foobar' expected_msg = 'OK' else: # in py3 these are byte literals type(self.mock_request).uri = b'/vault-redirector-health' type(self.mock_request).path = b'/vault-redirector-health' expected = b'foobar' expected_msg = b'OK' with patch('%s.logger' % pbm) as mock_logger: with patch('%s.VaultRedirectorSite.status_response' % pbm) as mock_status: mock_status.return_value = 'foobar' resp = self.cls.healthcheck(self.mock_request) assert self.mock_request.mock_calls == [ call.setResponseCode(200, message=expected_msg), call.setHeader("Content-Type", "application/json") ] assert resp == expected assert mock_logger.mock_calls == [ call.info( 'RESPOND %d for %s%s request for /vault-redirector-health' ' from %s:%s', 200, 'QUEUED ', 'GET', '1.2.3.4', 12345) ]
def test_healthcheck_no_active_log_disabled(self): type(self.mock_redir).active_node_ip_port = None type(self.mock_redir).log_enabled = False if sys.version_info[0] < 3: type(self.mock_request).uri = '/vault-redirector-health' type(self.mock_request).path = '/vault-redirector-health' expected = 'foobar' expected_msg = 'No Active Vault' else: # in py3 these are byte literals type(self.mock_request).uri = b'/vault-redirector-health' type(self.mock_request).path = b'/vault-redirector-health' expected = b'foobar' expected_msg = b'No Active Vault' with patch('%s.logger' % pbm) as mock_logger: with patch('%s.VaultRedirectorSite.status_response' % pbm) as mock_status: mock_status.return_value = 'foobar' resp = self.cls.healthcheck(self.mock_request) assert self.mock_request.mock_calls == [ call.setResponseCode(503, message=expected_msg), call.setHeader("Content-Type", "application/json") ] assert resp == expected assert mock_logger.mock_calls == []
def test_render(self): expected_location = 'http://mynode:1234/foo/bar' expected_server = 'vault-redirector/%s/TwistedWeb/16.1.0' % _VERSION if sys.version_info[0] < 3: type(self.mock_request).uri = '/foo/bar' type(self.mock_request).path = '/foo/bar' else: # in py3 these are byte literals type(self.mock_request).uri = b'/foo/bar' type(self.mock_request).path = b'/foo/bar' self.mock_request.reset_mock() with patch('%s.logger' % pbm) as mock_logger: resp = self.cls.render(self.mock_request) assert self.mock_request.mock_calls == [ call.setHeader('server', expected_server), call.setResponseCode(307), call.setHeader('Location', expected_location), call.setHeader("Content-Type", "text/html; charset=UTF-8") ] assert resp == self.empty_resp assert mock_logger.mock_calls == [ call.info('RESPOND 307 to %s for %s%s request for %s from %s:%s', expected_location, '', 'GET', '/foo/bar', '1.2.3.4', 12345) ]
def test_update(self): req_data = { 'host_id': 'myhostid', 'sensors': { 'sensor1': { 'type': 's1type', 'value': 12.345, 'alias': 's1alias', 'extra': 'extraS1' } } } req_json = json.dumps(req_data) mock_req = MagicMock(spec_set=Request) type(mock_req).responseHeaders = Mock() mock_req.content.getvalue.return_value = req_json type(mock_req).client = Mock(host='myhost') with patch('%s.logger' % pbm, autospec=True) as mock_logger: with patch('%s._parse_json_request' % pb) as mock_parse: with patch('%s.update_sensor' % pbm, autospec=True) as mock_upd: mock_upd.return_value = 'myid' mock_parse.return_value = req_data res = self.cls.update(None, mock_req) assert res.result == '{"ids": ["myid"], "status": "ok"}' assert mock_parse.mock_calls == [call(mock_req)] assert mock_req.mock_calls == [call.setResponseCode(201)] assert mock_logger.mock_calls == [ call.debug( 'Received sensor update request from %s with content: %s', 'myhost', req_data), call.debug('update_sensor() return value: %s', 'myid') ]
def test_status(self): mock_req = Mock(spec_set=Request) mock_headers = Mock() type(mock_req).responseHeaders = mock_headers mock_coll = Mock(spec_set=Collection) mock_coll.find.return_value = [] mock_dbconn = Mock() cls = TestClass(Mock(), Mock(), mock_dbconn, []) cls.dbconn = mock_dbconn with patch('%s.get_collection' % pbm, autospec=True) as mock_get_coll: with patch('%s.returnValue' % pbm) as mock_retval: with patch('%s.logger' % pbm, autospec=True) as mock_logger: mock_get_coll.return_value = mock_coll cls.status(cls, mock_req) expected = json.dumps({ 'status': True, 'dependencies': {'mongodb': True} }, sort_keys=True) assert mock_headers.mock_calls == [ call.addRawHeader( b"content-type", b"application/json") ] assert mock_coll.mock_calls == [call.find(limit=1)] assert mock_req.mock_calls == [call.setResponseCode(200)] assert mock_get_coll.mock_calls == [call(mock_dbconn, COLL_SENSORS)] # need to mock out get_collection and the find method on its result # also mock the request object and assert on calls assert mock_retval.mock_calls == [ call(expected) ] assert mock_logger.mock_calls == []
def test_update(self): req_data = { 'host_id': 'myhostid', 'sensors': { 'sensor1': { 'type': 's1type', 'value': 12.345, 'alias': 's1alias', 'extra': 'extraS1' } } } req_json = json.dumps(req_data) mock_req = MagicMock(spec_set=Request) type(mock_req).responseHeaders = Mock() mock_req.content.getvalue.return_value = req_json type(mock_req).client = Mock(host='myhost') with patch('%s.logger' % pbm, autospec=True) as mock_logger: with patch('%s._parse_json_request' % pb) as mock_parse: with patch('%s.update_sensor' % pbm, autospec=True) as mock_upd: mock_upd.return_value = 'myid' mock_parse.return_value = req_data res = self.cls.update(None, mock_req) assert res.result == '{"ids": ["myid"], "status": "ok"}' assert mock_parse.mock_calls == [call(mock_req)] assert mock_req.mock_calls == [call.setResponseCode(201)] assert mock_logger.mock_calls == [ call.debug( 'Received sensor update request from %s with content: %s', 'myhost', req_data ), call.debug('update_sensor() return value: %s', 'myid') ]
def _make_request( self, method, postpath, reqbody, resreadsreq, rescode, resbody): m_request = MagicMock(name='Request') m_request.method = method m_request.postpath = postpath if reqbody is None: readrv = '' elif reqbody == 'mangled JSON': readrv = reqbody else: readrv = json.dumps(reqbody, indent=2) m_request.content.read.return_value = readrv r = self.tar.render(m_request) self.assertEqual(r, server.NOT_DONE_YET) expected = [ call.setResponseCode(rescode), call.setHeader('Content-Type', 'application/json'), call.write(json.dumps(resbody, indent=2)), call.finish(), ] if resreadsreq: expected.insert(0, call.content.read()) check_mock(self, m_request, expected)
def test_healthcheck_no_active_log_disabled(self): type(self.mock_redir).active_node_ip_port = None type(self.mock_redir).log_enabled = False if sys.version_info[0] < 3: type(self.mock_request).uri = '/vault-redirector-health' type(self.mock_request).path = '/vault-redirector-health' expected = 'foobar' expected_msg = 'No Active Vault' else: # in py3 these are byte literals type(self.mock_request).uri = b'/vault-redirector-health' type(self.mock_request).path = b'/vault-redirector-health' expected = b'foobar' expected_msg = b'No Active Vault' with patch('%s.logger' % pbm) as mock_logger: with patch('%s.VaultRedirectorSite.status_response' % pbm ) as mock_status: mock_status.return_value = 'foobar' resp = self.cls.healthcheck(self.mock_request) assert self.mock_request.mock_calls == [ call.setResponseCode(503, message=expected_msg), call.setHeader("Content-Type", "application/json") ] assert resp == expected assert mock_logger.mock_calls == []
def test_healthcheck_queued(self): type(self.mock_redir).log_enabled = True type(self.mock_request).queued = 1 if sys.version_info[0] < 3: type(self.mock_request).uri = '/vault-redirector-health' type(self.mock_request).path = '/vault-redirector-health' expected = 'foobar' expected_msg = 'OK' else: # in py3 these are byte literals type(self.mock_request).uri = b'/vault-redirector-health' type(self.mock_request).path = b'/vault-redirector-health' expected = b'foobar' expected_msg = b'OK' with patch('%s.logger' % pbm) as mock_logger: with patch('%s.VaultRedirectorSite.status_response' % pbm ) as mock_status: mock_status.return_value = 'foobar' resp = self.cls.healthcheck(self.mock_request) assert self.mock_request.mock_calls == [ call.setResponseCode(200, message=expected_msg), call.setHeader("Content-Type", "application/json") ] assert resp == expected assert mock_logger.mock_calls == [ call.info('RESPOND %d for %s%s request for /vault-redirector-health' ' from %s:%s', 200, 'QUEUED ', 'GET', '1.2.3.4', 12345) ]
def test_status(self): mock_req = Mock(spec_set=Request) mock_headers = Mock() type(mock_req).responseHeaders = mock_headers mock_coll = Mock(spec_set=Collection) mock_coll.find.return_value = [] mock_dbconn = Mock() cls = TestClass(Mock(), Mock(), mock_dbconn, []) cls.dbconn = mock_dbconn with patch('%s.get_collection' % pbm, autospec=True) as mock_get_coll: with patch('%s.returnValue' % pbm) as mock_retval: with patch('%s.logger' % pbm, autospec=True) as mock_logger: mock_get_coll.return_value = mock_coll cls.status(cls, mock_req) expected = json.dumps( { 'status': True, 'dependencies': { 'mongodb': True } }, sort_keys=True) assert mock_headers.mock_calls == [ call.addRawHeader(b"content-type", b"application/json") ] assert mock_coll.mock_calls == [call.find(limit=1)] assert mock_req.mock_calls == [call.setResponseCode(200)] assert mock_get_coll.mock_calls == [call(mock_dbconn, COLL_SENSORS)] # need to mock out get_collection and the find method on its result # also mock the request object and assert on calls assert mock_retval.mock_calls == [call(expected)] assert mock_logger.mock_calls == []
def test_signed_malformed_JSON(self): m_request = self.make_mock() self.res._handle_signed_message(m_request, '%@ NOT JSON @%') self.assert_calls_equal( self.m_loghandler, [call.handle(ArgIsLogRecord(levelname='ERROR'))]) self.assert_calls_equal( m_request, [call.setResponseCode(400, 'MALFORMED')])
def test_render_GET(self): r = self.res.render_GET(self.m_request) self.assertEqual(NOT_DONE_YET, r) self.assert_calls_equal( self.m_handle_event, []) self.assert_calls_equal( self.m_request, [call.setResponseCode(403, 'FORBIDDEN'), call.finish()])
def test_render_GET(self): m_request = self._setup_mock_request('fake request type', []) r = self.res.render_GET(m_request) self.assertEqual(NOT_DONE_YET, r) self.assert_calls_equal( self.m_handle_push_tag, []) self.assert_calls_equal( m_request, [call.setResponseCode(403, 'FORBIDDEN'), call.finish()])
def test_render_log_disabled(self): expected_location = 'http://mynode:1234/foo/bar' expected_server = 'vault-redirector/%s/TwistedWeb/16.1.0' % _VERSION type(self.mock_request).uri = '/foo/bar' type(self.mock_request).path = '/foo/bar' self.mock_request.reset_mock() type(self.mock_redir).log_enabled = False with patch('%s.logger' % pbm) as mock_logger: resp = self.cls.render(self.mock_request) assert self.mock_request.mock_calls == [ call.setHeader('server', expected_server), call.setResponseCode(307), call.setHeader('Location', expected_location), call.setHeader("Content-Type", "text/html; charset=UTF-8") ] assert resp == self.empty_resp assert mock_logger.mock_calls == []
def test_render_POST_ping_tampered(self): tweakedmessage = self.pingmessage.copy() tweakedmessage['hook_id'] += 1 self.m_request.content.getvalue.return_value = json.dumps(tweakedmessage) r = self.res.render_POST(self.m_request) self.assertEqual(NOT_DONE_YET, r) self.assert_calls_equal( self.m_request, [call.getHeader('X-Hub-Signature'), call.content.getvalue(), call.setResponseCode(403, 'FORBIDDEN'), call.finish()]) self.assert_calls_equal( self.m_loghandler, [call.handle(ArgIsLogRecord(levelname='WARNING'))])
def test_render_POST_ping(self): r = self.res.render_POST(self.m_request) self.assertEqual(NOT_DONE_YET, r) self.assert_calls_equal( self.m_request, [call.getHeader('X-Hub-Signature'), call.content.getvalue(), call.getHeader('X-Github-Event'), call.getHeader('X-Github-Delivery'), call.setResponseCode(200, 'OK'), call.finish()]) self.assert_calls_equal( self.m_handle_event, [call('a fake unique id', 'ping', self.pingmessage)]) self.assert_calls_equal( self.m_loghandler, [])
def test_render_POST_unhandled_event_type(self): m_request = self._setup_mock_request('unknown event type', []) r = self.res.render_POST(m_request) self.assertEqual(NOT_DONE_YET, r) self.assert_calls_equal( m_request, [call.getHeader('X-Hub-Signature'), call.content.getvalue(), call.getHeader('X-Github-Event'), call.getHeader('X-Github-Delivery'), call.setResponseCode(400, 'Event Not Supported'), call.finish()]) self.assert_calls_equal( self.m_loghandler, [call.handle( ArgIsLogRecord( levelname='INFO', msg='Unhandled github %r event %r.'))])
def test_render_POST_ping_tampered(self): m_request = self._setup_mock_request('ping', self.pingmessage) tweakedmessage = self.pingmessage.copy() tweakedmessage['hook_id'] += 1 m_request.content.getvalue.return_value = \ json.dumps(tweakedmessage) r = self.res.render_POST(m_request) self.assertEqual(NOT_DONE_YET, r) self.assert_calls_equal( m_request, [call.getHeader('X-Hub-Signature'), call.content.getvalue(), call.setResponseCode(403, 'FORBIDDEN'), call.finish()]) self.assert_calls_equal( self.m_loghandler, [call.handle(ArgIsLogRecord(levelname='WARNING'))])
def test_render_POST_ping(self): m_request = self._setup_mock_request('ping', self.pingmessage) r = self.res.render_POST(m_request) self.assertEqual(NOT_DONE_YET, r) self.assert_calls_equal( m_request, [call.getHeader('X-Hub-Signature'), call.content.getvalue(), call.getHeader('X-Github-Event'), call.getHeader('X-Github-Delivery'), call.setResponseCode(200, 'OK'), call.finish()]) # Pings do not reach the push handler: self.assert_calls_equal( self.m_handle_push_tag, []) self.assert_calls_equal( self.m_loghandler, [])