예제 #1
0
    def test_cvarlist(self):
        # GIVEN
        when(self.console).write("cvarlist").thenReturn(r"""cvarlist
        g_spskill "4"
        _B3 "B3 v1.9.0b2 [nt]"
S R     auth_status "public"
S R     auth "1"
S     C g_antilagvis "0"
     L  g_bombPlantTime "3"
S        Admin "Courgette"
     L  net_ip "localhost"
    AL  com_zoneMegs "32"
  R     sv_cheats "1"

347 total cvars
347 cvar indexes
""")
        # WHEN
        rv = self.console.cvarList()
        # THEN
        self.assertDictEqual({
            ' admin': 'Courgette',
            '_b3': 'B3 v1.9.0b2 [nt]',
            'auth': '1',
            'auth_status': 'public',
            'com_zonemegs': '32',
            'g_antilagvis': '0',
            'g_bombplanttime': '3',
            'g_spskill': '4',
            'net_ip': 'localhost',
            'sv_cheats': '1'
        }, rv)
예제 #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 test_interface_creation(self):
        name = "pepito"
        os = "Windows"
        host = Host(name, os)

        when(self._model_controller).find(host.getID()).thenReturn(host)

        name = ""
        mac = "00:00:00:00:00:00"
        ipv4_address = "0.0.0.0"
        ipv4_mask = "0.0.0.0"
        ipv4_gateway = "0.0.0.0"
        ipv4_dns = []
        ipv6_address = "0000:0000:0000:0000:0000:0000:0000:0000"
        ipv6_prefix = "00"
        ipv6_gateway = "0000:0000:0000:0000:0000:0000:0000:0000"
        ipv6_dns = []
        network_segment = ""
        hostname_resolution = []

        interface_id = self.client.createInterface(
            name, mac, ipv4_address, ipv4_mask, ipv4_gateway, ipv4_dns,
            ipv6_address, ipv6_prefix, ipv6_gateway, ipv6_dns, network_segment,
            hostname_resolution, host.getID())

        interface = Interface(
            name, mac, ipv4_address, ipv4_mask, ipv4_gateway, ipv4_dns,
            ipv6_address, ipv6_prefix, ipv6_gateway, ipv6_dns, network_segment,
            hostname_resolution, parent_id=host.getID())

        self.assertNotEquals(
            interface_id, None, "interface created shouldn't be None")

        self.assertEquals(
            interface.getID(), interface_id, "ids should be the same")
예제 #4
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)
예제 #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
    def test_swift_checksum_save(self):
        """This tests that SwiftStorage.save returns the swift checksum"""
        context = TroveContext()
        backup_id = '123'
        user = '******'
        password = '******'
        backup_container = 'database_backups'

        swift_client = FakeSwiftConnectionWithRealEtag()
        when(swift).create_swift_client(context).thenReturn(swift_client)
        storage_strategy = SwiftStorage(context)

        with MockBackupRunner(filename=backup_id,
                              user=user,
                              password=password) as runner:
            (success,
             note,
             checksum,
             location) = storage_strategy.save(backup_container, runner)

        self.assertEqual(success, True,
                         "The backup should have been successful.")
        self.assertIsNotNone(note, "A note should have been returned.")
        self.assertEqual(location, 'http://mockswift/v1/database_backups/123',
                         "Incorrect swift location was returned.")
예제 #7
0
    def test_swift_segment_checksum_etag_mismatch(self):
        """This tests that when etag doesn't match segment uploaded checksum
        False is returned and None for checksum and location"""
        context = TroveContext()
        # this backup_id will trigger fake swift client with calculate_etag
        # enabled to spit out a bad etag when a segment object is uploaded
        backup_id = 'bad_segment_etag_123'
        user = '******'
        password = '******'
        backup_container = 'database_backups'

        swift_client = FakeSwiftConnectionWithRealEtag()
        when(swift).create_swift_client(context).thenReturn(swift_client)
        storage_strategy = SwiftStorage(context)

        with MockBackupRunner(filename=backup_id,
                              user=user,
                              password=password) as runner:
            (success,
             note,
             checksum,
             location) = storage_strategy.save(backup_container, runner)

        self.assertEqual(success, False,
                         "The backup should have failed!")
        self.assertTrue(note.startswith("Error saving data to Swift!"))
        self.assertIsNone(checksum,
                          "Swift checksum should be None for failed backup.")
        self.assertIsNone(location,
                          "Swift location should be None for failed backup.")
