Example #1
0
    def test_run_analyse_custom_regulator(self):
        '''Test run_analyze() with a custom regulator'''
        session_store = webdorina.SESSION_STORE.format(unique_id='fake-uuid')
        expected_trace = '''Called run.analyse(
    datadir='/fake/data/dir',
    genome='hg19',
    match_a='any',
    region_a='any',
    set_a=['scifi', '{session_store}/fake-uuid.bed'],
    set_b=None)'''.format(session_store=session_store)

        query = dict(genome='hg19', set_a=['scifi', 'fake-uuid'], match_a='any',
                     region_a='any', set_b=None)

        self.return_value = """chr1	doRiNA2	gene	1	1000	.	+	.	ID=gene01.01	chr1	250	260	PARCLIP#scifi*scifi_cds	5	+
chr1	doRiNA2	gene	2001	3000	.	+	.	ID=gene01.02	chr1	2350	2360	PARCLIP#scifi*scifi_intron	6	+"""

        run.run_analyse('/fake/data/dir', 'results:fake_key', 'results:fake_key_pending', query, 'fake-uuid')
        expected = self.return_value.split('\n')
        expected.sort(key=lambda x: float(x.split('\t')[13]), reverse=True)

        assert_same_trace(self.tt, expected_trace)

        self.assertTrue(self.r.exists('results:fake_key'))
        self.assertEqual(2, self.r.llen('results:fake_key'))
        self.assertEqual(expected, self.r.lrange('results:fake_key', 0, -1))

        self.assertTrue(self.r.exists('sessions:fake-uuid'))
        self.assertEqual(json.loads(self.r.get('sessions:fake-uuid')), dict(uuid='fake-uuid', state='done'))

        self.assertTrue(self.r.exists('results:sessions:fake-uuid'))
        self.assertEqual(json.loads(self.r.get('results:sessions:fake-uuid')), dict(redirect="results:fake_key"))
 def test_unknown_error(self):
     # mock urlfetch
     response = Response(500)
     trace = TraceTracker()
     boxcargae.urlfetch = Mock("boxcargae.urlfetch")
     boxcargae.urlfetch.fetch = Mock("fetch", returns=response, tracker=trace)
     # unknown error(500)
     self.assertRaises(
         boxcargae.BoxcarException,
         self.boxcar.notify,
         "*****@*****.**",
         "test_error",
         "unknown error",
         message_id=500,
     )
     assert_same_trace(
         trace,
         "Called fetch(\n"
         "    'http://boxcar.io/devices/providers/xxxxxxxxxxxxxxxxxxxx/notifications',\n"
         "    headers={'User-Agent': 'Boxcar_Client'},\n"
         "    method='POST',\n"
         "    payload='notification%5Bfrom_remote_service_id%5D=500&"
         "notification%5Bicon_url%5D=xxxxxxxxx%40xxxxx.xxx&"
         "secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&"
         "token=xxxxxxxxxxxxxxxxxxxx&"
         "notification%5Bmessage%5D=unknown+error&"
         "email=fd2504c1a700746932666efec57e4b92&"
         "notification%5Bfrom_screen_name%5D=test_error')\n",
     )
Example #3
0
    def test_set_password_with_login(self, mock_set_password):
        """Set password with login account that differs from `from` address."""
        tracker = mock_set_password

        login = '******'
        smtp_server = 'smtp.gmail.com'

        # argument to set_password
        email_config = {
            'enabled': True,
            'from': '*****@*****.**',
            'to': '*****@*****.**',
            'subject': 'updatewatch',
            'smtp': {
                'login': login,
                'host': smtp_server,
                'port': 587
            }
        }

        # expected trace from minimock
        want = dedent("""\
            Called getpass.getpass(
                prompt="Enter password for '{login}' using '{smtp_server}': ")
            Called keyring.set_password(
                '{smtp_server}',
                '{login}',
                'set_password_secret')""".format(
                    login=login, smtp_server=smtp_server))

        # set password with mockups
        mailer.set_password(email_config)

        # assert trace of all calls to smtplib are as expected
        minimock.assert_same_trace(tracker, want)
