コード例 #1
0
 def assert_response(_):
     self.assertEqual(201, request.code)
     self.assertEqual('/attachment/%s' % attachment_id, request.responseHeaders.getRawHeaders("location")[0])
     response_json = {'ident': attachment_id, 'content-type': 'some mocked type',
                      'name': 'filename.txt', 'size': 17, 'encoding': 'base64'}
     self.assertEqual(response_json, json.loads(request.written[0]))
     verify(self.mail_service).save_attachment('some mocked value', 'some mocked type')
コード例 #2
0
    def test_should_return_module_when_loading_project_module_and_import_raises_exception(self):
        module = mock()
        when(imp).load_source("build", "spam").thenReturn(module)

        self.assertEquals(module, self.reactor.load_project_module("spam"))

        verify(imp).load_source("build", "spam")
コード例 #3
0
 def assert_login_setup_service_for_user(_):
     verify(self.portal).login(ANY(), None, IResource)
     verify(self.services_factory).is_logged_in('some_user_uuid')
     verifyNoMoreInteractions(self.services_factory)
     interstitial_js_in_template = '<script src="startup-assets/Interstitial.js"></script>'
     self.assertIn(interstitial_js_in_template, self.request.written[0])
     self.assertTrue(self.resource.is_logged_in(self.request))
コード例 #4
0
    def test_catches_exceptions_to_not_break_other_listeners(self):
        when(logger).error(ANY()).thenReturn(None)
        listener = MailboxIndexerListener('INBOX', self.mail_store, mock())

        yield listener.notify_new()

        verify(logger).error(ANY())
コード例 #5
0
    def test_should_raise_exception_when_loading_project_module_and_import_raises_exception(self):
        when(imp).load_source("build", "spam").thenRaise(ImportError("spam"))

        self.assertRaises(
            PyBuilderException, self.reactor.load_project_module, "spam")

        verify(imp).load_source("build", "spam")
コード例 #6
0
ファイル: test_bank.py プロジェクト: BenjaminVanRyseghem/SVL
 def test_credit_errone_ne_debite_pas(self):
     """Test si quand le credit n'est pas possible, il n'y a pas de debit"""
     
     amount = 100
     when(self.accountDest).can_accept_credit(amount).thenReturn(False)
     self.assertRaises(ValueError, self.transfer.transfer, amount)
     verify(self.accountSrc, never).debit(amount)    
コード例 #7
0
    def testVerifiesMultipleCallsOnClassmethod(self):
        when(Dog).bark().thenReturn("miau!")

        Dog.bark()
        Dog.bark()

        verify(Dog, times=2).bark()
コード例 #8
0
ファイル: test_bank.py プロジェクト: BenjaminVanRyseghem/SVL
 def test_transfert_credite_le_bon_compte(self):
     """Test si lors du transfert la valeur est bien creditee a la destination"""
   
     amount = 100
     when(self.accountDest).can_accept_credit(amount).thenReturn(True)
     self.transfer.transfer(amount)
     verify(self.accountDest, times=1).credit(amount)
コード例 #9
0
ファイル: test_bank.py プロジェクト: BenjaminVanRyseghem/SVL
 def test_transfert_credite_et_debite_de_la_meme_valeur(self):  
     """Test que lors d'un transfert la valeur debitee et creditee est la meme"""  
     amount = 100
     when(self.accountDest).can_accept_credit(amount).thenReturn(True)
     self.transfer.transfer(amount)
     verify(self.accountDest, times=1).credit(amount)
     verify(self.accountSrc, times=1).debit(amount)
コード例 #10
0
    def test_glob_should_return_list_with_single_module_when_directory_contains_package(self):
        when(os).walk("spam").thenReturn([("spam", ["eggs"], []),
                                         ("spam/eggs", [], ["__init__.py"])])

        self.assertEquals(["eggs"], discover_modules_matching("spam", "*"))

        verify(os).walk("spam")