예제 #8
0
    def test_run_hook_preserves_current_directory(self):

        when(self.hooks.whobj).invoke_webhook(any(), any(), any(), any(), any(), any()).thenReturn()
        when(self.hooks.utils).get_identifier(any(), any(), any()).thenReturn(any())
        cwd = os.getcwd()
        self.hooks.run_hook("pre-build", self.appdata, "/tmp", any(), any())
        assert cwd == os.getcwd()
예제 #9
0
    def test_run_verify_checksum_mismatch(self):
        """This tests that SwiftDownloadIntegrityError is raised and swift
        download cmd does not run when original backup checksum does not match
        swift object etag"""

        context = TroveContext()
        location = "/backup/location/123"
        is_zipped = False
        backup_checksum = "checksum_different_then_fake_swift_etag"

        swift_client = FakeSwiftConnection()
        when(swift).create_swift_client(context).thenReturn(swift_client)

        storage_strategy = SwiftStorage(context)
        download_stream = storage_strategy.load(context,
                                                location,
                                                is_zipped,
                                                backup_checksum)

        self.assertEqual(download_stream.container, "location")
        self.assertEqual(download_stream.filename, "123")

        self.assertRaises(SwiftDownloadIntegrityError,
                          download_stream.__enter__)

        self.assertEqual(download_stream.process, None,
                         "SwiftDownloadStream process/cmd was not supposed"
                         "to run.")
예제 #10
0
파일: swift.py 프로젝트: NeCTAR-RC/trove
    def without_object(self, container, name):
        """
        sets expectations for deleting an object

        example:

        if FAKE:
        swift_stub.without_object('test-container-name', 'test-object-name')

        # allows container to be removed ONCE
        component_using_swift.remove_container('test-container-name')
        # throws ClientException - 404
        component_using_swift.get_container('test-container-name')
        component_using_swift.remove_container('test-container-name')

        :param container: container name that is the object belongs
        :param name: the name of the object expected to be removed
        """
        self._ensure_container_exists(container)
        self._ensure_object_exists(container, name)
        # throw exception if someone calls get object
        when(swift_client.Connection).get_object(container, name).thenRaise(
            swiftclient.ClientException('Resource Not found', http_status=404))
        when(swift_client.Connection).delete_object(
            container, name).thenReturn(None).thenRaise(
                swiftclient.ClientException('Resource Not Found',
                                            http_status=404))
        self._remove_object(name, self._objects[container])
        return self
예제 #11
0
    def setUp(self):

        B3TestCase.setUp(self)
        self.console.gameName = 'f00'

        self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
        when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
        self.adminPlugin.onLoadConfig()
        self.adminPlugin.onStartup()

        self.conf = CfgConfigParser()
        self.conf.loadFromString(dedent(r"""
            [settings]
            update_config_file: no

            [commands]
            cmdlevel: fulladmin
            cmdalias: fulladmin
            cmdgrant: superadmin
            cmdrevoke: superadmin
            cmduse: superadmin
        """))

        self.p = CmdmanagerPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()
예제 #12
0
파일: swift.py 프로젝트: NeCTAR-RC/trove
    def with_container(self, container_name):
        """
        sets expectations for creating a container and subsequently getting its
        information

        example:

        if FAKE:
            swift_stub.with_container('test-container-name')

        # returns swift container information - mostly faked
        component_using.swift.create_container('test-container-name')
        component_using_swift.get_container_info('test-container-name')

        :param container_name: container name that is expected to be created
        """

        def container_resp(container):
            return ({'content-length': '2', 'x-container-object-count': '0',
                     'accept-ranges': 'bytes', 'x-container-bytes-used': '0',
                     'x-timestamp': '1363370869.72356',
                     'x-trans-id': 'tx7731801ac6ec4e5f8f7da61cde46bed7',
                     'date': 'Fri, 10 Mar 2013 18:07:58 GMT',
                     'content-type': 'application/json; charset=utf-8'},
                    self._objects[container])

        # if this is called multiple times then nothing happens
        when(swift_client.Connection).put_container(container_name).thenReturn(
            None)
        self._create_container(container_name)
        # return container headers
        when(swift_client.Connection).get_container(container_name).thenReturn(
            container_resp(container_name))

        return self