Example #4
0
    def test_get_sensor(self):
        "Test get_sensor()"
        temp_alert = TempAlert()

        # Everything is fine
        mock("temp_alert.get_data",
             returns={u'temp':23.45, u'alarm': False, u'panic': False},
             tracker=self.tt)
        sensor = temp_alert.get_sensor('foo')
        self.assertAlmostEqual(23.45, sensor['temp'])
        self.assertFalse(sensor['alarm'])
        self.assertFalse(sensor['panic'])

        # Alarm state
        mock("temp_alert.get_data",
             returns={u'temp':23.45, u'alarm': True, u'panic': False},
             tracker=self.tt)
        sensor = temp_alert.get_sensor('foo')
        self.assertAlmostEqual(23.45, sensor['temp'])
        self.assertTrue(sensor['alarm'])
        self.assertFalse(sensor['panic'])

        # Panic state
        mock("temp_alert.get_data",
             returns={u'temp':23.45, u'alarm': True, u'panic': True},
             tracker=self.tt)
        sensor = temp_alert.get_sensor('foo')
        self.assertAlmostEqual(23.45, sensor['temp'])
        self.assertTrue(sensor['alarm'])
        self.assertTrue(sensor['panic'])

        expected = "Called temp_alert.get_data('foo')\n" * 3
        assert_same_trace(self.tt, expected)
Example #5
0
    def reblog_post_test(self):
        self.client.reblog_post("toqoz.tumblr.com", {
            "id": 123456789,
            "reblog_key": "adcdefg"
        })
        assert_same_trace(
            self.trackar, """\
            Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/reblog', %s)
        """ % ({
                "id": 123456789,
                "reblog_key": "adcdefg"
            }))

        self.trackar.clear()
        self.client.reblog_post("toqoz.tumblr.com", {
            "id": 123456789,
            "reblog_key": "adcdefg",
            "comment": "comment"
        })
        assert_same_trace(
            self.trackar, """\
            Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/reblog', %s)
        """ % ({
                "id": 123456789,
                "reblog_key": "adcdefg",
                "comment": "comment"
            }))
Example #6
0
    def test_notify(self):
        # mock urlfetch
        trace = TraceTracker()
        response = Response(200) 
        boxcar.fetch = Mock('fetch',
                                returns=response, 
                                tracker=trace)
        # send a notification
        self.boxcar.notify('*****@*****.**',
                           'test_normal',
                           'notification message',
                            message_id=200)
        assert_same_trace(trace,
            "Called fetch(\n"
            "    'http://boxcar.io/devices/providers/xxxxxxxxxxxxxxxxxxxx/notifications',\n"
            "    headers={'User-Agent': 'Boxcar_Client'},\n"

            "    payload='"
                         "email=yyyyyyyy%40yyyyy.yyy&"
                         "notification%5Bfrom_remote_service_id%5D=200&"
                         "notification%5Bfrom_screen_name%5D=test_normal&"
                         "notification%5Bicon_url%5D=xxxxxxxxx%40xxxxx.xxx&"
                         "notification%5Bmessage%5D=notification+message&"
                         "secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&"
                         "token=xxxxxxxxxxxxxxxxxxxx"
                         "')\n")
Example #7
0
    def test_search_query_pending(self):
        '''Test search() with a query for this key pending'''
        self.r.set('sessions:fake-uuid', json.dumps(dict(uuid='fake-uuid', state='done')))
        key = 'results:{"combine": "or", "genes": ["all"], "genome": "hg19", '
        key += '"match_a": "any", "match_b": "any", "region_a": "any", '
        key += '"region_b": "any", "set_a": ["scifi"], "set_b": null}'
        key_pending = '{0}_pending'.format(key)
        self.r.set(key_pending, True)

        data = dict(match_a='any', assembly='hg19', uuid='fake-uuid')
        data['set_a[]']=['scifi']
        rv = self.client.post('/api/v1.0/search', data=data)

        # Should return "pending"
        self.assertEqual(rv.json, dict(uuid='fake-uuid', state="pending"))

        # This query should trigger a defined set of calls
        expected_trace = '''Called fake_store.exists('sessions:fake-uuid')
Called fake_store.exists(
    '{0}')
Called fake_store.set(
    'sessions:fake-uuid',
    '{{"state": "pending", "uuid": "fake-uuid"}}')
Called fake_store.expire('sessions:fake-uuid', {2})
Called fake_store.get(
    '{1}')'''.format(key, key_pending, webdorina.SESSION_TTL)
        assert_same_trace(self.tt, expected_trace)
 def test_multi_record(self):
     results = {"r1": {"a": 2, "b": 4}, "r2": {"a": 2}, "r3": {"b": 3}}
     expected = ("Called logging.debug('Total times taken by modules')\n"
                 "Called logging.debug('  %s: %.1fs', 'a', 4.0)\n"
                 "Called logging.debug('  %s: %.1fs', 'b', 7.0)\n")
     main.log_module_runtimes(results)
     assert_same_trace(self.trace_tracker, expected)
