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')
Beispiel #2
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'], '*****@*****.**')        
 def setUp(self):
     self.api = MediaMosaAPI('http://video.example.com')
     self.tt = TraceTracker()
     mock('self.api.session', tracker=self.tt)
     self.response = Mock('requests.Response')
     self.response.status_code = 200
     self.api.session.get.mock_returns = self.response
    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()
        
Beispiel #5
0
 def setUp(self):
     self.maxDiff = None
     run.Redis = fakeredis.FakeRedis
     self.r = fakeredis.FakeStrictRedis()
     self.tt = TraceTracker()
     self.return_value = ''
     mock('run.analyse', tracker=self.tt, returns_func=self.get_return_value)
    def setUp(self):
        """
        Nadgers haystack SearchView so that:
        - we don't need a search backend
        - response is a TemplateResponse, not and HttpResponse (so
          that in tests we can check context contents)
        """
        import django.template.response
        import haystack.views
        
        # SearchView passes a RequestContext to render_to_response,
        # but we want to be able to get hold of the request itself
        # (to pass on to TemplateResponse).
        class RequestContext(django.template.response.RequestContext):
            def __init__(self, request):
                super(RequestContext, self).__init__(request)
                self.request = request

        def render_to_response(template, context, context_instance):
            return django.template.response.TemplateResponse(
                    request = context_instance.request,
                    template = template,
                    context = context)

        self.context_class = RequestContext
        minimock.mock("haystack.views.render_to_response", returns_func=render_to_response, tracker=None)
        minimock.mock("haystack.views.SearchView.get_results", returns_func=self.get_results, tracker=None)

        self.org = OrganizationFactory()
Beispiel #7
0
    def test_offline(self):
        """Proxy when offline"""

        import urllib
        minimock.mock('urllib.urlopen', raises=IOError)

        get_proxy()
Beispiel #8
0
def mock_send_email(request):
    """Mock up smtplib.SMTP and keyring.get_password for send_email."""
    import smtplib
    import keyring

    # capture all calls into mock objects
    # (instead of letting output go to stdout)
    tracker = minimock.TraceTracker()

    # mock up smtplib
    minimock.mock('smtplib.SMTP',
                  returns=minimock.Mock('smtp_connection', tracker=tracker),
                  tracker=tracker)

    # mock up keyring.get_password
    minimock.mock('keyring.get_password',
                  returns='send_email_secret',
                  tracker=tracker)

    def finalizer():
        # restore all objects in global module state that minimock replaced
        minimock.restore()

    request.addfinalizer(finalizer)

    return tracker
    def setUp(self):
        self.api = MediaMosaAPI('http://video.example.com')
        self.tt = TraceTracker()
        mock('self.api.session', tracker=self.tt)
        self.response = Mock('requests.Response')
        self.response.status_code = 200
        self.api.session.get.mock_returns = self.response

        self.item_dict = {u'is_original_file': u'FALSE',
            u'is_streamable': u'FALSE', u'is_downloadable': u'FALSE',
            u'app_id': u'2', u'transcode_inherits_acl': u'TRUE',
            u'tag': '', u'response_metafile_available': u'TRUE',
            u'mediafile_id_source': u'u2ilZNiHdl7iNUdexL7BcFMY',
            u'asset_id': u'g1QkoSmSeHdWfGkMKlOlldLn',
            u'mediafile_id': u'Md2RgaUEVFhfJMeUIbwPOMei',
            u'transcode_profile_id': u'17',
            u'filename': u'Sintel_Trailer1.1080p.DivX_Plus_HD.mp4',
            u'is_protected': u'FALSE', u'ega_stream_url': '',
            u'file_extension': u'mp4', 'metadata': {
            u'is_inserted_md': u'FALSE', u'fps': u'24', u'bpp': u'0.31',
            u'file_duration': u'00:00:52.20', u'colorspace': u'yuv420p',
            u'container_type': u'mov;mp4;m4a;3gp;3g2;mj2', u'height': u'478',
            u'channels': u'stereo', u'width': u'852', u'sample_rate': u'44100',
            u'filesize': u'20543936', u'audio_codec': u'aac',
            u'video_codec': u'h264', u'is_hinted': u'TRUE',
            u'bitrate': u'3012', u'mime_type': u'video/mp4'},
            u'ega_download_url': '', u'ega_play_url': '', u'tool': u'ffmpeg',
            u'response_plain_available': u'TRUE', u'owner_id': u'krkeppen',
            u'response_object_available': u'TRUE',
            u'created': u'2012-07-05 11:38:14',
            u'changed': u'2012-07-05 11:38:14', u'uri': '',
            u'is_still': u'FALSE', u'command':
            u'audiocodec:libfaac;audiobitrate:128000;audiosamplingrate:44100;audiochannels:2;videocodec:libx264;videopreset_quality:slow;videopreset_profile:baseline;2_pass_h264_encoding:2;videobitrate:800000;qmax:17;size:852x480;maintain_aspect_ratio:yes',
            u'group_id': ''}