コード例 #11
0
ファイル: test_bank.py プロジェクト: BenjaminVanRyseghem/SVL
    def test_transfert_debite_le_bon_compte(self):
        """Test si lors du transfert la valeur est bien debitee de la source"""

        amount = 100
        when(self.accountDest).can_accept_credit(amount).thenReturn(True)
        self.transfer.transfer(amount)
        verify(self.accountSrc, times=1).debit(amount)
コード例 #12
0
    def test_getPlayerList(self):
        """
        Query the game server for connected players.
        return a dict having players' id for keys and players' data as another dict for values
        """
        when(self.output_mock).write('status', maxRetries=anything()).thenReturn("""
map: ut4_casa
num score ping name            lastmsg  address              qport rate
--- ----- ---- --------------- ------- --------------------- ----- -----
10     0   13 snowwhite        0       192.168.1.11:51034     9992 15000
12     0   10 superman         0       192.168.1.12:53039     9993 15000
""")
        result = self.console.getPlayerList()
        verify(self.output_mock).write('status', maxRetries=anything())
        self.assertDictEqual({'10': {'ip': '192.168.1.11',
                                     'last': '0',
                                     'name': 'snowwhite',
                                     'pbid': None,
                                     'ping': '13',
                                     'port': '51034',
                                     'qport': '9992',
                                     'rate': '15000',
                                     'score': '0',
                                     'slot': '10'},
                              '12': {'ip': '192.168.1.12',
                                     'last': '0',
                                     'name': 'superman',
                                     'pbid': None,
                                     'ping': '10',
                                     'port': '53039',
                                     'qport': '9993',
                                     'rate': '15000',
                                     'score': '0',
                                     'slot': '12'}}
            , result)
コード例 #13
0
 def test_should_only_match_py_files_regardless_of_glob(self):
     when(os).walk("pet_shop").thenReturn([("pet_shop", [],
                                            ["parrot.txt", "parrot.py", "parrot.pyc", "parrot.py~", "slug.py"])])
     expected_result = ["parrot"]
     actual_result = discover_modules_matching("pet_shop", "*parrot*")
     self.assertEquals(set(expected_result), set(actual_result))
     verify(os).walk("pet_shop")
コード例 #14
0
 def test_saybig(self):
     """
     broadcast a message to all players in a way that will catch their attention.
     """
     self.console.msgPrefix = "B3:"
     self.console.saybig("something")
     verify(self.output_mock).write('bigtext "B3: something"')
コード例 #15
0
 def test_rotateMap(self):
     """
     load the next map/level
     """
     with patch("time.sleep"):
         self.console.rotateMap()
     verify(self.output_mock).write('cyclemap')
コード例 #16
0
    def test_should_install_dependency_without_version_on_windows_derivate(self):
        dependency = Dependency("spam")

        install_dependency(self.logger, self.project, dependency)

        verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command(
            PIP_EXEC_STANZA + ["install", "spam"], any_value(), env=any_value(), shell=False)
コード例 #17
0
 def test_say(self):
     """
     broadcast a message to all players
     """
     self.console.msgPrefix = "B3:"
     self.console.say("something")
     verify(self.output_mock).write('say B3: something')
コード例 #18
0
    def test_should_install_dependency_with_url_even_if_version_is_given(self):
        dependency = Dependency("spam", version="0.1.2", url="some_url")

        install_dependency(self.logger, self.project, dependency)

        verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command(
            PIP_EXEC_STANZA + ["install", "--force-reinstall", 'some_url'], any_value(), env=any_value(), shell=False)
コード例 #19
0
    def test_should_install_requirements_file_dependency(self):
        dependency = RequirementsFile("requirements.txt")

        install_dependency(self.logger, self.project, dependency)

        verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command(
            PIP_EXEC_STANZA + ["install", '-r', "requirements.txt"], any_value(), env=any_value(), shell=False)