Example #9
0
    def test_init_exists(self):
        """DictDB inits reading a previously existing file"""

        json.load.mock_returns = {}

        assert DictDB(self.file.name) == {}
        assert_same_trace(self.trace, "Called json.load(<open file '%s', mode 'r' at 0x...>)" % self.file.name)
Example #10
0
    def test_set_password(self, mock_set_password):
        """Set password with `from` address as login."""
        tracker = mock_set_password

        email_from = '*****@*****.**'
        smtp_server = 'smtp.gmail.com'

        # argument to set_password
        email_config = {
            'enabled': True,
            'from': email_from,
            'to': '*****@*****.**',
            'subject': 'updatewatch',
            'smtp': {
                'host': smtp_server,
                'port': 587
            }
        }

        # expected trace from minimock
        want = dedent("""\
            Called getpass.getpass(
                prompt="Enter password for '{email_from}' using '{smtp_server}': ")
            Called keyring.set_password(
                '{smtp_server}',
                '{email_from}',
                'set_password_secret')""".format(
                    email_from=email_from, smtp_server=smtp_server))

        # set password with mockups
        mailer.set_password(email_config)

        # assert trace of all calls to smtplib are as expected
        minimock.assert_same_trace(tracker, want)
Example #11
0
 def test_adds_client_id_to_lookup_store(self):
     tracker = minimock.TraceTracker()
     minimock.mock('channel.ServerChannels.add_client_id', tracker=tracker)
     self.post('/_ah/channel/connected/', params={'from': 'client-id'})
     minimock.assert_same_trace(
         tracker,
         "Called channel.ServerChannels.add_client_id(u'client-id')")
Example #12
0
    def test_check_if_db_record_exists(self):
        "Test for check_if_db_record_exists() function"
        # set up options namespace
        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.BioSQLconfig.dbgenomenamespace = "testgenomenamespace"
        # mock into BioSeqDatabase methods to interrupt database connection
        mock('BioSeqDatabase.Adaptor.fetch_dbid_by_dbname',
             tracker=self.trace_tracker,
             returns=1234)
        mock('BioSeqDatabase.Adaptor.fetch_seqid_by_display_id',
             tracker=self.trace_tracker,
             returns=4321)

        mytest = utils.check_if_dbrecord_exists("testrecord", self.options)

        expected = """    Called BioSeqDatabase.Adaptor.fetch_dbid_by_dbname('testgenomenamespace')
    Called BioSeqDatabase.Adaptor.fetch_dbid_by_dbname('testgenomenamespace')
    Called BioSeqDatabase.Adaptor.fetch_seqid_by_display_id(
        dbid=1234,
        name='testrecord')
        """
        assert_same_trace(self.trace_tracker, expected)

        self.assertTrue(mytest, "expected return value 'True' but got 'False'")
Example #13
0
    def test_users_from_url(self):
        mock('obswatch.http_GET', tracker=self.tt,
             returns=StringIO('''<?xml version="1.0" encoding="UTF-8"?>
           <project name="superkde" created="2005-01-01T00:00:02+01:00" updated="2007-01-19T10:44:45+01:00">
             <title>SuperKDE</title>
             <description>SuperKDE is a heavily tuned version of KDE.</description>
             <link project="openSUSE:11.2:Update" />
             <link project="openSUSE:11.2" />
             <person role="maintainer" userid="Geeko"/>
             <person role="maintainer" userid="BrownGeeko"/>
             <group  role="reviewer"  groupid="release_team"/>
             <build>
               <disable />
             </build>
             <repository name="kde4:factory" rebuild="transitive">
               <path project="kde4" repository="factory"/>
               <arch>i386</arch>

               <arch>x86_64</arch>
             </repository>
           </project>'''))
        mock('obswatch.get_user_email', returns='*****@*****.**')

        result = obswatch.get_users_from_url('%ssource/superkde/_meta' %
                                            obswatch.APIURL)
        assert_same_trace(self.tt, """Called obswatch.http_GET(
            '%ssource/superkde/_meta')""" % obswatch.APIURL)
        self.assertEqual(len(result), 2)
        self.assertEqual(result['Geeko'], '*****@*****.**')
        self.assertEqual(result['BrownGeeko'], '*****@*****.**')        