예제 #13
0
파일: swift.py 프로젝트: NeCTAR-RC/trove
    def without_container(self, container):
        """
        sets expectations for removing a container and subsequently throwing an
        exception for further interactions

        example:

        if FAKE:
            swift_stub.without_container('test-container-name')

        # returns swift container information - mostly faked
        component_using.swift.remove_container('test-container-name')
        # throws exception "Resource Not Found - 404"
        component_using_swift.get_container_info('test-container-name')

        :param container: container name that is expected to be removed
        """
        # first ensure container
        self._ensure_container_exists(container)
        # allow one call to get container and then throw exceptions (may need
        # to be revised
        when(swift_client.Connection).delete_container(container).thenRaise(
            swiftclient.ClientException("Resource Not Found", http_status=404))
        when(swift_client.Connection).get_container(container).thenRaise(
            swiftclient.ClientException("Resource Not Found", http_status=404))
        self._delete_container(container)
        return self
 def test_window_id_is_empty_container(self):
     driver = MockWebDriver()
     when(driver).execute_script(SCRIPT).thenReturn([[], "", "", ""]).thenReturn([{}, "", "", ""])
     info = driver.get_current_window_info()
     self.assertEqual(info[1], [])
     info = driver.get_current_window_info()
     self.assertEqual(info[1], {})
예제 #15
0
    def testVerifiesMultipleCallsOnClassmethod(self):
        when(Dog).bark().thenReturn("miau!")

        Dog.bark()
        Dog.bark()

        verify(Dog, times=2).bark()
예제 #16
0
 def test_debit_sur_solde_insuffisant(self): 
     """Test le debit quand le solde est insuffisant""" 
     storage = mock()
     when(storage).select().thenReturn([])
     account = Account(storage)
     amount = 11
     self.assertRaises(ValueError, account.debit, amount)
 def test_window_id_is_bool(self):
     driver = MockWebDriver()
     when(driver).execute_script(SCRIPT).thenReturn([True, "", "", ""]).thenReturn([False, "", "", ""])
     info = driver.get_current_window_info()
     self.assertEqual(info[1], True)
     info = driver.get_current_window_info()
     self.assertEqual(info[1], False)
예제 #18
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)
예제 #19
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)    
예제 #20
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)
예제 #21
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)
예제 #22
0
	def testBuildWithNestedBundles(self):
		import __builtin__, pickle
		from mockito import when, unstub

		b = os.path.join('/', 'b.js')
		when(__builtin__).open(b).thenReturn(StrIO('b'))
		
		@worker
		def content(files, bundle):
			for a in files:
				assert a == 'a.js'
				yield 'a'

		@worker
		def store(contents, bundle):
			for content in contents:
				assert content == 'ab'
				yield 'ab.js'

		env = ets.Environment(mode='development', map_from='/')

		nested_bundle = ets.Bundle(assets=['a.js'], env=env,
						development=[content])

		#keep in mind that build() expects a relative path at the end of the pipe
		bundle = ets.Bundle(assets=[nested_bundle, 'b.js'], env=env,
						development=[ets.f.read, ets.f.merge, store])

		assert bundle.build() == [os.path.join('/', 'ab.js')]

		unstub()
예제 #23
0
 def test_lookup_flavor(self):
     flavor = mock(Flavor)
     flavor.name = 'flav_1'
     when(self.flavor_mgr).get('1').thenReturn(flavor)
     transformer = NovaNotificationTransformer(context=self.context)
     self.assertThat(transformer._lookup_flavor('1'), Equals(flavor.name))
     self.assertThat(transformer._lookup_flavor('2'), Equals('unknown'))
예제 #24
0
    def testFailsOnNumberOfCalls(self):
        when(os.path).exists("test").thenReturn(True)

        os.path.exists("test")

        self.assertRaises(VerificationError, verify(os.path, times=2).exists,
                          "test")
예제 #25
0
    def setUp(self):
        B3TestCase.setUp(self)
        when(self.console.config).get_external_plugins_dir().thenReturn(external_plugins_dir)
        self.conf = CfgConfigParser(testplugin_config_file)

        self.plugin_list = [
            {'name': 'admin', 'conf': '@b3/conf/plugin_admin.ini', 'path': None, 'disabled': False},
        ]

        fp, pathname, description = imp.find_module('testplugin1', [os.path.join(b3.getB3Path(True), '..', 'tests', 'plugins', 'fakeplugins')])
        pluginModule1 = imp.load_module('testplugin1', fp, pathname, description)
        if fp:
            fp.close()

        fp, pathname, description = imp.find_module('testplugin3', [os.path.join(b3.getB3Path(True), '..', 'tests', 'plugins', 'fakeplugins')])
        pluginModule3 = imp.load_module('testplugin3', fp, pathname, description)
        if fp:
            fp.close()

        fp, pathname, description = imp.find_module('admin', [os.path.join(b3.getB3Path(True), 'plugins')])
        adminModule = imp.load_module('admin', fp, pathname, description)
        if fp:
            fp.close()

        when(self.console.config).get_plugins().thenReturn(self.plugin_list)
        when(self.console).pluginImport('admin', ANY).thenReturn(adminModule)
        when(self.console).pluginImport('testplugin1', ANY).thenReturn(pluginModule1)
        when(self.console).pluginImport('testplugin3', ANY).thenReturn(pluginModule3)
