def tearDown(self): """ tearDown :return: """ super(TestServer, self).tearDown() minimock.restore()
def test_no_email_notify(self): topost = { 'login_id': 'usersaved_noemailnotify', 'email_address': '*****@*****.**', 'user-submit-flag': 'submitted', 'approved_permissions': None, 'denied_permissions': None, 'assigned_groups': None, 'super_user': 1, 'inactive_flag': False, 'inactive_date': '10/11/2010', 'name_first': 'test', 'name_last': 'user' } # setup the mock objects so we can test the email getting sent out tt = minimock.TraceTracker() smtplib.SMTP = minimock.Mock('smtplib.SMTP', tracker=None) smtplib.SMTP.mock_returns = minimock.Mock('smtp_connection', tracker=tt) req, r = self.c.post('users/add', data=topost, follow_redirects=True) assert r.status_code == 200, r.status assert b'User added' in r.data assert req.url.endswith('users/manage') assert len(tt.dump()) == 0 minimock.restore()
def test_get_client_invalid(self): """Test getting a connection """ minimock.restore() mongothin.connection.register_connection("invalid", "mongothin", host="localhost", invalidaram="invalid") self.assertRaises(mongothin.connection.ConnectionError, mongothin.connection.get_connection, "invalid")
def test_parseUrl(self): "CSSParser.parseUrl()" if mock: # parseUrl(self, href, encoding=None, media=None, title=None): parser = cssutils.CSSParser() mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, u'')) sheet = parser.parseUrl('http://example.com', media='tv,print', title='test') restore() #self.assertEqual(sheet, 1) self.assertEqual(sheet.href, 'http://example.com') self.assertEqual(sheet.encoding, 'utf-8') self.assertEqual(sheet.media.mediaText, 'tv, print') self.assertEqual(sheet.title, 'test') # URL and content tests tests = { # (url, content): isSheet, encoding, cssText ('', None): (False, None, None), ('1', None): (False, None, None), ('mailto:[email protected]', None): (False, None, None), ('http://example.com/x.css', None): (False, None, None), ('http://example.com/x.css', ''): (True, u'utf-8', u''), # ('http://example.com/x.css', 'a'): (True, u'utf-8', u''), # ('http://example.com/x.css', 'a {color: red}'): (True, u'utf-8', # u'a {\n color: red\n }'), # ('http://example.com/x.css', 'a {color: red}'): (True, u'utf-8', # u'a {\n color: red\n }'), # ('http://example.com/x.css', '@charset "ascii";a {color: red}'): (True, u'ascii', # u'@charset "ascii";\na {\n color: red\n }'), } override = 'iso-8859-1' overrideprefix = u'@charset "iso-8859-1";' httpencoding = None for (url, content), (isSheet, expencoding, cssText) in tests.items(): mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(httpencoding, content)) #parser.setFetcher(self._make_fetcher(httpencoding, content)) sheet1 = parser.parseUrl(url) sheet2 = parser.parseUrl(url, encoding=override) restore() if isSheet: self.assertEqual(sheet1.encoding, expencoding) self.assertEqual(sheet1.cssText, cssText) self.assertEqual(sheet2.encoding, override) if sheet1.cssText and sheet1.cssText.startswith('@charset'): self.assertEqual(sheet2.cssText, cssText.replace('ascii', override)) elif sheet1.cssText: self.assertEqual(sheet2.cssText, overrideprefix + '\n' + cssText) else: self.assertEqual(sheet2.cssText, overrideprefix + cssText) else: self.assertEqual(sheet1, None) self.assertEqual(sheet2, None) self.assertRaises(ValueError, parser.parseUrl, '../not-valid-in-urllib') self.assertRaises(urllib2.HTTPError, parser.parseUrl, 'http://example.com/not-present.css')
def testTripwireTripped(self): '''Tripwire test, tripped''' tt = minimock.TraceTracker() minimock.mock('tripwire.sendEmail', tracker=tt) datevalue = datetime.date(2011, 8, 16) dtmock = minimock.Mock('datetime.date') minimock.mock('datetime.date', mock_obj=dtmock) dtmock.mock_returns = dtmock dtmock.today.mock_returns = datevalue dtmock.today.mock_tracker = tt #can't just do minimock.mock('datetime.date.today', returns=datevalue, tracker=tt) #because datetime.date is in an extension (ie, not native python) #Add another value to make the tripwire trip self.session.add(model.MeasuredValue(6)) self.session.commit() tripwire.main() expected = r'''Called datetime.date.today() Called tripwire.sendEmail(3.0, datetime.date(2011, 8, 16))''' self.assertTrue(tt.check(expected), tt.diff(expected)) minimock.restore()
def mock_get(url, **kwargs): """ Mock requests.get with the contents of a local file. If the file doesn't exist, make the request and save to the file. """ cache_dir = build_path(join_path('cache')) key = hashlib.md5(url.encode('utf-8')).hexdigest() file_path = os.path.join(cache_dir, '{}.xml'.format(key)) try: return MockResponse(file_path) except IOError: restore() # restore normal function r = requests.get(url) if not r.ok: mock('requests.get', returns_func=mock_get, tracker=None) # re-mock it. return r with open(file_path, 'w') as tmp: try: tmp.write(r.text) except UnicodeEncodeError: tmp.write(r.content) # python 2 mock('requests.get', returns_func=mock_get, tracker=None) # re-mock it. return MockResponse(file_path)
def test_ini_non_exist_or_bad(self): """ bad file """ os.environ = minimock.Mock("os.environ") os.environ.get.mock_returns = "/tmp/tdtdtd" self.assertEqual(h.base.load_ini().sections(), []) minimock.restore()
def test_env_not_set(self): """ no ini set in environ """ os.environ = minimock.Mock("os.environ") os.environ.get.mock_returns = None self.assertRaises(ValueError, h.base.load_ini) minimock.restore()
def tearDown(self): restore() try: # logging for record in self.log.records: if self.is_endpoints and len(record.args) >= 3: exception = record.args[2] if isinstance(exception, endpoints.ServiceException): try: str(exception) except TypeError: record.args[2].args = [str(arg) for arg in exception.args] except UnicodeEncodeError: record.args[2].args = [unicode(arg) for arg in exception.args] pathname = get_tail(record.pathname).group("tail") curdir_abspath = os.path.abspath(os.curdir) if is_mac: if curdir_abspath.startswith(mac_volumes_prefix): curdir_abspath = curdir_abspath[mac_volumes_prefix_length:] if pathname.startswith(mac_volumes_prefix): pathname = pathname[mac_volumes_prefix_length:] else: curdir_abspath = curdir_abspath.lstrip('/') pathname = pathname.lstrip('/') log = (record.levelname, pathname.replace(curdir_abspath, "").lstrip("/"), record.funcName, record.getMessage()) if getattr(self, "expected_logs", None): if log in self.expected_logs: continue matched = None for expected_log in self.expected_logs: if "..." in expected_log[3]: if log[:2] == expected_log[:2]: if doctest._ellipsis_match(expected_log[3], log[3]): matched = True continue if matched: continue elif self.is_endpoints: expected_log = ( 'WARNING', 'google/appengine/ext/ndb/tasklets.py', '_help_tasklet_along', '... generator ...(....py:...) raised ...Exception(...)') if log[:2] == expected_log[:2]: if doctest._ellipsis_match(expected_log[3], log[3]): matched = True continue print(record.levelname, pathname, record.lineno, record.funcName, record.getMessage()) assert not log finally: self.log.clear() self.log.uninstall() # testbed self.testbed.deactivate() # os.environ for key, value in self.origin_environ.iteritems(): if value is not None: os.environ[key] = value
def test_EncodeDataCheckProblemsFile_Exists(self): showname = "test show" inputname = "test input" outputname = "test_output_.mkv" data = EncodeData(showname, inputname, outputname) mock("os.path.exists", returns_iter=[False, True]) result = data.checkproblems() self.assertIn("FILE_EXISTS", result) minimock.restore()
def test_make_server_spawn(self): """ Check the spawn option for the backend that support it :return: """ for backend in ['gevent', 'fastgevent', 'geventwebsocket', 'socketio']: self.tt = minimock.TraceTracker() self._check_make_server_spawn(backend) minimock.restore()
def test_gpsdshm_Shm_error(): gpsdshm.shm.shm_get = minimock.Mock('gpsdshm.shm.shm_get') gpsdshm.shm.shm_get.mock_returns = None try: gpsdshm.Shm() except OSError: minimock.restore() return raise Exception('gpsdshm.shm.shm_get did nto raise OSError')
def tearDown(self): """ tearDown :return: """ super(TestServer, self).tearDown() minimock.restore() if self.old is not None: socket.socket.bind = self.old
def test_gpsdshm_Shm_error(): gpsdshm.shm.shm_get = minimock.Mock("gpsdshm.shm.shm_get") gpsdshm.shm.shm_get.mock_returns = None try: gpsdshm.Shm() except OSError: minimock.restore() return raise Exception("gpsdshm.shm.shm_get did nto raise OSError")
def tearDown(self): """Teardown """ super(Testconnection, self).tearDown() mongothin.connection._connection_settings.clear() mongothin.connection._connections.clear() mongothin.connection._dbs.clear() minimock.restore()
def tearDown(self): '''Clean up from each test case. Switch back to the original working directory, and clean up the test directory and any mocked objects. ''' os.chdir(self.orig_cwd) self.test_dir.cleanup() minimock.restore()
def testRight(self): ''' Will test if a right click event will open the correct Right-Click Menu. ''' evt = wx.TreeEvent(wx.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK) minimock.mock("evt.GetItem",returns=self.frame.tree.GetRootItem()) minimock.mock("evt.GetPoint",returns=wx.Point(83, 121)) self.frame.OnRight(evt) minimock.restore() minimock.restore()
def test_checkduplicatethomas(self): settings = Mock('libsettings.Settings') filemanager = FileManager(settings) os.walk = thomaswalk result = filemanager.checkduplicates("/path/to/S12E05 - Henry Gets It Wrong - SD TV.mkv") self.assertTrue(result) minimock.restore()
def test_checkfileexistscaseinsensitive(self): settings = Mock('libsettings.Settings') filemanager = FileManager(settings) mock("os.listdir", returns=["filename.test"]) result = filemanager.checkfileexists("/path/to/fiLename.test", False) self.assertTrue(result) minimock.restore()
def test_checkduplicatesameextension(self): settings = Mock('libsettings.Settings') filemanager = FileManager(settings) os.walk = dummywalk result = filemanager.checkduplicates("/path/to/S03E14 - Test - SD TV.avi") self.assertFalse(result) minimock.restore()
def testTripwireNormal(self): '''Tripwire test, not tripped''' tt = minimock.TraceTracker() minimock.mock('tripwire.sendEmail', tracker=tt) tripwire.main() self.assertTrue(tt.check(''), tt.diff('')) minimock.restore()
def test_make_server(self): """ Test all backends with default params :return: """ # nose does not have great support for parameterized tests for backend in backends(): self.tt = minimock.TraceTracker() self._check_make_server(backend) minimock.restore()
def test_check_prereqs(self): "Test active_site_finder.check_prereqs method" # THIS TEST HAS TO BE UPDATED WHEN NEW PROFILES ARE ADDED TO THE MODULE! self.tt = TraceTracker() mock('utils.locate_executable', returns="/my/path/to/executable", tracker=self.tt) mock('utils.locate_file', returns="/my/path/to/file", tracker=self.tt) result = self.my_ASF.check_prereqs() self.assertListEqual(result, [], "return empty list if executables/files are found") expected = """ Called utils.locate_executable('blastp') Called utils.locate_executable('hmmpfam2') Called utils.locate_executable('hmmscan') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-KR.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-KS_N.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-KS_C.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-AT.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-ACP.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-DH.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-KR.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/Thioesterase.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-ER.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/PKSI-AT.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/aa-activating.aroundLys.hmm2') Called utils.locate_file( '.../antismash/generic_modules/active_site_finder/hmm/p450.hmm3')""" assert_same_trace(self.tt, expected) restore() self.tt = TraceTracker() mock('utils.locate_executable', returns=None, tracker=self.tt) mock('utils.locate_file', returns="/my/path/to/file", tracker=self.tt) result = self.my_ASF.check_prereqs() expected = ["Failed to locate file: 'blastp'", "Failed to locate file: 'hmmpfam2'", "Failed to locate file: 'hmmscan'"] self.assertListEqual(result, expected, "test result if file not found") restore()
def test_resolveImports(self): "cssutils.resolveImports(sheet)" if mock: self._tempSer() cssutils.ser.prefs.useMinified() a = u'@charset "iso-8859-1";@import"b.css";ä{color:green}'.encode('iso-8859-1') b = u'@charset "ascii";\E4 {color:red}'.encode('ascii') # normal mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, b)) s = cssutils.parseString(a) restore() self.assertEqual(a, s.cssText) self.assertEqual(b, s.cssRules[1].styleSheet.cssText) c = cssutils.resolveImports(s) self.assertEqual('\xc3\xa4{color:red}\xc3\xa4{color:green}', c.cssText) c.encoding = 'ascii' self.assertEqual(r'@charset "ascii";\E4 {color:red}\E4 {color:green}', c.cssText) # b cannot be found mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, None)) s = cssutils.parseString(a) restore() self.assertEqual(a, s.cssText) self.assertEqual(None, s.cssRules[1].styleSheet) c = cssutils.resolveImports(s) self.assertEqual('@import"b.css";\xc3\xa4{color:green}', c.cssText) # @import with media a = u'@import"b.css";@import"b.css" print, tv ;@import"b.css" all;' b = u'a {color: red}' mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, b)) s = cssutils.parseString(a) restore() c = cssutils.resolveImports(s) self.assertEqual('a{color:red}@media print,tv{a{color:red}}a{color:red}', c.cssText) # cannot resolve with media => keep original a = u'@import"b.css"print;' b = u'@namespace "http://example.com";' mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, b)) s = cssutils.parseString(a) restore() c = cssutils.resolveImports(s) self.assertEqual(a, c.cssText) else: self.assertEqual(False, u'Minimock needed for this test')
def test_resolveImports(self): "cssutils.resolveImports(sheet)" if mock: self._tempSer() cssutils.ser.prefs.useMinified() a = u'@charset "iso-8859-1";@import"b.css";ä{color:green}'.encode( 'iso-8859-1') b = u'@charset "ascii";\E4 {color:red}'.encode('ascii') # normal mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, b)) s = cssutils.parseString(a) restore() self.assertEqual(a, s.cssText) self.assertEqual(b, s.cssRules[1].styleSheet.cssText) c = cssutils.resolveImports(s) self.assertEqual('\xc3\xa4{color:red}\xc3\xa4{color:green}', c.cssText) c.encoding = 'ascii' self.assertEqual( r'@charset "ascii";\E4 {color:red}\E4 {color:green}', c.cssText) # b cannot be found mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, None)) s = cssutils.parseString(a) restore() self.assertEqual(a, s.cssText) self.assertEqual(None, s.cssRules[1].styleSheet) c = cssutils.resolveImports(s) self.assertEqual('@import"b.css";\xc3\xa4{color:green}', c.cssText) # @import with media a = u'@import"b.css";@import"b.css" print, tv ;@import"b.css" all;' b = u'a {color: red}' mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, b)) s = cssutils.parseString(a) restore() c = cssutils.resolveImports(s) self.assertEqual( 'a{color:red}@media print,tv{a{color:red}}a{color:red}', c.cssText) # cannot resolve with media => keep original a = u'@import"b.css"print;' b = u'@namespace "http://example.com";' mock("cssutils.util._defaultFetcher", mock_obj=self._make_fetcher(None, b)) s = cssutils.parseString(a) restore() c = cssutils.resolveImports(s) self.assertEqual(a, c.cssText) else: self.assertEqual(False, u'Minimock needed for this test')
def test_nose_component_app_package_by_environ(): import minimock import tempfile from minimal2.config.settings import Default new_script_test_path = tempfile.mkdtemp() Default.get_storage_dir = minimock.Mock('get_storage_dir') Default.get_storage_dir.mock_returns = os.path.join(new_script_test_path, 'minimal2') base_environ['BLAZEWEB_APP_PACKAGE'] = 'minimal2' newenv = BWTestFileEnvironment(new_script_test_path, environ=base_environ) res = newenv.run('nosetests', 'minimal2', expect_error=True, cwd=apps_path) assert 'Ran 1 test in' in res.stderr, res.stderr assert 'OK' in res.stderr, res.stderr minimock.restore()
def test_fail_at_acquireWriteLock(self): self.setUpContext() mock('ReadWriteLock.acquireWriteLock', raises=Exception, tracker=None) self.assertRaises(Exception, self.context.dispatch, 'pseudo-init', self.obj) self.assertEqual(0, _FantasmFanIn.all().count()) self.assertEqual(None, memcache.get('foo--InitialState--ok--FanInState--step-2-lock-3255389373')) restore() self.setUpContext(retryCount=1) self.context.dispatch('pseudo-init', self.obj) self.assertEqual(1, _FantasmFanIn.all().count()) self.assertEqual('foo--InitialState--ok--FanInState--step-2-2957927341', _FantasmFanIn.all().get().workIndex) self.assertEqual('65536', memcache.get('foo--InitialState--ok--FanInState--step-2-lock-3255389373'))
def test_sends_message_to_all_connected_clients(self): minimock.restore() self.tracker = minimock.TraceTracker() models.User.create_user('4321', email='*****@*****.**') user = models.User.lookup(email='*****@*****.**') client_id = '{0}.{1}.1234.5678'.format(self.server.key.id(), self.user.key.id()) client_id2 = '{0}.{1}.1234.5678'.format(self.server.key.id(), user.key.id()) minimock.mock('channel.ServerChannels.get_client_ids', returns=[client_id, client_id2], tracker=None) minimock.mock('gae_channel.send_message', tracker=self.tracker) self.interesting_log_line.send_message() js = '{"username": "******", "achievement_message": null, "chat": "is there anybody in there?", "time": "12:01am", "date": "Mar 24, 2013", "event": "chat", "death_message": null}' trace = "Called gae_channel.send_message(\n '{0}',\n '{1}')".format(client_id, js) trace += "\nCalled gae_channel.send_message(\n '{0}',\n '{1}')".format(client_id, js) minimock.assert_same_trace(self.tracker, trace)
def test_fail_at_put(self): self.setUpContext() mock('db.put', raises=Exception, tracker=None) self.assertRaises(Exception, self.context.dispatch, 'pseudo-init', copy.copy(self.obj)) self.assertEqual(0, _FantasmFanIn.all(namespace='').count()) # notice the +1 extra on the lock self.assertEqual(65537, memcache.get('foo--InitialState--ok--FanInState--step-2-lock-3255389373')) restore() self.setUpContext(retryCount=1) self.context.dispatch('pseudo-init', self.obj) self.assertEqual(1, _FantasmFanIn.all(namespace='').count()) self.assertEqual('foo--InitialState--ok--FanInState--step-2-2957927341', _FantasmFanIn.all(namespace='').get().workIndex) self.assertEqual(65537, memcache.get('foo--InitialState--ok--FanInState--step-2-lock-3255389373'))
def test_nose_component_app_package_by_environ(): import minimock import tempfile from minimal2.config.settings import Default new_script_test_path = tempfile.mkdtemp() Default.get_storage_dir = minimock.Mock('get_storage_dir') Default.get_storage_dir.mock_returns = os.path.join( new_script_test_path, 'minimal2') base_environ['BLAZEWEB_APP_PACKAGE'] = 'minimal2' newenv = BWTestFileEnvironment(new_script_test_path, environ=base_environ) res = newenv.run('nosetests', 'minimal2', expect_error=True, cwd=apps_path) assert 'Ran 1 test in' in res.stderr, res.stderr assert 'OK' in res.stderr, res.stderr minimock.restore()
def test__execute_tool(self): "Test active_site_finder._execute_tool method" self.tt = TraceTracker() self.tt2 = TraceTracker() mock('utils.execute', returns=["shell output", 0, 0], tracker=self.tt) mock('SearchIO.parse', returns=["SearchIO object"], tracker=self.tt2) result = self.my_ASF._execute_tool(self.ETObj.find('./analysis'), fileName="testTempfile") self.assertListEqual(result, ["SearchIO object"]) expected = """ Called utils.execute( ['hmmscan', '--domE', '0.1', '--cpu', '1', '.../antismash/generic_modules/active_site_finder/hmm/p450.hmm3', 'testTempfile']) """ assert_same_trace(self.tt, expected) expected = " Called SearchIO.parse(<cStringIO.StringI object at ...>, 'hmmer3-text')" assert_same_trace(self.tt2, expected) restore() self.tt = TraceTracker() self.tt2 = TraceTracker() mock('utils.execute', returns=["shell output", 0, 0], tracker=self.tt) mock('SearchIO.parse', returns=["SearchIO object"], tracker=self.tt2) result = self.my_ASF._execute_tool( self.ETObj.find('./analysis'), stdin_data="fasta sequence from stdin") self.assertListEqual(result, ["SearchIO object"]) expected = """ Called utils.execute( ['hmmscan', '--domE', '0.1', '--cpu', '1', '.../antismash/generic_modules/active_site_finder/hmm/p450.hmm3'], input='fasta sequence from stdin') """ assert_same_trace(self.tt, expected) expected = " Called SearchIO.parse(<cStringIO.StringI object at ...>, 'hmmer3-text')" assert_same_trace(self.tt2, expected) restore() self.tt = TraceTracker() del self.tt2
def testSendEmail(self): tt = minimock.TraceTracker() smtpconn = minimock.Mock('smtplib.SMTP', tracker=tt) minimock.mock('smtplib.SMTP', mock_obj=smtpconn) smtpconn.mock_returns = smtpconn smtpconn.sendmail.mock_returns = {} tripwire.sendEmail(2.5, datetime.date(2011, 8, 16)) expected = r"""Called smtplib.SMTP('localhost') Called smtplib.SMTP.sendmail( '*****@*****.**', ['*****@*****.**', '*****@*****.**'], 'Content-Type: text/plain; charset="us-ascii"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: [DBTW] Tripwire Report 2011-08-16\nTo: [email protected], [email protected]\nFrom: [email protected]\n\nDatabase trip wire has been tripped.\n\nRMS value was: 2.5\n') Called smtplib.SMTP.quit()""" self.assertTrue(tt.check(expected), tt.diff(expected)) minimock.restore()
def setUp(self): "set up database test framework and test for db connection" self.options = Namespace() self.options.BioSQLconfig = Namespace() self.options.BioSQLconfig.dbdriver = 'psycopg2' self.options.BioSQLconfig.dbuser = '******' self.options.BioSQLconfig.dbpass = '******' self.options.BioSQLconfig.dbhost = 'localhost' self.options.BioSQLconfig.dbport = '5432' self.options.BioSQLconfig.dbdb = 'antiSMASHnosetest' self.options.BioSQLnamespace = 'test' self.trace_tracker = TraceTracker() # test correct method call for db.asDB)() mock('BioSeqDatabase.open_database', tracker=self.trace_tracker, returns=['mock result']) expected = """Called BioSeqDatabase.open_database( db='antiSMASHnosetest', driver='psycopg2', host='localhost', passwd='biosql', port='5432', user='******') """ mydb = db.aSDB(self.options) assert_same_trace(self.trace_tracker, expected) # restore mocked objects that other tests can run with the original code restore() self.trace_tracker = TraceTracker() #test initializing database object db.__init__" try: mydb = db.aSDB(self.options) except Exception: self.skipTest( 'database connection could not be established, skipping tests') self.assertIsInstance(mydb, db.aSDB) self.mydb = mydb
def test__init(self): "Test active_site_finder.__init__ method" self.tt = TraceTracker() class dummyET: def __init__(self): pass def getroot(self): return dummyET() def findall(self, a): return "ET-Subtree" mock('ET.parse', returns=dummyET(), tracker=self.tt) #mock('ET.getroot', returns="XMLTree", tracker=self.tt) #mock('ET.findall', returns="XMLSubtree", tracker=self.tt) mock( 'antismash.generic_modules.active_site_finder.active_site_finder.check_prereqs', returns=[], tracker=self.tt) expected = """ Called ET.parse( '.../antismash/generic_modules/active_site_finder/config/SignatureResources.xml')""" ASF = antismash.generic_modules.active_site_finder.active_site_finder( self.seq_record, self.options) assert_same_trace(self.tt, expected) # restore mocked objects that other tests can run with the original code restore() self.tt = TraceTracker() # now acutally generate ASF object myASF = antismash.generic_modules.active_site_finder.active_site_finder( self.seq_record, self.options) assert_is_instance( myASF, antismash.generic_modules.active_site_finder.active_site_finder) self.my_ASF = myASF
def setUp(self): "set up database connection" # restore all mocked methods restore() #Open testfile and parse it with Biopython testfile = path.join(path.dirname(__file__), "AAA26493.embl") testfile_fh = open(testfile, "rU") self.seq_record = SeqIO.read(testfile_fh, 'embl') self.options = Namespace() self.options.BioSQLconfig = Namespace() self.options.BioSQLconfig.dbdriver = 'psycopg2' self.options.BioSQLconfig.dbuser = '******' self.options.BioSQLconfig.dbpass = '******' self.options.BioSQLconfig.dbhost = 'localhost' self.options.BioSQLconfig.dbport = '5432' self.options.BioSQLconfig.dbdb = 'antiSMASHnosetest' self.options.BioSQLnamespace = 'test' self.options.dbnamespace = self.options.BioSQLnamespace self.trace_tracker = TraceTracker() try: mydb = db.aSDB(self.options) except Exception: self.skipTest( 'database connection could not be established, skipping tests') if not mydb: self.skipTest('database connection impossible; skipping tests') try: del mydb.server[self.options.BioSQLnamespace] mydb.commit() except Exception: pass mydb.generate_namespace(self.options.BioSQLnamespace, 'test namespace for nosetests') mydb.connect(self.options.BioSQLnamespace) rec_no = mydb.load_records([self.seq_record]) mydb.commit() self.mydb = mydb
def urlopen_stub(url, data=None, timeout=30): """Mock urllib2.urlopen and return a local file handle or create file if not existent and then return it.""" if isinstance(url, urllib2.Request): key = md5(url.get_full_url()).hexdigest() else: key = md5(url).hexdigest() data_file = os.path.join(os.path.dirname(__file__), 'cache', "%s.xml" % key) try: f = open(data_file) except IOError: restore() data = urllib2.urlopen(url, data).read() # re-mock it. mock('urllib2.urlopen', returns_func=urlopen_stub, tracker=None) f = open(data_file, "w").write(data) f = open(data_file, "r") return f
def test_sends_log_line_data_as_json(self): minimock.restore() self.user.timezone_name = 'US/Pacific' self.user.put() self.tracker = minimock.TraceTracker() client_id = '{0}.{1}.1234.5678'.format(self.server.key.id(), self.user.key.id()) minimock.mock('channel.ServerChannels.get_client_ids', returns=[client_id], tracker=None) minimock.mock('gae_channel.send_message', tracker=self.tracker) js = '{"username": "******", "achievement_message": null, "chat": "is there anybody in there?", "time": "05:01pm", "date": "Mar 23, 2013", "event": "chat", "death_message": null}' self.interesting_log_line.send_message() minimock.assert_same_trace(self.tracker, "Called gae_channel.send_message('{0}','{1}')".format(client_id, js)) log_line = json.loads(js) self.assertEqual('chat', log_line['event']) self.assertEqual('Mar 23, 2013', log_line['date']) self.assertEqual('05:01pm', log_line['time']) self.assertEqual('quazifene', log_line['username']) self.assertEqual('is there anybody in there?', log_line['chat']) self.assertEqual(None, log_line['death_message'])
def mock_get(url, **kwargs): """ Mock requests.get with the contents of a local file. If the file doesn't exist, make the request and save to the file. """ key = hashlib.md5(url.encode('utf-8')).hexdigest() file_path = os.path.join(test_dir, 'cache', '{0}.xml'.format(key)) try: return MockResponse(file_path) except IOError: restore() # restore normal function r = requests.get(url) with open(file_path, 'w') as tmp: try: tmp.write(r.text) except UnicodeEncodeError: tmp.write(r.content) # python 2 mock('requests.get', returns_func=mock_get, tracker=None) # re-mock it. return MockResponse(file_path)
def test_sends_message_to_all_connected_clients(self): minimock.restore() self.tracker = minimock.TraceTracker() models.User.create_user('4321', email='*****@*****.**') user = models.User.lookup(email='*****@*****.**') client_id = '{0}.{1}.1234.5678'.format(self.server.key.id(), self.user.key.id()) client_id2 = '{0}.{1}.1234.5678'.format(self.server.key.id(), user.key.id()) minimock.mock('channel.ServerChannels.get_client_ids', returns=[client_id, client_id2], tracker=None) minimock.mock('gae_channel.send_message', tracker=self.tracker) self.interesting_log_line.send_message() js = '{"username": "******", "achievement_message": null, "chat": "is there anybody in there?", "time": "12:01am", "date": "Mar 24, 2013", "event": "chat", "death_message": null}' trace = "Called gae_channel.send_message(\n '{0}',\n '{1}')".format( client_id, js) trace += "\nCalled gae_channel.send_message(\n '{0}',\n '{1}')".format( client_id, js) minimock.assert_same_trace(self.tracker, trace)
def mock_get(url, **kwargs): """ Mock requets.get and return a local file handle or create file if not existent and then return it. """ key = md5(url).hexdigest() file_path = join(test_dir, 'cache', '{0}.xml'.format(key)) try: f = MockFile(file_path, 'r') except IOError: restore() # restore normal function tmp = MockFile(file_path, 'w') tmp.write(requests.get(url).content) tmp.close() mock('requests.get', returns_func=mock_get, tracker=None) # re-mock it. f = MockFile(file_path, 'r') f.populate_content() f.status_code = requests.codes.ok if not f.content: f.status_code = requests.codes.not_found return f
def test_fail_at_acquireWriteLock(self): self.setUpContext() mock('ReadWriteLock.acquireWriteLock', raises=Exception, tracker=None) self.assertRaises(Exception, self.context.dispatch, 'pseudo-init', self.obj) self.assertEqual(0, _FantasmFanIn.all().count()) self.assertEqual( None, memcache.get( 'foo--InitialState--ok--FanInState--step-2-lock-3255389373')) restore() self.setUpContext(retryCount=1) self.context.dispatch('pseudo-init', self.obj) self.assertEqual(1, _FantasmFanIn.all().count()) self.assertEqual( 'foo--InitialState--ok--FanInState--step-2-2957927341', _FantasmFanIn.all().get().workIndex) self.assertEqual( '65536', memcache.get( 'foo--InitialState--ok--FanInState--step-2-lock-3255389373'))
def test_fail_at_put(self): self.setUpContext() mock('db.put', raises=Exception, tracker=None) self.assertRaises(Exception, self.context.dispatch, 'pseudo-init', copy.copy(self.obj)) self.assertEqual(0, _FantasmFanIn.all().count()) # notice the +1 extra on the lock self.assertEqual( '65537', memcache.get( 'foo--InitialState--ok--FanInState--step-2-lock-3255389373')) restore() self.setUpContext(retryCount=1) self.context.dispatch('pseudo-init', self.obj) self.assertEqual(1, _FantasmFanIn.all().count()) self.assertEqual( 'foo--InitialState--ok--FanInState--step-2-2957927341', _FantasmFanIn.all().get().workIndex) self.assertEqual( '65537', memcache.get( 'foo--InitialState--ok--FanInState--step-2-lock-3255389373'))
def test_get_record(self): "Test get_record() function" Fake_seq_rec = Namespace() Fake_seq_rec.name = 'fakedName' mock('db.aSDB.get_record_by_name', tracker=self.trace_tracker, returns=Fake_seq_rec) db_seq_rec = db.get_record('AAA26493', self.options) expected = "Called db.aSDB.get_record_by_name('AAA26493')" assert_same_trace(self.trace_tracker, expected) restore() self.trace_tracker = TraceTracker() db_seq_rec = db.get_record('AAA26493', self.options) myrecord_class = db_seq_rec.__class__.__name__ self.assertEqual(myrecord_class, "DBSeqRecord") self.assertEqual(str(db_seq_rec.seq), str(self.seq_record.seq)) self.assertEqual(db_seq_rec.id, self.seq_record.id) self.assertEqual(db_seq_rec.name, self.seq_record.name)
def test_sends_log_line_data_as_json(self): minimock.restore() self.user.timezone_name = 'US/Pacific' self.user.put() self.tracker = minimock.TraceTracker() client_id = '{0}.{1}.1234.5678'.format(self.server.key.id(), self.user.key.id()) minimock.mock('channel.ServerChannels.get_client_ids', returns=[client_id], tracker=None) minimock.mock('gae_channel.send_message', tracker=self.tracker) js = '{"username": "******", "achievement_message": null, "chat": "is there anybody in there?", "time": "05:01pm", "date": "Mar 23, 2013", "event": "chat", "death_message": null}' self.interesting_log_line.send_message() minimock.assert_same_trace( self.tracker, "Called gae_channel.send_message('{0}','{1}')".format( client_id, js)) log_line = json.loads(js) self.assertEqual('chat', log_line['event']) self.assertEqual('Mar 23, 2013', log_line['date']) self.assertEqual('05:01pm', log_line['time']) self.assertEqual('quazifene', log_line['username']) self.assertEqual('is there anybody in there?', log_line['chat']) self.assertEqual(None, log_line['death_message'])
def tearDown(self): restore() # pylint: disable-msg=W0212 ReadWriteLock.BUSY_WAIT_ITER_SECS = ReadWriteLock._BUSY_WAIT_ITER_SECS ReadWriteLock.BUSY_WAIT_ITERS = ReadWriteLock._BUSY_WAIT_ITERS super(ReadWriteLockTest, self).tearDown()
def tearDown(self): restore() super(RunOnceSemaphoreTest, self).tearDown()
def tearDown(self): restore()
def tearDown(self): restore() super(FanInQueueDispatchTest, self).tearDown()
def tearDown(self): restore() super(FanInMergeJoinDispatchTest, self).tearDown()
def tearDown(self): super(FanInTxnException, self).tearDown() restore()
def tearDown(self): super(TaskDoubleExecutionTest, self).tearDown() restore()
def teardown(self): restore()
def test_defaultFetcher(self): """util._defaultFetcher""" if mock: class Response(object): """urllib2.Reponse mock""" def __init__(self, url, contenttype, content, exception=None, args=None): self.url = url mt, params = cgi.parse_header(contenttype) self.mimetype = mt self.charset = params.get('charset', None) self.text = content self.exception = exception self.args = args def geturl(self): return self.url def info(self): mimetype, charset = self.mimetype, self.charset class Info(object): def gettype(self): return mimetype def getparam(self, name): return charset return Info() def read(self): # returns fake text or raises fake exception if not self.exception: return self.text else: raise self.exception(*self.args) def urlopen(url, contenttype=None, content=None, exception=None, args=None): # return an mock which returns parameterized Response def x(*ignored): if exception: raise exception(*args) else: return Response(url, contenttype, content, exception=exception, args=args) return x # positive tests tests = { # content-type, contentstr: encoding, contentstr ('text/css', u'€'.encode('utf-8')): (None, u'€'.encode('utf-8')), ('text/css;charset=utf-8', u'€'.encode('utf-8')): ('utf-8', u'€'.encode('utf-8')), ('text/css;charset=ascii', 'a'): ('ascii', 'a') } url = 'http://example.com/test.css' for (contenttype, content), exp in tests.items(): mock("urllib2.urlopen", mock_obj=urlopen(url, contenttype, content)) #print url, exp == _readUrl(url, encoding), exp, _readUrl(url, encoding) self.assertEqual(exp, _defaultFetcher(url)) # wrong mimetype mock("urllib2.urlopen", mock_obj=urlopen(url, 'text/html', 'a')) self.assertRaises(ValueError, _defaultFetcher, url) # calling url results in fake exception tests = { '1': (ValueError, ['invalid value for url']), 'e2': (urllib2.HTTPError, ['u', 500, 'server error', {}, None]), #_readUrl('http://cthedot.de/__UNKNOWN__.css') 'e3': (urllib2.HTTPError, ['u', 404, 'not found', {}, None]), #_readUrl('mailto:a.css') 'mailto:e4': (urllib2.URLError, ['urlerror']), # cannot resolve x, IOError 'http://x': (urllib2.URLError, ['ioerror']), } for url, (exception, args) in tests.items(): mock("urllib2.urlopen", mock_obj=urlopen(url, exception=exception, args=args)) self.assertRaises(exception, _defaultFetcher, url) restore()
def tearDown(self): minimock.restore()