Example #14
0
    def test_unknown_error(self):
        # mock urlfetch
        response = Response(500) 
        trace = TraceTracker()
        boxcar.fetch = Mock('fetch',
                                returns=response, 
                                tracker=trace)
        # unknown error(500)
        self.assertRaises(boxcar.BoxcarException, 
                          self.boxcar.notify, '*****@*****.**',
                                              'test_error',
                                              'unknown error',
                                              message_id=500)
        assert_same_trace(trace,
            "Called fetch(\n"
            "    'http://boxcar.io/devices/providers/xxxxxxxxxxxxxxxxxxxx/notifications',\n"
            "    headers={'User-Agent': 'Boxcar_Client'},\n"

            "    payload='"
                         "email=yyyyyyyy%40yyyyy.yyy&"
                         "notification%5Bfrom_remote_service_id%5D=500&"
                         "notification%5Bfrom_screen_name%5D=test_error&"
                         "notification%5Bicon_url%5D=xxxxxxxxx%40xxxxx.xxx&"
                         "notification%5Bmessage%5D=unknown+error&"
                         "secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&"
                         "token=xxxxxxxxxxxxxxxxxxxx"
                         "')\n")
Example #15
0
    def test_check_prereqs(self):
        "Test fullhmmer.check_prereqs()"
        expected = []
        returned = cluster_hmmer.check_prereqs(self.config)

        self.assertListEqual(expected, returned)
        assert_same_trace(self.tracer, self.expected_trace)
Example #16
0
 def test_shard_find_one(self):
     object_id = ObjectId()
     MongoResource.find_one(object_id)
     minimock.assert_same_trace(self.tt, '\n'.join([
         "Called Collection.find_one(",
         "    {'_id': ObjectId('...'), 'shard': '...'})"
     ]))
Example #17
0
 def test_post_put_hook_sends_log_line_to_channel(self):
     tracker = minimock.TraceTracker()
     minimock.mock('channel.ServerChannels.get_client_ids', returns=['client_id'], tracker=None)
     minimock.mock('channel.ServerChannels.send_message', tracker=tracker)
     log_line = models.LogLine.create(self.server, LOG_LINE, TIME_ZONE)
     minimock.assert_same_trace(
         tracker, """Called channel.ServerChannels.send_message({0}, u'chat')""".format(log_line)
     )
Example #18
0
    def test_check_prereqs_missing_exe(self):
        "Test fullhmmer.check_prereqs() with a missing executable"
        path.locate_executable.mock_returns = None
        expected = ["Failed to locate executable: 'hmmscan'"]
        returned = full_hmmer.check_prereqs()

        self.assertListEqual(expected, returned)
        assert_same_trace(self.tracer, self.expected_trace)
Example #19
0
 def unfollow_test(self):
     self.client.unfollow({"url": "toqoz.tumblr.com"})
     assert_same_trace(
         self.trackar, """\
         Called pyblr.Pyblr.post('/v2/user/unfollow', %s)
     """ % ({
             "url": "toqoz.tumblr.com"
         }))
Example #20
0
 def test_check_prereqs(self):
     "Test lanthipeptides.check_prereqs()"
     ret = check_prereqs()
     self.assertEqual(ret, [])
     expected = """    Called antismash.common.path.locate_executable('hmmpfam2')
 Called antismash.common.path.locate_executable('fimo')"""
     assert_same_trace(self.tracker, expected)
     self.assertTrue(get_config().fimo_present)
Example #21
0
 def info_test(self):
     self.client.info("toqoz.tumblr.com")
     assert_same_trace(
         self.trackar, """\
         Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/info', %s)
     """ % ({
             'api_key': self.api_key
         }))
Example #22
0
    def test__exit(self):
        "Test TemporaryFile __exit__() method"
        tfile = TemporaryFile()

        trace = """    Called tempfile.mkstemp('', 'tmp', None, False)
    Called os.unlink('/fake/tmp/file')"""
        tfile.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)