예제 #26
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")
    def test_repair_is_deferred(self):
        soledad = mock()
        when(soledad).get_all_docs().thenReturn(defer.succeed((1, [])))

        d = SoledadMaintenance(soledad).repair()

        self.assertIsInstance(d, defer.Deferred)
    def _mock_get_soledad_doc(self, doc_id, doc):
        soledad_doc = SoledadDocument(doc_id, json=json.dumps(doc.serialize()))

        # when(self.soledad).get_doc(doc_id).thenReturn(defer.succeed(soledad_doc))
        when(self.soledad).get_doc(doc_id).thenAnswer(lambda: defer.succeed(soledad_doc))

        self.doc_by_id[doc_id] = soledad_doc
예제 #29
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")
예제 #30
0
    def test_level_generator_is_created(self):
        """
        Test that portal adder has level generator set to it
        """
        portal_config = [PortalAdderConfiguration(icons = (1, 2),
                                                  level_type = 'catacombs',
                                                  location_type = 'room',
                                                  chance = 100,
                                                  new_level = 'upper crypt',
                                                  unique = False)]

        level_generator_factory = mock(LevelGeneratorFactory)
        level_generator = mock(LevelGenerator)

        when(level_generator_factory).get_generator(any()).thenReturn(level_generator)

        factory = PortalAdderFactory(portal_config,
                                     self.rng)
        factory.level_generator_factory = level_generator_factory

        portal_adders = factory.create_portal_adders('catacombs')

        portal_adder = portal_adders[0]

        assert_that(portal_adder.level_generator,
                    is_(same_instance(level_generator)))
예제 #31
0
 def test_exception_InvalidPlayerName(self):
     when(self.parser).write(
         ('player.isAlive',
          'Foobar')).thenRaise(CommandFailedError(['InvalidPlayerName']))
     self.assertEqual(b3.STATE_UNKNOWN, self.foobar.state)
예제 #32
0
    def test_roger_build(self):
        try:
            settings = mock(Settings)
            appConfig = mock(AppConfig)
            dockerUtilsObj = mock(DockerUtils)
            dockerObj = mock(Docker)
            roger_build = RogerBuild()
            roger_build.utils = mock(Utils)
            mockedHooks = mock(Hooks)
            roger_env = self.roger_env
            config = self.config
            data = self.data
            repo_name = 'test'
            repo_url = 'test.com'
            raised_exception = False
            sc = mock(StatsClient)

            when(sc).timing(any(), any()).thenReturn(any())
            when(roger_build.utils).getStatsClient().thenReturn(sc)
            when(roger_build.utils).get_identifier(any(), any(), any()).thenReturn(any())
            when(roger_build.utils).extract_app_name(any()).thenReturn(any())
            when(settings, strict=False).getConfigDir().thenReturn(any())
            when(settings, strict=False).getCliDir().thenReturn(any())
            when(settings).getUser().thenReturn(any())
            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, strict=False).run_hook(any(), any(), any(), any()).thenReturn(0)

            args = self.args
            # Setting app_name as empty
            args.app_name = ''
            args.env = 'test'
            args.config_file = 'app.json'
            args.directory = self.base_dir

            # with self.assertRaises(ValueError):
            roger_build.main(settings, appConfig, mockedHooks,
                             dockerUtilsObj, dockerObj, args)
        except:
            raised_exception = True
        self.assertFalse(raised_exception)
예제 #33
0
    def test_roger_build_calls_postbuild_hook_when_present(self):
        settings = mock(Settings)
        appConfig = mock(AppConfig)
        dockerUtilsObj = mock(DockerUtils)
        dockerObj = mock(Docker)
        roger_build = RogerBuild()
        roger_build.utils = mock(Utils)
        mockedHooks = mock(Hooks)
        roger_env = {}
        roger_env["registry"] = "any registry"
        appdata = {}
        appdata["hooks"] = dict([("post_build", "some command")])
        config = self.config
        args = self.args
        args.app_name = 'any app'
        args.env = 'test'
        args.directory = '/tmp'
        args.config_file = 'any.json'
        data = self.data
        repo_name = 'test'
        repo_url = 'test.com'
        sc = mock(StatsClient)

        when(sc).timing(any(), any()).thenReturn(any())
        when(roger_build.utils).getStatsClient().thenReturn(sc)
        when(roger_build.utils).get_identifier(any(), any(), any()).thenReturn(any())
        when(roger_build.utils).extract_app_name(any()).thenReturn("any app")
        when(settings, strict=False).getConfigDir().thenReturn(any())
        when(settings, strict=False).getCliDir().thenReturn(any())
        when(settings).getUser().thenReturn(any())
        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(mockedHooks).run_hook(any(), any(), any(), any()).thenReturn(0)
        when(mockedHooks).run_hook(any(), any(), any(), any()).thenReturn(0)

        return_code = roger_build.main(
            settings, appConfig, mockedHooks, dockerUtilsObj, dockerObj, args)
        verify(mockedHooks).run_hook("post_build", any(), any(), any())