Beispiel #10
0
    def setUp(self):
        from netprintbox.data import OAuthRequestToken

        super(DropboxServiceSetupTest, self).setUp()

        token = 'oauth_token=token&oauth_token_secret=secret'
        token = OAuthRequestToken(key=self.key, token=token)
        token.put()

        class client(object):
            @staticmethod
            def account_info():
                return {'uid': self.uid,
                        'email': 'email',
                        'display_name': 'display_name',
                        'country': 'JP',
                        }

        class session(object):
            @staticmethod
            def obtain_access_token(request_token):
                pass

            class token(object):
                key = 'access_key'
                secret = 'access_secret'

        import dropbox.client
        import dropbox.session
        mock('dropbox.client.DropboxClient', returns=client)
        mock('dropbox.session.DropboxSession', returns=session)
Beispiel #11
0
    def test_ok(self):
        """OK proxy"""

        minimock.mock('flickrapi.FlickrAPI.get_token_part_one')
        minimock.mock('flickrapi.FlickrAPI.get_token_part_two', returns=True)

        assert isinstance(get_proxy(), flickrapi.FlickrAPI)
Beispiel #12
0
    def test_cb(self):
        """Callback from proxy"""

        minimock.mock('flickrapi.FlickrAPI.get_token_part_one', returns=('token', 'frob'))

        def _bad_api(auth_response):
            raise FlickrError('Error: 108: Invalid frob')

        minimock.mock('flickrapi.FlickrAPI.get_token_part_two',
                      returns_func=_bad_api)

        self.hit_cb = False

        def _cb(proxy, perms, token, frob):
            assert perms == 'write'
            assert token == 'token'
            assert frob == 'frob'

            if self.hit_cb:
                return True
            else:
                self.hit_cb = True

        assert_raises(FlickrError, get_proxy, wait_callback=_cb)
        assert self.hit_cb
Beispiel #13
0
def mock_set_password(request):
    """Mock up getpass.getpass and keyring.set_password for set_password."""
    import getpass
    import keyring

    # capture all calls into mock objects
    # (instead of letting output go to stdout)
    tracker = minimock.TraceTracker()

    # mock up getpass.getpass
    minimock.mock('getpass.getpass',
                  returns='set_password_secret',
                  tracker=tracker)

    # mock up keyring.set_password
    minimock.mock('keyring.set_password',
                  tracker=tracker)

    def finalizer():
        # restore all objects in global module state that minimock replaced
        minimock.restore()

    request.addfinalizer(finalizer)

    return tracker
Beispiel #14
0
    def test_bad_xml(self):
        """Bad XML from proxy"""

        minimock.mock('flickrapi.FlickrAPI.get_token_part_one',
                      raises=ExpatError)

        get_proxy()
Beispiel #15
0
 def setUp(self):
     super(FanInMergeJoinDispatchTest, self).setUp()
     setUpByString(self, FAN_IN_MACHINE, machineName='FanInMachine', instanceName='foo')
     mock('config.currentConfiguration', returns=self.currentConfig, tracker=None)
     for i in range(20):
         SimpleModel(key_name='%d' % i).put()
     memcache.set('calls', 0)
     memcache.set('raise', False)
     
     context = self.factory.createFSMInstance(self.machineConfig.name, instanceName='foo')
     context[constants.STEPS_PARAM] = 1
     obj = TemporaryStateObject()
     obj[constants.TASK_NAME_PARAM] = 'taskName'
     obj[constants.RETRY_COUNT_PARAM] = 0
     
     self.context = None
     self.obj = None
     
     random.seed(0)
     context.dispatch('pseudo-init', obj) # write down a work package
     self.index = context[constants.INDEX_PARAM]
     
     self.assertEqual(1, _FantasmFanIn.all().count())
     self.assertEqual('foo--InitialState--ok--FanInState--step-2-2957927341', 
                      _FantasmFanIn.all().get().workIndex)