Example #23
0
    def test__exit(self):
        "Test TemporaryDirectory __exit__() method"
        tdir = TemporaryDirectory()

        trace = """    Called tempfile.mkdtemp('', 'tmp', None)
    Called shutil.rmtree('/fake/tmp/dir')"""
        tdir.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)
Example #24
0
 def delete_post_test(self):
     self.client.delete_post("toqoz.tumblr.com", {"id": 123456789})
     assert_same_trace(
         self.trackar, """\
         Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/delete', %s)
     """ % ({
             "id": 123456789
         }))
Example #25
0
 def test_minimal(self):
     with TemporaryDirectory(change=True) as tempdir:
         self.options = build_config(["--minimal", "--output-dir", tempdir],
                                     isolated=True, modules=antismash.get_all_modules())
         antismash.main.run_antismash(helpers.get_path_to_balhymicin_genbank(),
                                      self.options)
     # make sure it didn't run
     minimock.assert_same_trace(self.tracker, "")
Example #26
0
    def test__exit(self):
        "Test TemporaryDirectory __exit__() method"
        tdir = TemporaryDirectory()

        trace = """    Called tempfile.mkdtemp('', 'tmp', None)
    Called shutil.rmtree('/fake/tmp/dir')"""
        tdir.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)
Example #27
0
    def test_check_prereqs_missing_exe(self):
        "Test fullhmmer.check_prereqs() with a missing executable"
        self.config.executables.__dict__.pop("hmmscan")
        expected = ["Failed to locate executable: 'hmmscan'"]
        returned = cluster_hmmer.check_prereqs(self.config)

        self.assertListEqual(expected, returned)
        assert_same_trace(self.tracer, self.expected_trace)
Example #28
0
    def test_context_should_increment_failed_and_raise(self):
        def foo():
            with counter.counter('countername'):
                raise Exception

        self.assertRaises(Exception, foo)
        minimock.assert_same_trace(self.tt, '\n'.join([
            "Called counter.increment('countername_failed')"
        ]))
Example #29
0
    def test__exit(self):
        "Test TemporaryFile __exit__() method"
        tfile = TemporaryFile()

        trace = """    Called tempfile.mkstemp('', 'tmp', None, False)
    Called os.close(42)
    Called os.unlink('/fake/tmp/file')"""
        tfile.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)
Example #30
0
 def test__enter(self):
     "Test TemporaryDirectory __enter__() method"
     expected = "/fake/tmp/dir"
     trace = """    Called tempfile.mkdtemp('', 'tmp', None)"""
     tdir = TemporaryDirectory()
     d = tdir.__enter__()
     self.assertEqual(d, expected)
     self.assertEqual(self.cwd, '/old/cur/dir')
     assert_same_trace(self.tt, trace)
Example #31
0
 def test__enter(self):
     "Test TemporaryPipe __enter__() method"
     expected = "/fake/tmp/dir/pipe"
     trace = """    Called tempfile.mkdtemp()
 Called os.mkfifo('/fake/tmp/dir/pipe')"""
     pipe = TemporaryPipe()
     path = pipe.__enter__()
     self.assertEqual(path, expected)
     assert_same_trace(self.tt, trace)
Example #32
0
 def test__enter(self):
     "Test TemporaryPipe __enter__() method"
     expected = "/fake/tmp/dir/pipe"
     trace = """    Called tempfile.mkdtemp()
 Called os.mkfifo('/fake/tmp/dir/pipe')"""
     pipe = TemporaryPipe()
     path = pipe.__enter__()
     self.assertEqual(path, expected)
     assert_same_trace(self.tt, trace)
Example #33
0
 def test__enter(self):
     "Test TemporaryFile __enter__() method"
     expected = "/fake/tmp/file"
     trace = """    Called tempfile.mkstemp('', 'tmp', None, False)"""
     tfile = TemporaryFile()
     f = tfile.__enter__()
     self.assertEqual(f.name, expected)
     self.assertEqual(f.handle, 42)
     assert_same_trace(self.tt, trace)
Example #34
0
 def test__enter(self):
     "Test TemporaryDirectory __enter__() method"
     expected = "/fake/tmp/dir"
     trace = """    Called tempfile.mkdtemp('', 'tmp', None)"""
     tdir = TemporaryDirectory()
     d = tdir.__enter__()
     self.assertEqual(d, expected)
     self.assertEqual(self.cwd, '/old/cur/dir')
     assert_same_trace(self.tt, trace)