コード例 #20
0
    def test_should_install_dependency_without_version(self):
        dependency = Dependency("spam")

        install_dependency(self.logger, self.project, dependency)

        verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command(
            "pip install 'spam'", any_value(), shell=True)
コード例 #21
0
    def test_should_install_dependency_with_version_and_operator(self):
        dependency = Dependency("spam", "==0.1.2")

        install_dependency(self.logger, self.project, dependency)

        verify(pybuilder.plugins.python.install_dependencies_plugin).execute_command(
            PIP_EXEC_STANZA + ["install", 'spam==0.1.2'], any_value(), env=any_value(), shell=False)
コード例 #22
0
    def test_mark_as_read(self):
        mail = LeapMail('id', 'INBOX')
        when(self.mail_store).get_mail(ANY(), include_body=True).thenReturn(mail)
        yield self.mail_service.mark_as_read(1)

        self.assertIn(Status.SEEN, mail.flags)
        verify(self.mail_store).update_mail(mail)
コード例 #23
0
 def test_find_with_link_synonym(self):
     finder = ElementFinder()
     browser = mock()
     when(browser).get_current_url().thenReturn("http://localhost/mypage.html")
     finder.find(browser, "test1", tag='link')
     verify(browser).find_elements_by_xpath(
         "//a[(@id='test1' or @name='test1' or @href='test1' or normalize-space(descendant-or-self::text())='test1' or @href='http://localhost/test1')]")
コード例 #24
0
ファイル: test_models.py プロジェクト: NeCTAR-RC/trove
 def test_delete_backup_fail_delete_segment(self):
     when(self.swift_client).delete_object(any(), "second").thenRaise(ClientException("foo"))
     self.assertRaises(TroveError, taskmanager_models.BackupTasks.delete_backup, "dummy context", self.backup.id)
     verify(backup_models.Backup, never).delete(self.backup.id)
     self.assertEqual(
         backup_models.BackupState.DELETE_FAILED, self.backup.state, "backup should be in DELETE_FAILED status"
     )
コード例 #25
0
 def test_find_with_text_field_synonym(self):
     finder = ElementFinder()
     browser = mock()
     when(browser).get_current_url().thenReturn("http://localhost/mypage.html")
     finder.find(browser, "test1", tag='text field')
     verify(browser).find_elements_by_xpath(
         "//input[@type='text' and (@id='test1' or @name='test1' or @value='test1' or @src='test1' or @src='http://localhost/test1')]")
コード例 #26
0
    def testSpy2(self):
        spy2('os.path.exists')

        import os.path
        assert not os.path.exists('/Foo')

        verify('os.path', times=1).exists('/Foo')
コード例 #27
0
    def testReconfigureStrictMock(self):
        when(Dog).bark()  # important first call, inits theMock

        when(Dog, strict=False).waggle().thenReturn('Sure')
        expect(Dog, strict=False).weggle().thenReturn('Sure')


        with pytest.raises(InvocationError):
            when(Dog).wuggle()

        with pytest.raises(InvocationError):
            when(Dog).woggle()

        rex = Dog()
        assert rex.waggle() == 'Sure'
        assert rex.weggle() == 'Sure'

        # For documentation; the inital strict value of the mock will be used
        # here. So the above when(..., strict=False) just assures we can
        # actually *add* an attribute to the mocked object
        with pytest.raises(InvocationError):
            rex.waggle(1)

        verify(Dog).waggle()
        verify(Dog).weggle()
コード例 #28
0
 def test_find_with_img(self):
     finder = ElementFinder()
     browser = mock()
     when(browser).get_current_url().thenReturn("http://localhost/mypage.html")
     finder.find(browser, "test1", tag='img')
     verify(browser).find_elements_by_xpath(
         "//img[(@id='test1' or @name='test1' or @src='test1' or @alt='test1' or @src='http://localhost/test1')]")