Beispiel #16
0
 def test_multipleLevelMountPointExtraPathInfo(self):
     url = '/other/mount/point/fsm/MyMachine/state1/to/state2'
     request = buildRequest(path=url)
     from fantasm import config
     mock('config.currentConfiguration', returns=MockConfigRootUrl('/other/mount/point/'), tracker=None)
     name = getMachineNameFromRequest(request)
     self.assertEquals(name, 'MyMachine')
Beispiel #17
0
 def setUp(self):
     super(StartStateMachineTests, self).setUp()
     filename = 'test-TaskQueueFSMTests.yaml'
     setUpByFilename(self, filename)
     self.machineName = getMachineNameByFilename(filename)
     self.mockQueue = TaskQueueDouble()
     mock(name='Queue.add', returns_func=self.mockQueue.add, tracker=None)
 def test_successful_authentication(self):
     # setup
     mock('self.api._login_challenge', returns='xxx', tracker=self.tt)
     mock('self.api._login_response', returns=True, tracker=self.tt)
     # test
     success = self.api.authenticate(self.username, self.secret)
     # validate
     self.assertEquals(success, True)
Beispiel #19
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)
     )
Beispiel #20
0
 def setUp(self):
     super(ScreenShotBlurredTaskTest, self).setUp()
     minimock.mock('image.NdbImage.post_data', returns_func=self.mock_post_data, tracker=None)
     self.server = models.Server.create()
     self.image_data = None
     blob_info = self.create_blob_info(IMAGE_PATH)
     self.screenshot = models.ScreenShot.create(self.server.key, None, blob_info=blob_info)
     self.assertEqual(1, models.ScreenShot.query().count())
Beispiel #21
0
    def test_reject(self):
        """Rejected proxy"""

        minimock.mock('flickrapi.FlickrAPI.get_token_part_one')
        minimock.mock('flickrapi.FlickrAPI.get_token_part_two',
                      raises=FlickrError)

        get_proxy()
Beispiel #22
0
    def test_finalStateDispatchWithEventEmitsNoEventAsTask(self):
        mockQueue = TaskQueueDouble()
        mock(name='Queue.add', returns_func=mockQueue.add, tracker=None)

        self.context.currentState = self.stateNormal
        self.context.dispatch('next-event', {})

        self.assertEquals(len(mockQueue.tasks), 0)
Beispiel #23
0
 def test_maxDoublingsAddedToQueuedTask(self):
     def execute(context, obj):
         return 'ok5'            
     mock(name='CountExecuteCalls.execute', returns_func=execute, tracker=None)
     self.context.dispatch(self.initEvent, TemporaryStateObject())
     self.assertEquals(len(self.mockQueue.tasks), 1)
     task = self.mockQueue.tasks[0][0]
     self.assertEquals(task.retry_options.max_doublings, 5)
  def test(self):
    gv = tap.ext.GoogleVisualization(username="******", password="******", key="dummy")
    assert isinstance(gv, tap.ext.GoogleVisualization)
    assert list(gv.query("select *")) == [{u'A': u'Japan', u'Population Density': 339.0}]

    mock("atom.service.AtomService.request", returns=ErrorResponse())
    assert list(gv.query("select *")) == []
    self.expected_logs = [('ERROR', 'gae/tap/ext.py', 'query', "[{u'reason': u'invalid_query', u'detailed_message': u'Query parse error: Encountered...', u'message': u'Invalid query'}]")]
Beispiel #25
0
 def setUp(self):
     super(FanInTxnException, self).setUp()
     setUpByString(self, FAN_IN_MACHINE, machineName='FanInMachine')
     mock('config.currentConfiguration', returns=self.currentConfig, tracker=None)
     for i in range(20):
         SimpleModel(key_name='%d' % i).put()
     memcache.set('calls', 0)
     memcache.set('raise', True)