Example #35
0
 def test__enter(self):
     "Test TemporaryFile __enter__() method"
     expected = "/fake/tmp/file"
     trace = """    Called tempfile.mkstemp('', 'tmp', None, False)"""
     tfile = TemporaryFile()
     f = tfile.__enter__()
     self.assertEqual(f.name, expected)
     self.assertEqual(f.handle, 42)
     assert_same_trace(self.tt, trace)
Example #36
0
    def test_get_available_sensors(self):
        "Test get_available_sensors()"
        temp_alert = TempAlert()
        mock("temp_alert.get_data", returns={u'sensors': [u'first', u'second']},
             tracker=self.tt)
        self.assertEqual(['first', 'second'], temp_alert.get_available_sensors())

        expected = "Called temp_alert.get_data('available')"
        assert_same_trace(self.tt, expected)
Example #37
0
    def test_decorator_should_increment_failed_and_raise(self):
        @counter.counted('countername')
        def foo():
            raise Exception('argh')

        self.assertRaises(Exception, foo)

        minimock.assert_same_trace(self.tt, '\n'.join([
            "Called counter.increment('countername_failed')"
        ]))
Example #38
0
    def test_get_data(self):
        "Test get_data()"
        temp_alert = TempAlert()
        mock("orig_ta.urlopen", returns=StringIO('{"test": "passed"}'),
             tracker=self.tt)

        self.assertEqual({'test': 'passed'}, temp_alert.get_data('test'))

        expected = "Called orig_ta.urlopen('http://localhost:8367/test')"
        assert_same_trace(self.tt, expected)
Example #39
0
    def test_decorator_should_increment(self):
        @counter.counted('countername')
        def foo():
            pass

        foo()

        minimock.assert_same_trace(self.tt, '\n'.join([
            "Called counter.increment('countername')"
        ]))
Example #40
0
    def test_init_exists(self):
        """DictDB inits reading a previously existing file"""

        json.load.mock_returns = {}

        assert DictDB(self.file.name) == {}
        assert_same_trace(
            self.trace,
            "Called json.load(<open file '%s', mode 'r' at 0x...>)" %
            self.file.name)
Example #41
0
    def followers_test(self):
        self.client.followers("toqoz.tumblr.com")
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s)
        """ % ({}))

        self.trackar.clear()
        self.client.followers("toqoz.tumblr.com", {"limit": 10})
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s)
        """ % ({'limit': 10}))
Example #42
0
    def test_send_email(self):
        "Test send_email()"
        expected = r'''Called smtplib.SMTP('localhost')
Called smtp_conn.sendmail(
    '*****@*****.**',
    ['*****@*****.**', '*****@*****.**'],
    'From: [email protected]\nTo: [email protected], [email protected]\nSubject: Temperature Alert - Status: alarm\n\nThe following sensors are in alarm or panic state:\nSensor\tTemperature\nfoo\t23.42\nbar\t42.23\n\nSincerely,\ntemp-alert\n')
Called smtp_conn.quit()'''
        template = orig_ta.build_alert_mail('alarm', {'foo': 23.42, 'bar': 42.23})
        orig_ta.send_email(self.config, template)
        assert_same_trace(self.tt, expected)
Example #43
0
    def following_test(self):
        self.client.following()
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/user/following', %s)
        """ % ({}))

        self.trackar.clear()
        self.client.following({"limit": 10})
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/user/following', %s)
        """ % ({"limit": 10}))
Example #44
0
    def test__exit(self):
        "Test TemporaryPipe __exit__() method"
        trace = ""
        pipe = TemporaryPipe()
        pipe.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)

        pipe.tempdir = "foo"
        trace = "    Called shutil.rmtree('foo')"
        pipe.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)
Example #45
0
    def test__exit(self):
        "Test TemporaryPipe __exit__() method"
        trace = ""
        pipe = TemporaryPipe()
        pipe.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)

        pipe.tempdir = "foo"
        trace = "    Called shutil.rmtree('foo')"
        pipe.__exit__(None, None, None)
        assert_same_trace(self.tt, trace)