コード例 #29
0
    def testVerify(self):
        when('os.path').exists('/Foo').thenReturn(True)

        import os.path
        os.path.exists('/Foo')

        verify('os.path', times=1).exists('/Foo')
コード例 #30
0
    def test_delete_mail(self):
        mail_to_delete = LeapMail(1, 'INBOX')
        when(self.mail_store).get_mail(1, include_body=True).thenReturn(defer.succeed(mail_to_delete))

        yield self.mail_service.delete_mail(1)

        verify(self.mail_store).move_mail_to_mailbox(1, 'TRASH')
コード例 #31
0
    def testVerifiesUsingContainsMatcher(self):
        ourMock = mock()
        ourMock.foo("foobar")

        verify(ourMock).foo(contains("foo"))
        verify(ourMock).foo(contains("bar"))
コード例 #32
0
 def assert_removed_from_drafts(_):
     verify(self.drafts).remove(any())
コード例 #33
0
 def test_open_browser_no_get(self):
     browser = mock()
     when(self.brorser)._make_driver('firefox', None, None, False, None,
                                     None).thenReturn(browser)
     self.brorser.open_browser()
     verify(browser, times=0).get(ANY)
コード例 #34
0
 def test_close_services_closes_the_underlying_leap_session(self):
     self.services.close()
     verify(self.leap_session).close()
コード例 #35
0
    def test_rogerDeploy_with_skip_gitpull_true(self):
        settings = mock(Settings)
        appConfig = mock(AppConfig)
        roger_deploy = RogerDeploy()
        marathon = mock(Marathon)
        gitObj = mock(GitUtils)
        mockedHooks = mock(Hooks)
        roger_deploy.rogerGitPullObject = mock(RogerGitPull)
        roger_deploy.rogerPushObject = mock(RogerPush)
        roger_deploy.rogerBuildObject = mock(RogerBuild)
        roger_deploy.dockerUtilsObject = mock(DockerUtils)
        roger_deploy.dockerObject = mock(Docker)
        roger_deploy.utils = mock(Utils)

        roger_env = self.roger_env

        repo_name = 'roger'
        repo_url = 'test_url'
        random = 'test'

        config = self.config
        data = self.data
        when(marathon).getCurrentImageVersion(
            any(), any(), any()).thenReturn("testversion/v0.1.0")
        when(marathon).getName().thenReturn('Marathon')
        frameworkUtils = mock(FrameworkUtils)

        sc = mock(StatsClient)
        when(sc).timing(any(), any()).thenReturn(any())
        when(roger_deploy.utils).getStatsClient().thenReturn(sc)
        when(roger_deploy.utils).get_identifier(any(), any(), any()).thenReturn(any())
        when(roger_deploy.utils).extract_app_name(any()).thenReturn("test")

        when(frameworkUtils).getFramework(data).thenReturn(marathon)
        when(settings).getConfigDir().thenReturn(any())
        when(settings).getCliDir().thenReturn(any())
        when(settings).getUser().thenReturn('test_user')
        when(appConfig).getRogerEnv(any()).thenReturn(roger_env)
        when(appConfig).getConfig(any(), any()).thenReturn(config)
        when(appConfig).getAppData(any(), any(), any()).thenReturn(data)

        when(appConfig).getRepoUrl(any()).thenReturn(repo_name)
        when(appConfig).getRepoName(any()).thenReturn(repo_name)

        when(mockedHooks).run_hook(any(), any(), any(), any()).thenReturn(0)

        when(gitObj).gitPull(any()).thenReturn(0)
        when(gitObj).gitShallowClone(any(), any()).thenReturn(0)
        when(gitObj).gitClone(any(), any()).thenReturn(0)
        when(gitObj).getGitSha(any(), any(), any()).thenReturn(random)

        when(roger_deploy.rogerGitPullObject).main(any(), any(), any(), any(), any()).thenReturn(0)
        when(roger_deploy.rogerPushObject).main(any(), any(), any(), any(), any()).thenReturn(0)

        args = self.args
        args.directory = ""
        args.secrets_file = ""
        args.environment = "dev"
        args.skip_push = True
        args.skip_gitpull = True
        args.application = 'grafana_test_app'
        args.config_file = 'test.json'
        args.skip_build = True
        args.branch = None
        os.environ["ROGER_CONFIG_DIR"] = self.configs_dir
        roger_deploy.main(settings, appConfig, frameworkUtils, gitObj, mockedHooks, args)
        verify(roger_deploy.rogerGitPullObject, times=0).main(any(), any(), any(), any(), any())