예제 #34
0
 def test_delete_backup_is_running(self):
     backup = mock()
     backup.is_running = True
     when(models.Backup).get_by_id(any()).thenReturn(backup)
     self.assertRaises(exception.UnprocessableEntity,
                       models.Backup.delete, self.context, 'backup_id')
예제 #35
0
    def test_sender(self, tx):
        DUMMY_SENDER = 'sender'
        (when('plasma_cash.child_chain.transaction').get_sender(
            tx.hash, tx.sig).thenReturn(DUMMY_SENDER))

        assert tx.sender == DUMMY_SENDER
예제 #36
0
 def createMapperMock(self):
     map_mock = mock()
     when(map_mock).find(any()).thenReturn(mock())
     when(map_mock).find(None).thenReturn(None)
     return map_mock
예제 #37
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest

from confluent_kafka import Consumer
from confluent_kafka import Message, KafkaError
from mockito import when, mock, verify
from clx.io.reader.kafka_reader import KafkaReader

batch_size = 100
message = mock(Message)
kafka_error = mock(KafkaError)
when(kafka_error).code().thenReturn("test")
when(message).value().thenReturn("test message".encode("utf-8"))


@pytest.mark.parametrize("batch_size", [batch_size])
def test_read_data(batch_size):
    consumer = mock(Consumer)
    reader = KafkaReader(batch_size, consumer)
    # Return msg = None 1 time, then return a valid message moving forward
    when(
        reader.consumer).poll(timeout=1.0).thenReturn(None).thenReturn(message)
    # Always return no message error
    when(message).error().thenReturn(None)
    df = reader.fetch_data()
    assert df.shape == (100, 1)
    assert df.columns == ["Raw"]
예제 #38
0
 def test_alive(self):
     # GIVEN
     when(self.parser).write(
         ('player.isAlive', 'Foobar')).thenReturn(['true'])
     # THEN
     self.assertEqual(b3.STATE_ALIVE, self.foobar.state)
예제 #39
0
def no_email():
    mockito.when(config).load_var_no_error("email").thenReturn(None)
예제 #40
0
 def test_dead(self):
     # GIVEN
     when(self.parser).write(
         ('player.isAlive', 'Foobar')).thenReturn(['false'])
     # THEN
     self.assertEqual(b3.STATE_DEAD, self.foobar.state)
예제 #41
0
async def test_onboard_issuer_public_did_exists(
    mock_agent_controller: AcaPyClient,
):
    when(acapy_wallet).get_public_did(controller=mock_agent_controller).thenReturn(
        get(
            Did(
                did="WgWxqztrNooG92RXvxSTWv",
                verkey="WgWxqztrNooG92RXvxSTWvWgWxqztrNooG92RXvxSTWv",
            )
        )
    )

    endorser_controller = get_mock_agent_controller()

    when(endorser_controller.out_of_band).create_invitation(...).thenReturn(
        get(InvitationRecord(invitation=InvitationMessage()))
    )
    when(mock_agent_controller.out_of_band).receive_invitation(...).thenReturn(
        get(ConnRecord())
    )

    when(acapy_wallet).get_public_did(controller=endorser_controller).thenReturn(
        get(Did(did="EndorserController", verkey="EndorserVerkey"))
    )

    when(mock_agent_controller.endorse_transaction).set_endorser_role(...).thenReturn(
        get()
    )
    when(mock_agent_controller.endorse_transaction).set_endorser_info(...).thenReturn(
        get()
    )

    # Mock event listener
    when(onboarding).start_listener(...).thenReturn(get(mock_start_listener))
    onboard_result = await onboarding.onboard_issuer(
        name="issuer_name",
        endorser_controller=endorser_controller,
        issuer_controller=mock_agent_controller,
        issuer_wallet_id="issuer_wallet_id",
    )

    assert_that(onboard_result).has_did("did:sov:WgWxqztrNooG92RXvxSTWv")
    verify(acapy_wallet, times=0).create_did(...)
    verify(endorser_controller.out_of_band).create_invitation(
        auto_accept=True,
        body=InvitationCreateRequest(
            handshake_protocols=["https://didcomm.org/didexchange/1.0"],
            use_public_did=True,
        ),
    )
    verify(mock_agent_controller.out_of_band).receive_invitation(
        auto_accept=True,
        use_existing_connection=True,
        body=InvitationMessage(),
        alias="endorser",
    )