Beispiel #26
0
    def test_get_fail(self):
        """Fail shorthash retrieval"""

        self.make_mock_photo('123')

        minimock.mock('urllib2.urlopen', raises=IOError)

        self.index.refresh()
Beispiel #27
0
    def test_get_fail_bad(self):
        """Failed shorthash retrieval passes fatal exceptions"""

        self.make_mock_photo('123')

        minimock.mock('urllib2.urlopen', raises=SystemError)

        self.index.refresh()
Beispiel #28
0
 def setUp(self):
     super(BaseTest, self).setUp()
     setUpByString(self, FAN_IN_MACHINE, machineName=self.MACHINE_NAME)
     mock('config.currentConfiguration', returns=self.currentConfig, tracker=None)
     mock('FSMFanInCleanupHandler.post', returns=None, tracker=None)
     for i in range(10):
         ContinuationFanInModel(value=i).put()
     self.context['event'] = self.EVENT
Beispiel #29
0
 def testLights(self):
     minimock.mock("executor.dim.set_dim_level", returns=None)
     for i in ['12', '50']:
         self.assertEqual("Lights turned %s" % str(i), executor.lights(i))
     for i in ['lala', '234$', '12 12', '-12', '0', '50.5', 'off']:
         self.assertEqual("Lights turned 0", executor.lights(i))
     for i in ['100', '34674', '1111111111', 'on']:
         self.assertEqual("Lights turned 100", executor.lights(i))
Beispiel #30
0
def stub(name, **kw):
	kw['tracker'] = minimock.Printer(open(os.devnull, "w"))

	stack = inspect.stack()
	globals_ = stack[1][0].f_globals
	locals_ = stack[1][0].f_locals
	kw['nsdicts'] = (locals_, globals_, __builtin__.__dict__)

	minimock.mock(name, **kw)
Beispiel #31
0
    def setUp(self):
        """ Set up test fixtures """
        self.mock_outfile = StringIO()

        self.app_class_name = self.application_class.__name__
        self.mock_app = Mock("test_app", outfile=self.mock_outfile)
        self.mock_app_class = Mock(self.app_class_name,
                                   outfile=self.mock_outfile)
        self.mock_app_class.mock_returns = self.mock_app
        mock(self.app_class_name,
             mock_obj=self.mock_app_class,
             nsdicts=[self.program_module.__dict__])

        super(Test_ProgramMain, self).setUp()
Beispiel #32
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')
Beispiel #33
0
 def setUp(self):
     super(FanInQueueDispatchTest, self).setUp()
     setUpByString(self,
                   FAN_IN_MACHINE,
                   machineName='FanInMachine',
                   instanceName='foo')
     mock('config.currentConfiguration',
          returns=self.currentConfig,
          tracker=None)
     for i in range(20):
         SimpleModel(key_name='%d' % i).put()
     FanInAction.CALLS = 0
     self.context = None
     self.obj = None
Beispiel #34
0
    def test_initialDispatchEmitsEventAsTask(self):
        mockQueue = TaskQueueDouble()
        mock(name='Queue.add', returns_func=mockQueue.add, tracker=None)

        event = self.context.initialize()
        self.assertEquals(len(mockQueue.tasks), 1)

        self.context.dispatch(event, {})

        self.assertEquals(len(mockQueue.tasks), 2)
        (task, transactional) = mockQueue.tasks[1]

        # state-initial is the state we're transitioning FROM
        self.assertTaskUrlHasStateAndEvent(task, 'state-initial', 'next-event')
Beispiel #35
0
    def setUp(self):
        super(TaskQueueFSMRetryTests, self).setUp()
        filename = 'test-TaskQueueFSMRetryTests.yaml'
        machineName = getMachineNameByFilename(filename)
        self.factory = getFSMFactoryByFilename(filename)
        self.context = self.factory.createFSMInstance(machineName)

        self.mockQueue = TaskQueueDouble()
        mock(name='Queue.add', returns_func=self.mockQueue.add, tracker=None)
        self.loggingDouble = getLoggingDouble()

        # drive the machine to ready
        self.initEvent = self.context.initialize()
        self.mockQueue.purge()  # clear the initialization task
