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')
Esempio n. 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")
 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))
    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())
Esempio n. 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")
Esempio n. 6
0
 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)    
Esempio n. 7
0
    def testVerifiesMultipleCallsOnClassmethod(self):
        when(Dog).bark().thenReturn("miau!")

        Dog.bark()
        Dog.bark()

        verify(Dog, times=2).bark()
Esempio n. 8
0
 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)
Esempio n. 9
0
 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)
Esempio n. 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")
Esempio n. 11
0
    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)
Esempio n. 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)
Esempio n. 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")
Esempio n. 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"')
Esempio n. 15
0
 def test_rotateMap(self):
     """
     load the next map/level
     """
     with patch("time.sleep"):
         self.console.rotateMap()
     verify(self.output_mock).write('cyclemap')
    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)
Esempio n. 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')
    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)
    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)
    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)
    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)
    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)
 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')]")
Esempio n. 24
0
 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"
     )
 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')]")
Esempio n. 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')
Esempio n. 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()
 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')]")
Esempio n. 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')
    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')
Esempio n. 31
0
    def testVerifiesUsingContainsMatcher(self):
        ourMock = mock()
        ourMock.foo("foobar")

        verify(ourMock).foo(contains("foo"))
        verify(ourMock).foo(contains("bar"))
Esempio n. 32
0
 def assert_removed_from_drafts(_):
     verify(self.drafts).remove(any())
 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)
 def test_close_services_closes_the_underlying_leap_session(self):
     self.services.close()
     verify(self.leap_session).close()
Esempio n. 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())
Esempio n. 36
0
    def testStubsAndVerifies(self):
        theMock = mock()
        when(theMock).foo().thenReturn("foo")

        self.assertEquals("foo", theMock.foo())
        verify(theMock).foo()
Esempio n. 37
0
    def testDoesNotVerifyStubbedCalls(self):
        theMock = mock()
        when(theMock).foo().thenReturn(1)

        verify(theMock, times=0).foo()
Esempio n. 38
0
    def test_should_issue_hello_world_message(self):
        out = mock()

        helloworld(out)

        verify(out).write("Hello world of Python\n")
 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)")
    def test_module_should_issue_hello_world_message(self):
        out = mock()

        hello_module(out)

        verify(out).write("Hello world from python module\n")
 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")
Esempio n. 42
0
    def test_the_container_is_run(self):
        self.stage.execute(self.submission)

        verify(self.container).run()
 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")
 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")
Esempio n. 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))
 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")
Esempio n. 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()
 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]//*")
Esempio n. 49
0
 def test_simple(self):
     global handler
     handler = mock()
     when(handler).__call__().thenReturn(None)
     emit('simple')
     verify(handler).__call__()
Esempio n. 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)
Esempio n. 51
0
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)
Esempio n. 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', ))
Esempio n. 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()
Esempio n. 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")
Esempio n. 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())
Esempio n. 56
0
    def test_scan_calls_plugin_manager_scan(self):
        module = m.mock()

        self.botapp.scan(module)

        m.verify(self.plugin_manager).scan(module)
Esempio n. 57
0
 def testVerifyNeverCalled(self):
   verify(self.mock, never).someMethod()
Esempio n. 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)
 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)
Esempio n. 60
0
 def testVerifyNeverCalledRaisesError(self):
   self.mock.foo()
   self.assertRaises(VerificationError, verify(self.mock, never).foo)