コード例 #36
0
    def testStubsAndVerifies(self):
        theMock = mock()
        when(theMock).foo().thenReturn("foo")

        self.assertEquals("foo", theMock.foo())
        verify(theMock).foo()
コード例 #37
0
    def testDoesNotVerifyStubbedCalls(self):
        theMock = mock()
        when(theMock).foo().thenReturn(1)

        verify(theMock, times=0).foo()
コード例 #38
0
    def test_should_issue_hello_world_message(self):
        out = mock()

        helloworld(out)

        verify(out).write("Hello world of Python\n")
コード例 #39
0
 def test_find_by_row_with_css_locator(self):
     when(self._browser).find_elements_by_css_selector(
         "table#test1 tr:nth-child(2)").thenReturn([])
     self.finder.find_by_row("css=table#test1", 2, 'hi')
     verify(self._browser).find_elements_by_css_selector("table#test1 "
                                                         "tr:nth-child(2)")
コード例 #40
0
    def test_module_should_issue_hello_world_message(self):
        out = mock()

        hello_module(out)

        verify(out).write("Hello world from python module\n")
コード例 #41
0
 def test_find_by_footer_with_css_locator(self):
     when(self._browser).find_elements_by_css_selector(
         "table#test1 tfoot td").thenReturn([])
     self.finder.find_by_footer("css=table#test1", 'hi')
     verify(self._browser).find_elements_by_css_selector(
         "table#test1 tfoot td")
コード例 #42
0
    def test_the_container_is_run(self):
        self.stage.execute(self.submission)

        verify(self.container).run()
コード例 #43
0
 def test_find_with_implicit_css_locator(self):
     when(self._browser).find_elements_by_css_selector(
         "table#test1").thenReturn([])
     self.finder.find("test1")
     verify(self._browser).find_elements_by_css_selector("table#test1")
コード例 #44
0
 def test_find_by_footer_with_xpath_locator(self):
     when(self._browser).find_elements_by_xpath(
         "//table[@id='test1']//tfoot//td").thenReturn([])
     self.finder.find_by_footer("xpath=//table[@id='test1']", 'hi')
     verify(self._browser).find_elements_by_xpath("//table[@id='test1']"
                                                  "//tfoot//td")
コード例 #45
0
 def test_isRecording_False(self):
     when(self.conn).isTunerRecording(any(int)).thenReturn(False)
     self.assertFalse(self.tuner.isRecording())
     verify(self.conn).isTunerRecording(any(int))
コード例 #46
0
 def test_find_with_css_selector(self):
     elements = self._make_mock_elements('table', 'table', 'table')
     when(self._browser).find_elements_by_css_selector(
         "table#test1").thenReturn(elements)
     self.assertEqual(self.finder.find("css=table#test1"), elements[0])
     verify(self._browser).find_elements_by_css_selector("table#test1")
コード例 #47
0
 def test_delete_backup_nolocation(self):
     self.backup.location = ''
     taskmanager_models.BackupTasks.delete_backup('dummy context',
                                                  self.backup.id)
     verify(self.backup).delete()