Beispiel #36
0
 def setUp(self):
     super(SpawnTests, self).setUp()
     filename = 'test-TaskQueueFSMTests.yaml'
     setUpByFilename(self, filename)
     self.machineName = getMachineNameByFilename(filename)
     self.mockQueue = TaskQueueDouble()
     mock(name='Queue.add', returns_func=self.mockQueue.add, tracker=None)
     # dispatch initial event to get context in correct state
     self.taskName = 'foo'
     self.obj = {TASK_NAME_PARAM: self.taskName}
     self.context.dispatch(FSM.PSEUDO_INIT, self.obj)
     # but now flush the task queue to remove the event that we just dispatched;
     # we're only interested in testing spawn tasks
     self.mockQueue.purge()
Beispiel #37
0
 def test_pksi_dh(self):
     with umock.patch.object(active_site_finder.common.ActiveSiteAnalysis, "scaffold_matches") as mocked_match:
         mocked_match.return_value = True
         for values in ["GGP", "HPP", "HGG", "NNN", "HGP"]:
             mock("active_site_finder.common.ActiveSiteAnalysis.get_alignments",
                  returns=[DummyAlignment(values, {5: values[0], 39: values[1], 44: values[2]})])
             pairings = analysis.asp_pksi_dh(self.record)
             assert pairings == [(values, "catalytic triad H,G,P found: %s" % (values == "HGP"))]
         # and an inconclusive
         mocked_match.return_value = False
         # values here don't matter
         mock("active_site_finder.common.ActiveSiteAnalysis.get_alignments",
              returns=[DummyAlignment("incon", {})])
         pairings = analysis.asp_pksi_dh(self.record)
         assert pairings == [("incon", "catalytic triad H,G,P inconclusive")]
Beispiel #38
0
 def test_kr_stereo(self):
     for char in string.ascii_uppercase:
         mock("active_site_finder.common.ActiveSiteAnalysis.get_alignments",
              returns=[DummyAlignment("match", {102: char})])
         pairings = analysis.pksi_kr_stereo(self.record)
         if char == "D":
             assert pairings == [(
                 "match",
                 "KR domain putatively catalyzing D-configuration product formation"
             )]
         else:
             assert pairings == [(
                 "match",
                 "KR domain putatively catalyzing L-configuration product formation"
             )]
Beispiel #39
0
    def test_taskQueueOnQueueSpecifiedAtTransitionLevel(self):
        mockQueue = TaskQueueDouble()
        mock(name='Queue.__init__',
             returns_func=mockQueue.__init__,
             tracker=None)
        mock(name='Queue.add', returns_func=mockQueue.add, tracker=None)

        self.transNormalToFinal.queueName = 'fantasm-queue'  # should be this one (dest state)
        self.transInitialToNormal.queueName = 'barfoo'
        self.context.queueName = 'foobar'

        self.context.currentState = self.stateInitial
        self.context.dispatch('next-event', {})

        self.assertEquals(mockQueue.name, 'fantasm-queue')
Beispiel #40
0
    def test_get_git_vesion(self):
        "Test utils.get_git_version()"
        mock('utils.execute', tracker=self.tt, returns=('deadbeef', '', 0))

        expected_trace = r"""  Called utils.execute(['git', 'rev-parse', '--short', 'HEAD'])
  Called utils.execute(['git', 'rev-parse', '--short', 'HEAD'])"""

        ret = utils.get_git_version()
        self.assertEqual(ret, 'deadbeef')

        mock('utils.execute', tracker=self.tt, raises=OSError)
        ret = utils.get_git_version()
        self.assertEqual(ret, '')

        assert_same_trace(self.tt, expected_trace)
Beispiel #41
0
 def test_KS_N(self):
     mock("subprocessing.run_hmmpfam2",
          returns=parse_hmmpfam_results("KS_N.output"))
     results = analysis.asp_ks(self.record)
     expected = {
         "PKS_KS0":
         'found active site cysteine: False, scaffold matched GSSS: True',
         "PKS_KS1":
         'found active site cysteine: False, scaffold matched GSSS: False',
         "PKS_KS2":
         'found active site cysteine: False, scaffold matched GSSS: False',
         "PKS_KS3":
         'found active site cysteine: False, scaffold matched GSSS: False'
     }
     assert {dom.domain_id: message for dom, message in results} == expected