Example #46
0
    def posts_test(self):
        self.client.posts("toqoz.tumblr.com")
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts', %s)
        """ % ({'api_key': self.api_key}))

        self.trackar.clear()
        self.client.posts("toqoz.tumblr.com", {"type": "photo"})
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts', %s)
        """ % ({'api_key': self.api_key, 'type': 'photo'}))
Example #47
0
    def dashboard_test(self):
        self.client.dashboard()
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/user/dashboard', %s)
        """ % ({}))

        self.trackar.clear()
        self.client.dashboard({"type": "photo"})
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/user/dashboard', %s)
        """ % ({"type": "photo"}))
Example #48
0
    def likes_test(self):
        self.client.likes()
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/user/likes', %s)
        """ % ({}))

        self.trackar.clear()
        self.client.likes({"limit": 10})
        assert_same_trace(self.trackar, """\
            Called pyblr.Pyblr.get('/v2/user/likes', %s)
        """ % ({"limit": 10}))
Example #49
0
    def test_search_cached_results(self):
        '''Test search() with cached_results'''
        key = 'results:{"combine": "or", "genes": ["all"], "genome": "hg19", '
        key += '"match_a": "any", "match_b": "any", "region_a": "any", '
        key += '"region_b": "any", "set_a": ["scifi"], "set_b": null}'
        results = [
        'chr1	doRiNA2	gene	1	1000	.	+	.	ID=gene01.01	chr1	250	260	PARCLIP#scifi*scifi_cds	6	+	250	260',
        'chr1	doRiNA2	gene	2001	3000	.	+	.	ID=gene01.02	chr1	2350	2360	PARCLIP#scifi*scifi_intron	5	+	2350	2360',
        'chr1	doRiNA2	gene	3001	4000	.	+	.	ID=gene01.03	chr1	3350	3360	PARCLIP#scifi*scifi_intron	7	+	3350	3360'
        ]
        for res in results:
            self.r.rpush(key, res)

        self.r.set('sessions:fake-uuid', json.dumps(dict(uuid='fake-uuid', state='done')))

        data = dict(match_a='any', assembly='hg19', uuid='fake-uuid')
        data['set_a[]']=['scifi']
        rv = self.client.post('/api/v1.0/search', data=data)

        self.assertEqual(rv.json, dict(state='done', uuid="fake-uuid"))

        rv = self.client.get('/api/v1.0/result/fake-uuid')
        expected = dict(state='done', results=results, more_results=False, next_offset=100, total_results=3)
        self.assertEqual(rv.json, expected)

        # This query should trigger a defined set of calls
        expected_trace = '''Called fake_store.exists('sessions:fake-uuid')
Called fake_store.exists(
    '{0}')
Called fake_store.expire(
    '{0}',
    {1})
Called fake_store.set(
    'sessions:{3}',
    '{{"state": "done", "uuid": "{3}"}}')
Called fake_store.expire('sessions:{3}', {4})
Called fake_store.set(
    'results:sessions:{3}',
    {5!r})
Called fake_store.expire('results:sessions:{3}', {4})
Called fake_store.exists('results:sessions:{3}')
Called fake_store.get('results:sessions:{3}')
Called fake_store.expire(
    '{0}',
    {1})
Called fake_store.lrange(
    '{0}',
    0,
    {2})
Called fake_store.llen(
    '{0}')
    '''.format(key, webdorina.RESULT_TTL, webdorina.MAX_RESULTS - 1,
               'fake-uuid', webdorina.SESSION_TTL, json.dumps(dict(redirect=key)))
        assert_same_trace(self.tt, expected_trace)
Example #50
0
    def test_check_prereqs_missing_file(self):
        "Test fullhmmer.check_prereqs() with a missing file"
        self.file_list[0] = None
        path.locate_file.mock_returns_iter = self.file_list
        expected = [
            "Failed to locate file: 'Pfam-A.hmm' in %s/pfam/%s" %
            (self.config.database_dir, self.latest_pfam)
        ]
        returned = cluster_hmmer.check_prereqs(self.config)

        self.assertListEqual(expected, returned)
        assert_same_trace(self.tracer, self.expected_trace)
Example #51
0
    def test_commit(self):
        "test commit method"

        mydb = self.mydb

        mock('BioSeqDatabase.DBServer.commit',
             tracker=self.trace_tracker,
             returns=["mock result"])

        mydb.commit()
        expected = "Called BioSeqDatabase.DBServer.commit()"
        assert_same_trace(self.trace_tracker, expected)
Example #52
0
    def test_rollback(self):
        "test rollback method"

        mydb = self.mydb

        mock('BioSeqDatabase.DBServer.rollback',
             tracker=self.trace_tracker,
             returns=["mock result"])

        mydb.rollback()
        expected = 'Called BioSeqDatabase.DBServer.rollback()'
        assert_same_trace(self.trace_tracker, expected)
Example #53
0
 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()
Example #54
0
 def _check_make_server(self, backend):
     mocked_backend = minimock.Mock('Backend', returns='backend_impl', tracker=self.tt)
     minimock.mock('chaussette.server.get', returns=mocked_backend, tracker=self.tt)
     server = chaussette.server.make_server('app', 'host', 'port', backend)
     minimock.assert_same_trace(self.tt, '\n'.join([
         "Called chaussette.server.get('%s')" % backend,
         "Called Backend(",
         "    ('host', 'port'),",
         "   'app',",
         "   address_family=2,",
         "   backlog=2048,",
         "socket_type=1)"
     ]))
     self.assertEqual(server, 'backend_impl')
Example #55
0
 def edit_post_test(self):
     self.client.edit_post("toqoz.tumblr.com", {
         "id": 123456789,
         "type": "text",
         "body": "new text"
     })
     assert_same_trace(
         self.trackar, """\
         Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/edit', %s)
     """ % ({
             "id": 123456789,
             "type": "text",
             "body": "new text"
         }))
Example #56
0
    def test_simple_request_799(self):
        req = Request.blank('http://example.com/testform')
        self.set_response(
            status='799 Silly Response',
            headers=h(x_foobar='blaz'),
            body='blahblah',
        )

        res = req.get_response(proxy_exact_request)

        self.assertEqual(res.status_code, 799)
        self.assertEqual(res.body, 'blahblah')
        self.assertEqual(res.headers['X-Foobar'], 'blaz')
        assert_same_trace(self.trace_tracker, expected_trace_for_request(req))
Example #57
0
    def test_simple_request_200(self):
        req = Request.blank('http://example.com/testform')
        self.set_response(
            status='200 OK',
            headers=h(content_type='text/html'),
            body='some stuff',
        )

        res = req.get_response(proxy_exact_request)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.body, 'some stuff')
        self.assertEqual(res.headers['Content-Type'], 'text/html')
        assert_same_trace(self.trace_tracker, expected_trace_for_request(req))
Example #58
0
    def followers_test(self):
        self.client.followers("toqoz.tumblr.com")
        assert_same_trace(
            self.trackar, """\
            Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s)
        """ % ({}))

        self.trackar.clear()
        self.client.followers("toqoz.tumblr.com", {"limit": 10})
        assert_same_trace(
            self.trackar, """\
            Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s)
        """ % ({
                'limit': 10
            }))
Example #59
0
 def test_change_cwd(self):
     "Test TemporaryDirectory changing the cwd"
     expected = "/fake/tmp/dir"
     trace = """    Called tempfile.mkdtemp('', 'tmp', None)
 Called os.getcwd()
 Called os.chdir('/fake/tmp/dir')
 Called os.chdir('/old/cur/dir')
 Called shutil.rmtree('/fake/tmp/dir')"""
     tdir = TemporaryDirectory(change=True)
     tdir.__enter__()
     self.assertEqual(self.cwd, expected)
     self.assertEqual(tdir.old_wd, '/old/cur/dir')
     tdir.__exit__(None, None, None)
     self.assertEqual(self.cwd, '/old/cur/dir')
     assert_same_trace(self.tt, trace)
Example #60
0
    def test_simple_request_302(self):
        req = Request.blank('http://example.com/testform')
        self.set_response(
            status='302 Found',
            headers=h(content_type='text/html', set_cookie='foo=bar'),
            body='some content',
        )

        res = req.get_response(proxy_exact_request)

        self.assertEqual(res.status_code, 302)
        self.assertEqual(res.body, 'some content')
        self.assertEqual(res.headers['Content-Type'], 'text/html')
        self.assertEqual(res.headers['Set-Cookie'], 'foo=bar')
        assert_same_trace(self.trace_tracker, expected_trace_for_request(req))