예제 #42
0
 def test_unknown(self):
     # GIVEN
     when(self.parser).write(('player.isAlive', 'Foobar')).thenReturn()
     # THEN
     self.assertEqual(b3.STATE_UNKNOWN, self.foobar.state)
예제 #43
0
    def test_roger_gitpull_calls_postgitpull_hook_when_present(self):
        settings = mock(Settings)
        appConfig = mock(AppConfig)
        roger_gitpull = RogerGitPull()
        roger_gitpull.utils = mock(Utils)
        mockedHooks = mock(Hooks)
        gitObj = mock(GitUtils)
        roger_env = {}
        repo_name = 'roger'
        repo_url = 'test_url'
        roger_env["registry"] = "any registry"
        when(settings).getConfigDir().thenReturn(self.configs_dir)
        when(appConfig).getRogerEnv(any()).thenReturn(roger_env)
        appdata = {}
        appdata["hooks"] = dict([("post_gitpull", "some command")])
        when(appConfig).getAppData(any(), any(), any()).thenReturn(appdata)
        config = self.config

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

        when(settings).getUser().thenReturn('test_user')
        when(appConfig).getConfig(any(), any()).thenReturn(config)
        when(appConfig).getRepoUrl(any()).thenReturn(repo_name)
        when(appConfig).getRepoName(any()).thenReturn(repo_name)
        args = self.args
        args.config_file = 'any.json'
        args.app_name = 'any app'
        args.branch = "some_branch"
        args.directory = '/tmp'
        args.environment = 'test'
        when(gitObj).gitPull(any()).thenReturn(0)
        when(gitObj).gitShallowClone(any(), any()).thenReturn(0)
        when(mockedHooks).run_hook(any(), any(), any(), any()).thenReturn(0)
        return_code = roger_gitpull.main(settings, appConfig, gitObj,
                                         mockedHooks, args)
        verify(mockedHooks).run_hook("post_gitpull", any(), any(), any())
예제 #44
0
async def test_onboard_issuer_no_public_did(
    mock_agent_controller: AcaPyClient,
):
    endorser_controller = get_mock_agent_controller()

    when(acapy_wallet).get_public_did(controller=mock_agent_controller).thenRaise(
        CloudApiException(detail="Error")
    )
    when(acapy_wallet).create_did(mock_agent_controller).thenReturn(
        get(
            Did(
                did="WgWxqztrNooG92RXvxSTWv",
                verkey="WgWxqztrNooG92RXvxSTWvWgWxqztrNooG92RXvxSTWv",
            )
        )
    )

    when(acapy_ledger).register_nym_on_ledger(...).thenReturn(get())

    when(acapy_ledger).accept_taa_if_required(...).thenReturn(get())
    when(acapy_wallet).set_public_did(...).thenReturn(get())

    when(acapy_wallet).get_public_did(controller=endorser_controller).thenReturn(
        get(Did(did="EndorserController", verkey="EndorserVerkey"))
    )

    when(endorser_controller.out_of_band).create_invitation(...).thenReturn(
        get(InvitationRecord(invitation=InvitationMessage()))
    )
    when(mock_agent_controller.out_of_band).receive_invitation(...).thenReturn(
        get(ConnRecord())
    )

    when(mock_agent_controller.endorse_transaction).set_endorser_role(...).thenReturn(
        get()
    )
    when(mock_agent_controller.endorse_transaction).set_endorser_info(...).thenReturn(
        get()
    )

    # Mock event listener
    when(onboarding).start_listener(...).thenReturn(get(mock_start_listener))
    onboard_result = await onboarding.onboard_issuer(
        name="issuer_name",
        endorser_controller=endorser_controller,
        issuer_controller=mock_agent_controller,
        issuer_wallet_id="issuer_wallet_id",
    )

    assert_that(onboard_result).has_did("did:sov:WgWxqztrNooG92RXvxSTWv")
    verify(acapy_wallet).create_did(mock_agent_controller)
    verify(acapy_ledger).register_nym_on_ledger(
        endorser_controller,
        did="WgWxqztrNooG92RXvxSTWv",
        verkey="WgWxqztrNooG92RXvxSTWvWgWxqztrNooG92RXvxSTWv",
        alias="issuer_name",
    )
    verify(acapy_ledger).accept_taa_if_required(mock_agent_controller)
    verify(acapy_wallet).set_public_did(mock_agent_controller, "WgWxqztrNooG92RXvxSTWv")