Beispiel #42
0
 def test_AT(self):
     mock("subprocessing.run_hmmpfam2",
          returns=parse_hmmpfam_results("AT.output"))
     results = analysis.asp_at(self.record)
     expected = {
         "PKS_AT0":
         "found active site serine: True, scaffold matched GHGE: False",
         "PKS_AT1":
         "found active site serine: False, scaffold matched GHGE: True",
         "PKS_AT2":
         "found active site serine: False, scaffold matched GHGE: True",
         "PKS_AT3":
         "found active site serine: False, scaffold matched GHGE: False"
     }
     assert {dom.domain_id: message for dom, message in results} == expected
Beispiel #43
0
 def test_p450(self):
     with umock.patch.object(active_site_finder.common.ActiveSiteAnalysis, "scaffold_matches") as mocked_match:
         mocked_match.return_value = True
         for char in string.ascii_uppercase:
             mock("active_site_finder.common.ActiveSiteAnalysis.get_alignments",
                  returns=[DummyAlignment(char, {407: char})])
             pairings = analysis.asp_p450_oxy(self.record)
             assert pairings == [(char, "active site cysteine present: %s" % (char == "C"))]
         # and an inconclusive
         mocked_match.return_value = False
         # values here don't matter
         mock("active_site_finder.common.ActiveSiteAnalysis.get_alignments",
              returns=[DummyAlignment("incon", {})])
         pairings = analysis.asp_p450_oxy(self.record)
         assert pairings == [("incon", "active site cysteine inconclusive")]
Beispiel #44
0
 def setUp(self):
     super(SendLogLineTest, self).setUp()
     self.server = models.Server.create()
     models.User.create_user('1234', email='*****@*****.**')
     self.user = models.User.lookup(email='*****@*****.**')
     self.interesting_log_line = models.LogLine.create(
         self.server, self.INTERESTING_LOG_LINE, 'US/Central')
     self.uninteresting_log_line = models.LogLine.create(
         self.server, self.UNINTERESTING_LOG_LINE, 'US/Central')
     self.tracker = minimock.TraceTracker()
     minimock.mock('channel.ServerChannels.get_client_ids',
                   returns=['client_id'],
                   tracker=None)
     minimock.mock('channel.ServerChannels.send_message',
                   tracker=self.tracker)
Beispiel #45
0
    def setUp(self):
        self.user = UserFactory()
        self.decision = DecisionFactory()

        # Ensure value of "now" always increases by amount sufficient
        # to show up as a change, even if db resolution for datetime
        # is one second.
        def now_iter(start):
            t = start
            while True:
                t += datetime.timedelta(hours=1)
                yield t

        minimock.mock("timezone.now",
                      returns_iter=now_iter(timezone.now()),
                      tracker=None)
Beispiel #46
0
    def test_generate_namespace(self):
        "test generate_namespace() method"

        mydb = db.aSDB(self.options)

        mock('BioSeqDatabase.DBServer.new_database',
             tracker=self.trace_tracker,
             returns=["mock result"])
        expected = """Called BioSeqDatabase.DBServer.new_database(
        db_name='test',
        description='test namespace for nosetests')
        """

        mydb.generate_namespace(self.options.BioSQLnamespace,
                                'test namespace for nosetests')
        assert_same_trace(self.trace_tracker, expected)
Beispiel #47
0
 def setUp(self):
     self.domains = [
         'Condensation', 'AMP-binding', 'PP-binding', 'Condensation',
         'A-OX', 'PP-binding', 'PKS_AT', 'hyb_KS', 'PP-binding', 'PF00561',
         'Peptidase_S9', 'LANC_like', 'Pkinase', 'p450', 'Abi', 'DUF4135',
         'Condensation', 'AMP-binding', 'PP-binding', 'Condensation',
         'AMP-binding', 'PP-binding', 'PF07366', 'adh_short',
         'adh_short_C2', 'p450', 'PF12697', 'PP-binding', 'PKS_AT',
         'mod_KS', 'hyb_KS', 'adh_short', 'PP-binding', 'PKS_AT', 'mod_KS',
         'adh_short', 'PP-binding', 'PKS_AT', 'mod_KS', 'adh_short',
         'NAD_binding_4', 'Condensation', 'PP-binding'
     ]
     mock("lanthi.run_rodeo", returns=20)
     self.cds = DummyCDS(38, 48)
     # an all_orf detected gene at 7922405:7922549 in CP013129.1, with a C appended
     self.cds.translation = "VCGPRDHGRQRTSAPHAFHSDSMDRAASRPVEYGDYSGSPLSQGLGGC"
