def test_pushover_send_error(self): expected = { 'user': '******', 'timestamp': 1423807323, 'title': 'piface input change', 'token': 'aB5D3uoGZuVQg4QMJMm8817sJFn7Up', 'message': 'mymsg', 'priority': 0 } resp_json = { 'status': 0, 'user': '******', 'errors': ['user identifier is invalid'] } with patch('%s.requests.post' % pbm) as mock_post: with patch('%s.logger' % pbm) as mock_logger: type(mock_post.return_value).status_code = 401 mock_post.return_value.json.return_value = resp_json self.cls._pushover_send('mymsg', datetime(2015, 2, 13, 1, 2, 3, 123456)) assert mock_post.mock_calls == [ call('https://api.pushover.net/1/messages.json', data=expected), call().json() ] assert mock_logger.mock_calls == [ call.debug("Sending POST to Pushover; data: %s", expected), call.critical("POST to Pushover returned %s", 401), call.critical("POST to Pushover returned bad status: %s", resp_json) ]
def test_init_no_sensors(self): with patch('%s.logger' % pbm, autospec=True) as mock_logger: with patch.multiple( pb, autospec=True, find_host_id=DEFAULT, discover_engine=DEFAULT, discover_sensors=DEFAULT, ) as mocks: with patch('%s._list_classes' % pbm, autospec=True) as mock_list: mocks['find_host_id'].return_value = 'myhostid' mocks['discover_engine'].return_value = ( 'foo.bar.baz', 1234 ) with pytest.raises(SystemExit) as excinfo: SensorDaemon() assert mock_logger.mock_calls == [ call.warning('This machine running with host_id %s', 'myhostid'), call.critical('ERROR - no sensors discovered.') ] assert mocks['find_host_id'].call_count == 1 assert mocks['discover_engine'].call_count == 1 assert mocks['discover_sensors'].call_count == 1 assert excinfo.value.code == 1 assert mock_list.mock_calls == []
def test_init_no_sensors(self): with patch('%s.logger' % pbm, autospec=True) as mock_logger: with patch.multiple( pb, autospec=True, find_host_id=DEFAULT, discover_engine=DEFAULT, discover_sensors=DEFAULT, ) as mocks: with patch('%s._list_classes' % pbm, autospec=True) as mock_list: mocks['find_host_id'].return_value = 'myhostid' mocks['discover_engine'].return_value = ('foo.bar.baz', 1234) with pytest.raises(SystemExit) as excinfo: SensorDaemon() assert mock_logger.mock_calls == [ call.warning('This machine running with host_id %s', 'myhostid'), call.critical('ERROR - no sensors discovered.') ] assert mocks['find_host_id'].call_count == 1 assert mocks['discover_engine'].call_count == 1 assert mocks['discover_sensors'].call_count == 1 assert excinfo.value.code == 1 assert mock_list.mock_calls == []
def test_run_error(self): self.cls.reactor = Mock(spec_set=reactor) with patch.multiple(pbm, logger=DEFAULT, Site=DEFAULT, LoopingCall=DEFAULT, VaultRedirectorSite=DEFAULT) as mod_mocks: with patch.multiple(pb, get_active_node=DEFAULT, run_reactor=DEFAULT, listentcp=DEFAULT, add_update_loop=DEFAULT) as cls_mocks: cls_mocks['get_active_node'].return_value = None with pytest.raises(SystemExit) as excinfo: self.cls.run() assert excinfo.value.code == 3 assert mod_mocks['logger'].mock_calls == [ call.critical("ERROR: Could not get active vault node from " "Consul. Exiting.") ] assert mod_mocks['VaultRedirectorSite'].mock_calls == [] assert mod_mocks['Site'].mock_calls == [] assert self.cls.reactor.mock_calls == [] assert cls_mocks['run_reactor'].mock_calls == [] assert mod_mocks['LoopingCall'].mock_calls == []
def test_run_error(self): self.cls.reactor = Mock(spec_set=reactor) with patch.multiple( pbm, logger=DEFAULT, Site=DEFAULT, LoopingCall=DEFAULT, VaultRedirectorSite=DEFAULT ) as mod_mocks: with patch.multiple( pb, get_active_node=DEFAULT, run_reactor=DEFAULT, listentcp=DEFAULT, add_update_loop=DEFAULT ) as cls_mocks: cls_mocks['get_active_node'].return_value = None with pytest.raises(SystemExit) as excinfo: self.cls.run() assert excinfo.value.code == 3 assert mod_mocks['logger'].mock_calls == [ call.critical("ERROR: Could not get active vault node from " "Consul. Exiting.") ] assert mod_mocks['VaultRedirectorSite'].mock_calls == [] assert mod_mocks['Site'].mock_calls == [] assert self.cls.reactor.mock_calls == [] assert cls_mocks['run_reactor'].mock_calls == [] assert mod_mocks['LoopingCall'].mock_calls == []
def test_pushover_no_status(self): expected = { 'user': '******', 'timestamp': 1423807323, 'title': 'piface input change', 'token': 'aB5D3uoGZuVQg4QMJMm8817sJFn7Up', 'message': 'mymsg', 'priority': 0 } resp_json = { 'foo': 'bar' } with patch('%s.requests.post' % pbm) as mock_post: with patch('%s.logger' % pbm) as mock_logger: type(mock_post.return_value).status_code = 200 mock_post.return_value.json.return_value = resp_json self.cls._pushover_send('mymsg', datetime(2015, 2, 13, 1, 2, 3, 123456)) assert mock_post.mock_calls == [ call('https://api.pushover.net/1/messages.json', data=expected), call().json() ] assert mock_logger.mock_calls == [ call.debug("Sending POST to Pushover; data: %s", expected), call.critical("POST to Pushover - response lacks status element") ]
def test_pushover_cant_decode_json(self): expected = { 'user': '******', 'timestamp': 1423807323, 'title': 'piface input change', 'token': 'aB5D3uoGZuVQg4QMJMm8817sJFn7Up', 'message': 'mymsg', 'priority': 0 } def se_exc(): raise Exception("foo") with patch('%s.requests.post' % pbm) as mock_post: with patch('%s.logger' % pbm) as mock_logger: type(mock_post.return_value).status_code = 200 mock_post.return_value.json.side_effect = se_exc self.cls._pushover_send('mymsg', datetime(2015, 2, 13, 1, 2, 3, 123456)) assert mock_post.mock_calls == [ call('https://api.pushover.net/1/messages.json', data=expected), call().json() ] assert mock_logger.mock_calls == [ call.debug("Sending POST to Pushover; data: %s", expected), call.critical("POST to Pushover - response could not be decoded") ]
def test_send_error(self): dt = datetime(2015, 2, 13, 1, 2, 3, 123456) expected = { 'timestamp': 1423807323, 'datetime_iso8601': '2015-02-13T01:02:03', 'pin_num': 2, 'pin_name': 'pin2', 'state': 0, 'state_name': 'state0name', } with patch('%s.requests.post' % pbm) as mock_post: with patch('%s.requests.get' % pbm) as mock_get: with patch('%s.logger' % pbm) as mock_logger: type(mock_post.return_value).status_code = 401 type(mock_get.return_value).status_code = 401 self.cls.send(dt, 2, 0, 'pin2', 'state0name') assert mock_get.mock_calls == [] assert mock_post.mock_calls == [ call('myurl', data=expected, timeout=10) ] assert mock_logger.mock_calls == [ call.debug('POSTing to %s: %s', 'myurl', expected), call.critical("Request to %s returned status code %s", 'myurl', 401) ]
def test_validate_fail(self): def se_run(*args, **kwargs): print(args) if args[0] == 'version': return "Terraform v1.2.3\nfoo\n" if args[0] == 'validate': raise Exception() # validate is called in __init__; we can't easily patch and re-call with patch('%s._run_tf' % pb) as mock_run: mock_run.side_effect = se_run with patch('%s.logger' % pbm, autospec=True) as mock_logger: with pytest.raises(Exception) as excinfo: TerraformRunner(self.mock_config(), 'terraform-bin') assert exc_msg(excinfo.value) == 'ERROR: Terraform config validation ' \ 'failed.' assert mock_run.mock_calls == [ call('version'), call('validate', ['.']) ] assert mock_logger.mock_calls == [ call.debug('Terraform version: %s', (1, 2, 3)), call.critical("Terraform config validation failed. This is almost " "certainly a bug in webhook2lambda2sqs; please " "re-run with '-vv' and open a bug at <https://" "github.com/jantman/webhook2lambda2sqs/issues>") ]
def test_connect_exception(self): def se_exc(*args, **kwargs): raise Exception('foo') with patch.multiple( pbm, autospec=True, logger=DEFAULT, setup_mongodb=DEFAULT, ConnectionPool=DEFAULT, ) as mocks: mocks['ConnectionPool'].side_effect = se_exc with pytest.raises(SystemExit) as excinfo: connect_mongodb('myhost', 1234) assert excinfo.value.code == 2 assert mocks['setup_mongodb'].mock_calls == [call('myhost', 1234)] assert mocks['ConnectionPool'].mock_calls == [ call(uri='mongodb://myhost:1234') ] assert mocks['logger'].mock_calls == [ call.info('Connecting to MongoDB via txmongo at %s', 'mongodb://myhost:1234'), call.critical('Error connecting to MongoDB at %s', 'mongodb://myhost:1234', exc_info=1) ]
def test_get_active_node_none(self): get_json = testdata.test_get_active_node_none with patch('%s.requests.get' % pbm) as mock_get: mock_get.return_value.json.return_value = get_json with patch('%s.logger' % pbm) as mock_logger: res = self.cls.get_active_node() url = 'http://consul:123/v1/health/service/vault' assert mock_get.mock_calls[0] == call(url) assert mock_logger.mock_calls == [ call.debug('Polling active node from: %s', url), call.critical('NO vault services found with health check passing') ] assert res is None
def test_create_export_printlist_duplicate_sub_location_suffixes(mock_latlons, mock_MessagebarAndLog): mock_latlons.return_value = {u'1': (u'lat1', u'lon1')} tables_columns = OrderedDict([(u'testtable', (u'col1', u'col2'))]) stored_settings = [(0, ((u'parameter_list', [u'par1;type1;hint1']), (u'sublocation_suffix', u'proj.group'), (u'location_suffix', u'proj'))), (1, ((u'parameter_list', [u'par2;type2;hint2']), (u'sublocation_suffix', u'proj.group'), (u'location_suffix', u'proj')))] mock_connect = MagicMock() parameter_groups = ExportToFieldLogger.create_parameter_groups_using_stored_settings(stored_settings, mock_connect) parameter_groups[0]._obsid_list.addItems([u'1']) parameter_groups[1]._obsid_list.addItems([u'1']) printlist = ExportToFieldLogger.create_export_printlist(parameter_groups) test_string = printlist assert test_string is None assert call.critical(bar_msg=u'Critical: Combination of obsid, locationsuffix and sublocation suffix must be unique') in mock_MessagebarAndLog.mock_calls
def test_run_tf_fail(self): expected_args = 'terraform-bin plan config foo bar' with patch('%s._validate' % pb): cls = TerraformRunner(self.mock_config(), 'terraform-bin') with patch('%s.logger' % pbm, autospec=True) as mock_logger: with patch('%s.run_cmd' % pbm, autospec=True) as mock_run: mock_run.return_value = ('myoutput', 5) with pytest.raises(Exception) as excinfo: cls._run_tf('plan', cmd_args=['config', 'foo', 'bar'], stream=True) assert exc_msg(excinfo.value) == 'terraform plan failed' assert mock_run.mock_calls == [ call(expected_args, stream=True) ] assert mock_logger.mock_calls == [ call.info('Running terraform command: %s', expected_args), call.critical('Terraform command (%s) failed with exit code ' '%d:\n%s', expected_args, 5, 'myoutput') ]
def test_setup_mongodb_exception(self): def se_exc(*args, **kwargs): raise Exception('foo') with patch('%s.MongoClient' % pbm, autospec=True) as mock_client: with patch('%s.logger' % pbm, autospec=True) as mock_logger: mock_client.side_effect = se_exc with pytest.raises(SystemExit) as excinfo: setup_mongodb('h', 12) assert excinfo.value.code == 1 assert mock_client.mock_calls == [ call('h', 12, connect=True, connectTimeoutMS=5000, serverSelectionTimeoutMS=5000, socketTimeoutMS=5000, waitQueueTimeoutMS=5000) ] assert mock_logger.mock_calls == [ call.debug('Connecting to MongoDB via pymongo at %s:%s', 'h', 12), call.critical('Error connecting to MongoDB at %s:%s', 'h', 12, exc_info=1) ]
def test_pushover_no_status(self): expected = { 'user': '******', 'timestamp': 1423807323, 'title': 'piface input change', 'token': 'aB5D3uoGZuVQg4QMJMm8817sJFn7Up', 'message': 'mymsg', 'priority': 0 } resp_json = {'foo': 'bar'} with patch('%s.requests.post' % pbm) as mock_post: with patch('%s.logger' % pbm) as mock_logger: type(mock_post.return_value).status_code = 200 mock_post.return_value.json.return_value = resp_json self.cls._pushover_send('mymsg', datetime(2015, 2, 13, 1, 2, 3, 123456)) assert mock_post.mock_calls == [ call('https://api.pushover.net/1/messages.json', data=expected), call().json() ] assert mock_logger.mock_calls == [ call.debug("Sending POST to Pushover; data: %s", expected), call.critical("POST to Pushover - response lacks status element") ]