def setup():
"""setup temporary env for tests"""
global tmp
tmp = tempfile.mkdtemp()
patchers[:] = [
patch.dict(os.environ, {
'HOME': tmp,
# Let tests work with --user install when HOME is changed:
'PYTHONPATH': os.pathsep.join(sys.path),
}),
]
for p in patchers:
p.start()
# install IPython in the temp home:
install(user=True)
python类dict()的实例源码
def test_format_descr_wo_notes(self):
"""
Tests the _format_description method when the alert has no notes.
"""
self.mock_settings['INCLUDE_FULL_DESCRIPTION'] = False
with patch('ambassador.transport.Transport.get_key_cert',
return_value=self.mock_cert):
with patch('platforms.jira.handlers.jira.JIRA',
return_value=self.mock_auth):
with patch.dict('platforms.jira.handlers.settings.JIRA',
self.mock_settings):
handler_w_user = IssueAPI(endpoint=self.endpoint,
user=self.user)
alert = Alert.objects.get(pk=2)
actual = handler_w_user._format_description(alert)
expected = ''
self.assertEqual(actual, expected)
def test_allowed_file(self):
"""
Tests the get_file_path function for an allowed file type.
"""
self.msg.attach(self.image)
attachment = get_first_attachment(self.msg)
mock_uuid = Mock()
mock_uuid.hex = self.uuid
with patch('sifter.mailsifter.attachments.uuid.uuid4',
return_value=mock_uuid):
with patch.dict('sifter.mailsifter.attachments.settings.MAILSIFTER',
self.mock_mailsifter_settings):
actual = attachments.get_file_path(attachment, self.company)
expected = '%s/test-attachments/%s.jpeg' \
% (self.company.uuid.hex, self.uuid)
self.assertEqual(actual, expected)
def test_unallowed_file(self):
"""
Tests the get_file_path function for an unallowed file type.
"""
self.mock_mailsifter_settings['ALLOWED_EMAIL_ATTACHMENTS'] = ('application/java',)
with patch.dict('sifter.mailsifter.accessors.settings.MAILSIFTER',
self.mock_mailsifter_settings):
self.msg.attach(self.java)
attachment = get_first_attachment(self.msg)
with patch('sifter.mailsifter.attachments.settings',
return_value=self.mock_settings):
with LogCapture() as log_capture:
actual = attachments.get_file_path(attachment)
expected = None
self.assertEqual(actual, expected)
msg = 'The attachment %s is not an allowed file type' \
% self.java_file
log_capture.check(
('sifter.mailsifter.attachments', 'WARNING', msg),
)
def test_no_file_path(self):
"""
Tests the save_attachment function.
"""
mock_settings_1 = {
'ALLOWED_EMAIL_ATTACHMENTS': ('application/java',)
}
with patch.dict('sifter.mailsifter.accessors.settings.MAILSIFTER',
mock_settings_1):
self.msg.attach(self.java)
attachment = get_first_attachment(self.msg)
with patch('sifter.mailsifter.attachments.settings',
self.mock_settings):
with LogCapture() as log_capture:
actual = attachments.save_attachment(attachment)
expected = None
self.assertEqual(actual, expected)
msg = 'The attachment %s is not an allowed file type' \
% self.java_file
log_capture.check(
('sifter.mailsifter.attachments', 'WARNING', msg),
)
def test_match_with_default(self):
"""
Tests the process_email receiver for an email that matches an
existing MailChute.
"""
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'critical alert'
mock_config = {
'DEFAULT_MUNGER': 'default_mail',
'DEFAULT_MUNGER_ENABLED': True
}
with patch('distilleries.models.Distillery.save_data',
return_value='id_123') as mock_save:
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER',
mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') \
as mock_catch_email:
MailChute.objects.process(doc_obj)
self.assertIs(mock_save.called, True)
self.assertIs(mock_catch_email.called, False)
def test_no_match_with_default(self):
"""
Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailMunger is enabled.
"""
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {
'DEFAULT_MUNGER': 'default_mail',
'DEFAULT_MUNGER_ENABLED': True
}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER',
mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') \
as mock_default_process:
MailChute.objects.process(doc_obj)
mock_default_process.assert_called_once_with(doc_obj)
def test_no_match_missing_munger(self):
"""
Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailChute is enabled but
the defaul MailMunger can't be found.
"""
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {
'DEFAULT_MUNGER': 'missing_munger',
'DEFAULT_MUNGER_ENABLED': True
}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER',
mock_config):
with LogCapture() as log_capture:
msg = 'Default MailMunger "missing_munger" is not configured.'
MailChute.objects.process(doc_obj)
log_capture.check(
('sifter.chutes.models', 'ERROR', msg),
)
def test_get_default_no_chute(self):
"""
Tests the _default_munger function when the default LogMunger
does not exist.
"""
mock_config = {
'DEFAULT_MUNGER': 'dummy_munger',
'DEFAULT_MUNGER_ENABLED': True
}
with patch.dict('sifter.logsifter.logchutes.models.conf.LOGSIFTER',
mock_config):
with LogCapture() as log_capture:
actual = LogChute.objects._default_munger
expected = None
self.assertEqual(actual, expected)
self.assertFalse(LogChute.objects._default_munger_enabled)
log_capture.check(
('sifter.chutes.models',
'ERROR',
'Default LogMunger "dummy_munger" is not configured.'),
)
def test_raise_no_supported_snmp_backend_found_raised_if_no_snmp_libraries_are_available(
self):
modules = {
'pynetsnmp': None,
}
with patch.dict(sys.modules, modules):
self._patch_cleaning(sys.modules)
pytest.raises(ImportError, 'import pynetsnmp')
pytest.raises(ImportError, 'from nav.Snmp.pynetsnmp import *')
try:
from nav.Snmp import Snmp
pytest.fail("Should never happen")
except ImportError as foo:
assert str(foo) == 'No supported SNMP backend was found'
def setUp(self):
self.plugin_a = Mock(
name='snmptrapd plugin a')
self.plugin_a.strip.return_value = 'nav.snmptrapd.handlers.foo'
self.plugin_b = Mock(
name='snmptrapd plguin b')
self.plugin_b.strip.return_value = 'nav.snmptrapd.handlers.bar'
del self.plugin_b.initialize
def raise_exception():
raise Exception('boom')
self.bad_plugin = Mock(name='snmptrapd plugin which is bad')
self.bad_plugin.strip.return_value = 'nav.snmptrapd.handlers.bad_plugin'
self.bad_plugin.initialize=raise_exception
self.patcher = patch.dict(sys.modules, {
'nav.snmptrapd.handlers.foo': self.plugin_a,
'nav.snmptrapd.handlers.bar': self.plugin_b,
'nav.snmptrapd.handlers.bad_plugin': self.bad_plugin,
'nav.snmptrapd.handlers.non_existent': None
})
self.patcher.start()
def test_bouncer_env(self):
"""
Validate the environment variable loader works as expected.
"""
# Test it doesn't leak
with patch.dict('lambada.os.environ', dict(BLAH='asdf'), clear=True):
config = lambada.get_config_from_env()
self.assertFalse(config)
# Test it works with default
with patch.dict(
'lambada.os.environ', dict(BOUNCER_BLAH='asdf'), clear=True
):
config = lambada.get_config_from_env()
self.assertDictEqual(config, dict(blah='asdf'))
# Test that we can override the prefix
with patch.dict(
'lambada.os.environ',
dict(STUFF_BLAH='asdf', STUFFS_BLAH='jkl;'),
clear=True
):
config = lambada.get_config_from_env('STUFF_')
self.assertDictEqual(config, dict(blah='asdf'))
def test_dancer_class(self):
"""
Verify the dancer class constructor, props, and call.
"""
dancer = lambada.Dancer(self.sample_dancer, 'foo', 'bar', memory=128)
# Confirm __init__
self.assertEqual(dancer.name, 'foo')
self.assertEqual(dancer.description, 'bar')
self.assertDictEqual(dancer.override_config, dict(memory=128))
# Validate config merge property
self.assertDictEqual(
dancer.config,
dict(name='foo', description='bar', memory=128)
)
self.assertEqual((1, 2), dancer(1, 2))
def test_keeptemp_via_env_variable():
if os.environ.get('NICEMAN_TESTS_KEEPTEMP'):
raise SkipTest("We have env variable set to preserve tempfiles")
files = []
@with_tempfile()
def check(f):
open(f, 'w').write("LOAD")
files.append(f)
with patch.dict('os.environ', {}):
check()
with patch.dict('os.environ', {'NICEMAN_TESTS_KEEPTEMP': '1'}):
check()
eq_(len(files), 2)
ok_(not exists(files[0]), msg="File %s still exists" % files[0])
ok_( exists(files[1]), msg="File %s not exists" % files[1])
rmtemp(files[-1])
def test_skip_if_no_network():
cleaned_env = os.environ.copy()
cleaned_env.pop('NICEMAN_TESTS_NONETWORK', None)
# we need to run under cleaned env to make sure we actually test in both conditions
with patch('os.environ', cleaned_env):
@skip_if_no_network
def somefunc(a1):
return a1
eq_(somefunc.tags, ['network'])
with patch.dict('os.environ', {'NICEMAN_TESTS_NONETWORK': '1'}):
assert_raises(SkipTest, somefunc, 1)
with patch.dict('os.environ', {}):
eq_(somefunc(1), 1)
# and now if used as a function, not a decorator
with patch.dict('os.environ', {'NICEMAN_TESTS_NONETWORK': '1'}):
assert_raises(SkipTest, skip_if_no_network)
with patch.dict('os.environ', {}):
eq_(skip_if_no_network(), None)
def test_load_settings_from_env(tmpdir):
with patch.dict('os.environ', {}) as e:
load_settings_from_env(str(tmpdir))
assert os.environ.get('FOO', None) is None
p = tmpdir.join(".env")
p.write("FOO = bar")
with patch.dict('os.environ', {}) as e:
load_settings_from_env(str(tmpdir))
assert os.environ.get('FOO', None) == 'bar'
def test_handle_content_type_json(self, mocklast, mockjsonify,
mockrender, mockrequest):
fake_d = {'Content-Type': 'application/json'}
mockrequest.headers.__getitem__.side_effect = fake_d.__getitem__
mockrequest.headers.get.side_effect = fake_d.get
mockrequest.headers.__iter__.side_effect = fake_d.__iter__
mockjsonify.side_effect = myjsonify
res = util.handle_content_type(dict(template='example.html'))
err_msg = "template key should exist"
assert res.get('template') == 'example.html', err_msg
err_msg = "jsonify should be called"
assert mockjsonify.called, err_msg