Beispiel #48
0
    def test_encode_failed_returncode_1(self):
        """encode test with failed"""
        mock('encoder.subprocess.Popen', returns=Mock(
            'proc',
            communicate=Mock(
                'proc.communicate',
                returns=(b'', b'')),
            returncode=1))

        dummy_src_file = 'aaa.m2ts'
        args = (dummy_src_file, 'bbb.mp4')
        kwargs = {'reso': '1280x720', 'vb_mbps': 2, 'ab_kbps': 256, 'is_deint': False}

        self.assertRaises(ConvertError, encoder.encode, *args, **kwargs)
        self.assertTrue(os.path.isfile(os.path.splitext(dummy_src_file)[0] + '.log'))

        os.remove(os.path.splitext(dummy_src_file)[0] + '.log')
Beispiel #49
0
    def test_run_hmmsearch(self):
        "Test utils.run_hmmsearch()"
        mock('Bio.SearchIO.parse', tracker=self.tt, returns=['mock result'])
        mock('utils.execute', tracker=self.tt, returns=('output', 'error', 0))

        expected = r"""    Called utils.execute(
        ['hmmsearch', '--cpu', '2', '-o', '/dev/null', '--domtblout', 'result.domtab', 'fake.hmm', '-'],
        input='>testinput\nMADEUP')
    Called Bio.SearchIO.parse(
        'result.domtab', 'hmmsearch3-domtab')"""

        hits = utils.run_hmmsearch('fake.hmm', ">testinput\nMADEUP")
        self.assertEqual(len(hits), 1)

        hit = hits.pop()
        self.assertEqual('mock result', hit)
        assert_same_trace(self.tt, expected)
Beispiel #50
0
    def test_DatastoreFSMContinuationFanInTests_write_lock_error(self):
        obj = TemporaryStateObject()
        obj[TASK_NAME_PARAM] = 'taskName'

        event = self.context.initialize()  # queues the first task
        self.assertEqual('pseudo-init', self.context.currentState.name)

        event = self.context.dispatch(event, obj)
        self.assertEqual('state-initial', self.context.currentState.name)

        mock('memcache.incr', returns=1, tracker=None)

        # the .dispatch() takes the machine into "state-continuation" and the queueDispatch() looks
        # ahead to determine that _queueDispatchFanIn() is required, which raises the expected error
        # due to lock acquisition problems
        self.assertRaises(FanInWriteLockFailureRuntimeError,
                          self.context.dispatch, event, obj)
Beispiel #51
0
    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
Beispiel #52
0
    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
Beispiel #53
0
    def test__run_external_tool(self):
        "Test active_site_finder._run_external_tool method"

        self.tt = TraceTracker()

        SeqFeatureList = utils.get_all_features_of_type_with_query(
            self.seq_record, "PFAM_domain", "domain", "p450")
        self.assertEqual(6, len(SeqFeatureList))

        mock(
            'antismash.generic_modules.active_site_finder.active_site_finder._execute_tool',
            returns=["external program call successful"],
            tracker=self.tt)

        result = self.my_ASF._run_external_tool(self.ETObj.find('./analysis'),
                                                SeqFeatureList)
        expected = ["external program call successful"]
        self.assertListEqual(result, expected)
Beispiel #54
0
    def test_run_hmmpfam2(self):
        "Test utils.run_hmmpfam2()"
        mock('Bio.SearchIO.parse', tracker=self.tt, returns=['mock result'])
        mock('utils.execute', tracker=self.tt, returns=('output', 'error', 0))

        expected = r"""    Called utils.execute(
        ['hmmpfam2', '--cpu', '2', 'fake.hmm', '-'],
        input='>testinput\nMADEUP')
    Called Bio.SearchIO.parse(
        <cStringIO.StringI object at ...>,
        'hmmer2-text')"""

        hits = utils.run_hmmpfam2('fake.hmm', ">testinput\nMADEUP")
        self.assertEqual(len(hits), 1)

        hit = hits.pop()
        self.assertEqual('mock result', hit)
        assert_same_trace(self.tt, expected)