コード例 #48
0
 def test_find_by_row_with_xpath_locator(self):
     when(self._browser).find_elements_by_xpath(
         "//table[@id='test1']//tr[2]//*").thenReturn([])
     self.finder.find_by_row("xpath=//table[@id='test1']", 2, 'hi')
     verify(self._browser).find_elements_by_xpath("//table[@id='test1']"
                                                  "//tr[2]//*")
コード例 #49
0
ファイル: test_event.py プロジェクト: sriharikapu/plasma-cash
 def test_simple(self):
     global handler
     handler = mock()
     when(handler).__call__().thenReturn(None)
     emit('simple')
     verify(handler).__call__()
コード例 #50
0
 def test_isRecording_True(self):
     when(self.conn).isTunerRecording(4).thenReturn(True)
     result = self.tuner.isRecording()
     log.debug('isRecording_True = %s' % result)
     self.assertTrue(result)
     verify(self.conn).isTunerRecording(4)
コード例 #51
0
ファイル: shredgen.spec.py プロジェクト: eviljoe/shredgen
with description(shredgen) as self:
    with after.each:
        unstub()

    with description(shredgen.main):
        with before.each:
            self.opts = mock({})
            when(shredgen)._parse_opts(...).thenReturn(self.opts)
            when(shredgen)._update_default_opts(...)
            when(shredgen)._perform_user_action(...)
            when(shredgen)._print_err_and_usage(...)
            when(sys).exit(...)

        with it('parses the options'):
            shredgen.main()
            verify(shredgen)._parse_opts()

        with it('updates the default options'):
            shredgen.main()
            verify(shredgen)._update_default_opts(self.opts)

        with it('performs the user action'):
            shredgen.main()
            verify(shredgen)._perform_user_action(self.opts)

        with it('prints the error & usage when an error is raised'):
            err = shredgen.ExitCodeError('foo', 7)
            when(shredgen)._perform_user_action(...).thenRaise(err)
            shredgen.main()
            verify(shredgen)._print_err_and_usage(err)
コード例 #52
0
 def test_nominal(self):
     when(self.console).write()
     self.superadmin.clearMessageHistory()
     self.superadmin.says('!roundnext')
     self.assertEqual([], self.superadmin.message_history)
     verify(self.console).write(('mapList.runNextRound', ))
コード例 #53
0
    def test_start_starts_all_connections_and_joins_with_cmanager(self):
        self.botapp.start()

        m.verify(self.concurrency_manager, times=2).start(self.provided_client)
        m.verify(self.concurrency_manager).join()
コード例 #54
0
    def test_dont_pass_through_to_repo_if_present(self):
        self.__given_snapshot({"F1": FeatureState("F1", True)})

        feature_state = self.snapshot.get_feature_state("F1")
        self.assertTrue(feature_state.enabled)
        verify(self.state_repo, times=0).get_feature_state("F1")
コード例 #55
0
    def test_connections_are_not_started_for_unknown_servers(self):
        message = al.Message(self.server1_key + '!!!', None, None)
        self.connection_starter(message)

        m.verify(self.concurrency_manager, m.never).start(m.any())
コード例 #56
0
    def test_scan_calls_plugin_manager_scan(self):
        module = m.mock()

        self.botapp.scan(module)

        m.verify(self.plugin_manager).scan(module)
コード例 #57
0
 def testVerifyNeverCalled(self):
   verify(self.mock, never).someMethod()
コード例 #58
0
    def test_start_all_connections_starts_all_connections(self):
        self.connection_starter.start_all_connections()

        m.verify(self.concurrency_manager, times=2).start(self.provided_client)
コード例 #59
0
 def test_0(self):
     when(self.console).write().thenReturn()
     self.superadmin.message_history = []
     self.superadmin.says("!endround 0")
     verify(self.console).write(('mapList.endRound', '0'))
     self.assertEqual([], self.superadmin.message_history)
コード例 #60
0
 def testVerifyNeverCalledRaisesError(self):
   self.mock.foo()
   self.assertRaises(VerificationError, verify(self.mock, never).foo)