예제 #45
0
    def _clear(self):
        self.elements = {}
        self.current_uuid_i = 0

    def _keys(self):
        return list(self.elements.keys())

    def _next_uuid(self):
        r_uuid = self.uuids[self.current_uuid_i]
        self.current_uuid_i += 1
        return r_uuid


redis_mock = MockRedis()
when(redis).StrictRedis(...).thenReturn(redis_mock)
patch(uuid_pack.uuid1, redis_mock._next_uuid)
from explorer.manager import (Explorer, cache, ItemNotFoundException)


@pytest.fixture
def explorer():
    redis_mock._clear()
    return Explorer('000')


def test__init(explorer):
    Explorer('000')
    Explorer('000')
    assert redis_mock._keys() == ['000#/', '000#d_list-/']
    assert json.loads(redis_mock.elements['000#/']) == {
예제 #46
0
    def test_rogerGitPull(self):
        set_config_dir = ''
        if "ROGER_CONFIG_DIR" in os.environ:
            set_config_dir = os.environ.get('ROGER_CONFIG_DIR')
        os.environ["ROGER_CONFIG_DIR"] = self.configs_dir
        config_file = "app.json"
        work_dir = self.work_dir
        settings = mock(Settings)
        appConfig = mock(AppConfig)
        roger_gitpull = RogerGitPull()
        roger_gitpull.utils = mock(Utils)
        marathon = mock(Marathon)
        mockedHooks = mock(Hooks)
        gitObj = mock(GitUtils)
        data = self.data
        config = self.config
        roger_env = self.roger_env
        repo_name = 'roger'
        sc = mock(StatsClient)

        when(sc).timing(any(), any()).thenReturn(any())
        when(roger_gitpull.utils).getStatsClient().thenReturn(sc)
        when(roger_gitpull.utils).get_identifier(any(), any(),
                                                 any()).thenReturn(any())
        when(roger_gitpull.utils).extract_app_name(any()).thenReturn("test")

        when(marathon).put(self.components_dir + '/test-roger-grafana.json',
                           roger_env['environments']['dev'],
                           'grafana_test_app').thenReturn("Response [200]")
        frameworkUtils = mock(FrameworkUtils)
        when(frameworkUtils).getFramework(data).thenReturn(marathon)
        when(settings).getComponentsDir().thenReturn(self.base_dir +
                                                     "/tests/components")
        when(settings).getSecretsDir().thenReturn(self.base_dir +
                                                  "/tests/secrets")
        when(settings).getTemplatesDir().thenReturn(self.base_dir +
                                                    "/tests/templates")
        when(settings).getConfigDir().thenReturn(self.configs_dir)
        when(settings).getCliDir().thenReturn(self.base_dir)
        when(settings).getUser().thenReturn('test_user')
        when(appConfig).getRogerEnv(self.configs_dir).thenReturn(roger_env)
        when(appConfig).getConfig(self.configs_dir,
                                  "app.json").thenReturn(config)
        when(appConfig).getAppData(self.configs_dir, "app.json",
                                   "grafana_test_app").thenReturn(data)
        when(appConfig).getRepoName(any()).thenReturn(repo_name)

        args = self.args
        args.app_name = "grafana_test_app"
        args.config_file = config_file
        args.branch = "master"
        args.environment = 'test'
        args.directory = self.work_dir
        when(mockedHooks).run_hook(any(), any(), any(), any()).thenReturn(0)
        when(gitObj).gitPull(any()).thenReturn(0)
        when(gitObj).gitShallowClone(any(), any()).thenReturn(0)
        return_code = roger_gitpull.main(settings, appConfig, gitObj,
                                         mockedHooks, args)
        with open(self.configs_dir + '/{}'.format(config_file)) as config:
            config = json.load(config)
        exists = os.path.exists(work_dir)
        assert exists is True
        shutil.rmtree(work_dir)
        if set_config_dir.strip() != '':
            os.environ["ROGER_CONFIG_DIR"] = "{}".format(set_config_dir)
예제 #47
0
    def testStubsAnInstanceMethodWithAnArgument(self):
        when(Dog).bark('Miau').thenReturn('Wuff')

        rex = Dog()
        self.assertEquals('Wuff', rex.bark('Miau'))
예제 #48
0
    def setUp(self):

        TranslatorTestCase.setUp(self)
        self.conf = CfgConfigParser()
        self.conf.loadFromString(dedent(r"""
            [settings]
            default_source_language: it
            default_target_language: en
            display_translator_name: no
            translator_name: ^7[^1T^7]
            min_sentence_length: 6
            microsoft_client_id: fakeclientid
            microsoft_client_secret: fakeclientsecret

            [commands]
            translate: reg
            translast: reg
            transauto: reg
            translang: reg
        """))

        self.p = TranslatorPlugin(self.console, self.conf)
        self.p.onLoadConfig()
        self.p.onStartup()

        with logging_disabled():
            from b3.fake import FakeClient

        # create 2 fake clients
        self.mike = FakeClient(console=self.console, name="Mike", guid="mikeguid", groupBits=2)
        self.bill = FakeClient(console=self.console, name="Bill", guid="billguid", groupBits=2)

        # connect the clients
        self.mike.connects("1")
        self.bill.connects("2")

        # define some translations for !translate command
        when(self.p).translate('it', 'en', 'Messaggio di prova').thenReturn('Test message')
        when(self.p).translate('en', 'fr', 'Test message').thenReturn('Message de test')
        when(self.p).translate('de', 'es', 'Test Meldungs').thenReturn('Mensaje de prueba')
        when(self.p).translate('nl', 'de', 'Test Bericht').thenReturn('Test Meldungs')
        when(self.p).translate('fr', 'en', 'Message de test').thenReturn('Test message')
        when(self.p).translate('it', 'es', 'Messaggio di prova').thenReturn('Mensaje de prueba')

        # define some translations for !transauto and !translast command
        when(self.p).translate('', 'en', 'Messaggio di prova').thenReturn('Test message')
        when(self.p).translate('', 'fr', 'Messaggio di prova').thenReturn('Message de test')
예제 #49
0
 def testUnstubMockedInstanceMethod(self):
     rex = Dog()
     when(rex).waggle().thenReturn('Nope!')
     assert rex.waggle() == 'Nope!'
     unstub()
     assert rex.waggle() == 'Wuff!'
예제 #50
0
    def testInvokeAStubbedMethodFromAnotherMethod(self):
        when(Dog).bark('Wau').thenReturn('Wuff')

        rex = Dog()
        self.assertEquals('Wuff', rex.do_default_bark())
        verify(Dog).bark('Wau')
예제 #51
0
 def testFailSecondAnswerUnused(self):
     when(Dog).bark('Miau').thenReturn('Yep').thenReturn('Nop')
     rex = Dog()
     rex.bark('Miau')
     with pytest.raises(VerificationError):
         verifyStubbedInvocationsAreUsed(Dog)
예제 #52
0
    def testStubAnInstanceMethod(self):
        when(Dog).waggle().thenReturn('Boing!')

        rex = Dog()
        self.assertEquals('Boing!', rex.waggle())
예제 #53
0
 def testPassUsedOnceImplicitAnswer(self):
     when(Dog).bark('Miau')
     rex = Dog()
     rex.bark('Miau')
     verifyStubbedInvocationsAreUsed(Dog)
예제 #54
0
 def testEnsureWhenGetsNotConfused(self):
     m = mock()
     when(m).foo(1).thenReturn()
     m.foo(1)
     with pytest.raises(VerificationError):
         verifyNoMoreInteractions(m)
예제 #55
0
        def testPassIfExplicitlyVerified(self, verification):
            dog = mock()
            when(dog).waggle().thenReturn('Sure')
            verify(dog, **verification).waggle()

            verifyStubbedInvocationsAreUsed(dog)
예제 #56
0
    def testPassUsedOnce(self):
        dog = mock()
        when(dog).waggle().thenReturn('Sure')

        dog.waggle()
        verifyStubbedInvocationsAreUsed(dog)
예제 #57
0
 def testNothingVerifiedVerifyZeroInteractionsRaises(self):
     when(Dog).bark('Miau')
     rex = Dog()
     rex.bark('Miau')
     with pytest.raises(VerificationError):
         verifyZeroInteractions(Dog)
예제 #58
0
        def testWildacardCallSignatureOnStub(self):
            dog = mock()
            when(dog).waggle(Ellipsis).thenReturn('Sure')
            verify(dog, times=0).waggle(1)

            verifyStubbedInvocationsAreUsed(dog)
예제 #59
0
 def testIfVerifiedVerifyNoMoreInteractionsPasses(self):
     when(Dog).bark('Miau')
     rex = Dog()
     rex.bark('Miau')
     verify(Dog).bark('Miau')
     verifyNoMoreInteractions(Dog)
예제 #60
0
 def testBarkOnUnusedStub(self):
     when(Dog).bark('Miau')
     with pytest.raises(VerificationError):
         verifyStubbedInvocationsAreUsed(Dog)