Beispiel #55
0
    def test_alignment_generation(self):
        pregenerated = list(
            SearchIO.parse(
                open(path.get_full_path(__file__, 'data', 'KS_N.output')),
                "hmmer2-text"))
        mock("subprocessing.run_hmmpfam2", returns=pregenerated)

        domains = self.generate_domains()
        analysis = ActiveSiteAnalysis("PKS_KS", domains, "PKSI-KS_N.hmm2",
                                      [176, 186, 187, 188],
                                      ['G', 'S', 'S', 'S'])
        assert {"PKS_KS"} == {
            domain.domain
            for domain in analysis.domains_of_interest
        }
        alignments = analysis.get_alignments()
        assert len(alignments) == 4
        assert [align.domain for align in alignments[:4]] == domains[:4]
Beispiel #56
0
 def test_er_stereo(self):
     with umock.patch.object(active_site_finder.common.ActiveSiteAnalysis, "scaffold_matches") as mocked_match:
         mocked_match.return_value = True
         for char in string.ascii_uppercase:
             mock("active_site_finder.common.ActiveSiteAnalysis.get_alignments",
                  returns=[DummyAlignment(char, {39: char})])
             pairings = analysis.pksi_er_stereo(self.record)
             if char == "Y":
                 assert pairings == [(char, "ER domain putatively catalyzing 2S-configuration product formation")]
             else:
                 assert pairings == [(char, "ER domain putatively catalyzing 2R-configuration product formation")]
         # and an inconclusive
         mocked_match.return_value = False
         # values here don't matter
         mock("active_site_finder.common.ActiveSiteAnalysis.get_alignments",
              returns=[DummyAlignment("incon", {})])
         pairings = analysis.pksi_er_stereo(self.record)
         assert pairings == [("incon", "ER configuration inconclusive")]
Beispiel #57
0
    def test_acquireReadLock_one_wait_iter(self):
        lock = ReadWriteLock('foo', self.context)
        index = lock.currentIndex()
        self.assertEqual(None, memcache.get(lock.lockKey(index)))
        lock.acquireWriteLock(index)
        self.assertEqual('65537', memcache.get(lock.lockKey(index)))

        def sleepAndRelease(seconds):  # pylint: disable-msg=W0613
            lock.releaseWriteLock(index)

        mock('time.sleep', returns_func=sleepAndRelease, tracker=None)
        lock.acquireReadLock(index)
        self.assertEqual('32768', memcache.get(lock.lockKey(index)))
        self.assertEqual(
            ["Tried to acquire read lock 'foo-lock-3626764237' 1 times..."],
            self.loggingDouble.messages['debug'])
        self.assertEqual([
            "Gave up waiting for all fan-in work items with read lock 'foo-lock-3626764237'."
        ], self.loggingDouble.messages['critical'])
Beispiel #58
0
 def setup(self):
     raimei.vim = None
     mock("raimei.vim")
     raimei.vim.current = Mock(
         "current",
         window=Mock(
             "window",
             cursor=Mock("cursor"),
         ),
         range=Mock(
             "range",
             start=Mock("start"),
             end=Mock("end"),
         ),
     )
     utils.vim = None
     mock("utils.vim")
     _eval_func = lambda var: self.eval_var[var]
     utils.vim.eval = Mock("eval", returns_func=_eval_func)
Beispiel #59
0
 def setUp(self):
     super(UsernameClaimTest, self).setUp()
     self.params = {'username': '******', 'password': '******'}
     self.response_data = Object()
     self.response_data.content = json.dumps({
         "accessToken": "random access token",
         "clientToken": "mc-coal",
         "availableProfiles": [
             {
                 "id": "profile identifier",
                 "name": "steve",
             }
         ],
         "selectedProfile": {
             "id": "profile identifier",
             "name": "steve",
         }
     })
     minimock.mock('urlfetch.fetch', returns=self.response_data, tracker=None)
Beispiel #60
0
    def test_get_fail_intermittent(self):
        """Fail shorthash retrieval twice"""

        shs = map(self.make_mock_photo, map(str, range(10)))

        fails = []
        old_open = urllib2.urlopen

        def _(request):
            fails.append(True)

            if len(fails) < 3:
                raise IOError()
            else:
                return old_open(request)

        minimock.mock('urllib2.urlopen', returns_func=_)

        assert set(self.index.refresh()) == set(shs)