def test_walk_passes_the_specified_argument_to_callback(listdir_mock):
    listdir_mock.return_value = ['f1.py']
    cb = MagicMock()

    fs.walk('/dummy/path', cb, 'arg')

    cb.assert_called_with(ANY, 'arg')
Exemple #2
0
    def test_patching_a_builtin(self):
        mock = MagicMock(return_value=sentinel.file_handle)
        with patch('__builtin__.open', mock):
            handle = open('filename', 'r')

        mock.assert_called_with('filename', 'r')
        assert handle == sentinel.file_handle, "incorrect file handle returned"
def test_scalyr_facets(monkeypatch, fx_facets):
    kwargs, res = fx_facets

    read_key = '123'

    post = MagicMock()
    post.return_value.json.return_value = res

    monkeypatch.setattr('requests.post', post)

    scalyr = ScalyrWrapper(read_key)
    result = scalyr.facets(**kwargs)

    assert result == res

    if 'minutes' not in kwargs:
        kwargs['minutes'] = 30
    query = get_query(
        'facet', None, read_key, **kwargs)

    query.pop('function', None)
    query.pop('buckets', None)
    query['maxCount'] = kwargs.get('max_count', 5)

    post.assert_called_with(
        scalyr._ScalyrWrapper__facet_url, json=query, headers={'Content-Type': 'application/json'})
 def test_wait_list(self):
     self.update_ci.deploy_jobs = MagicMock(
         side_effect=[['autopilot-ci'], []])
     sleep_mock = MagicMock()
     with patch('time.sleep', sleep_mock):
         self.update_ci.update_jenkins(self.jenkins, self.jjenv, self.stack)
     sleep_mock.assert_called_with(10)
class TestGraphiteTarget(TestCase):

    def setUp(self):
        self.base_url = 'BASE_URL'
        self.record_class = MagicMock(GraphiteDataRecord)
        self.http_get = MagicMock(requests.get)
        self.http_get().content = SAMPLE_RESPONSE
        self.target = 'TARGET'

        self.records = get_records(
            self.base_url,
            self.http_get,
            self.record_class,
            self.target,
        )

    def test_hits_correct_url(self):
        url = 'BASE_URL/render/?target=TARGET&rawData=true&from=-1min'
        self.http_get.assert_called_with(url, verify=False)

    def should_create_two_records(self):
        calls = [call(SAMPLE_1), call(SAMPLE_2)]
        self.assertEqual(self.record_class.call_args_list, calls)

    def should_return_data_records(self):
        self.assertEqual(self.records[0], self.record_class(SAMPLE_1))
        self.assertEqual(self.records[1], self.record_class(SAMPLE_2))

    def should_raise_for_status(self):
        self.http_get().raise_for_status.assert_called_with()
 def test_run(self):
     mock = MagicMock()
     code = "some SDK code"
     with patch('omnimax.sdk.base_sdk.execute', mock):
         sdk = omnimax.sdk.BaseSDK('ruby')
         sdk.run(code)
     mock.assert_called_with(self.sdk_dir + '/run.sh', code, cwd=self.sdk_dir)
def test_metrics(monkeypatch):
    client = client_mock(monkeypatch)

    resp = MagicMock()
    resp.text = 'metrics'

    client.return_value.session.get.return_value = resp

    parsed = MagicMock()
    parsed.samples = [
        ('metric-1', {}, 20.17), ('metric-2', {'verb': 'GET'}, 20.16), ('metric-1', {'verb': 'POST'}, 20.18)
    ]

    parser = MagicMock()
    parser.return_value = [parsed]

    monkeypatch.setattr('zmon_worker_monitor.builtins.plugins.kubernetes.text_string_to_metric_families', parser)

    k = KubernetesWrapper()
    metrics = k.metrics()

    expected = {
        'metric-1': [({}, 20.17), ({'verb': 'POST'}, 20.18)],
        'metric-2': [({'verb': 'GET'}, 20.16)],
    }

    assert metrics == expected

    parser.assert_called_with(resp.text)
    client.return_value.session.get.assert_called_with(CLUSTER_URL + '/metrics')
def test_appdynamics_log_count(monkeypatch, fx_log_count):
    es_url, kwargs, res = fx_log_count

    count = MagicMock()
    count.return_value = res

    monkeypatch.setattr('zmon_worker_monitor.builtins.plugins.appdynamics.ElasticsearchWrapper.count', count)

    timestamp = 1234
    timestamp_mock = MagicMock()
    timestamp_mock.return_value = timestamp
    monkeypatch.setattr(AppdynamicsWrapper, '_AppdynamicsWrapper__get_timestamp', timestamp_mock)

    cli = AppdynamicsWrapper(url=URL, es_url=es_url, username=USER, password=PASS, index_prefix='PREFIX_')

    exp_q = ('{} AND eventTimestamp:>{}'
             .format(kwargs.get('q', ''), timestamp)
             .lstrip(' AND '))

    result = cli.count_logs(**kwargs)

    assert result == res['count']

    kwargs['q'] = exp_q
    kwargs['indices'] = ['PREFIX_*']
    if 'body' not in kwargs:
        kwargs['body'] = None

    count.assert_called_with(**kwargs)
def test_appdynamics_log_query(monkeypatch, fx_log_hits):
    es_url, kwargs, res = fx_log_hits

    search = MagicMock()
    search.return_value = res

    monkeypatch.setattr('zmon_worker_monitor.builtins.plugins.appdynamics.ElasticsearchWrapper.search', search)

    timestamp = 1234
    timestamp_mock = MagicMock()
    timestamp_mock.return_value = timestamp
    monkeypatch.setattr(AppdynamicsWrapper, '_AppdynamicsWrapper__get_timestamp', timestamp_mock)

    cli = AppdynamicsWrapper(url=URL, es_url=es_url, username=USER, password=PASS, index_prefix='PREFIX_')

    exp_q = ('{} AND eventTimestamp:>{}'
             .format(kwargs.get('q', ''), timestamp)
             .lstrip(' AND '))

    result = cli.query_logs(**kwargs)

    expected = res['hits']['hits'] if not kwargs.get('raw_result', False) else res

    assert result == expected

    kwargs.pop('raw_result', None)
    kwargs['q'] = exp_q
    kwargs['size'] = 100
    kwargs['indices'] = ['PREFIX_*']
    if 'body' not in kwargs:
        kwargs['body'] = None

    search.assert_called_with(**kwargs)
Exemple #10
0
    def test_install_pre_argument_in_resulting_command(self):
        # Lower than 1.4 versions don't end-up with `--pre` in the resulting
        # output
        mock = MagicMock(side_effect=[
            {'retcode': 0, 'stdout': 'pip 1.2.0 /path/to/site-packages/pip'},
            {'retcode': 0, 'stdout': ''}
        ])
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(
                'pep8', pre_releases=True
            )
            mock.assert_called_with(
                'pip install pep8',
                runas=None,
                cwd=None
            )

        mock = MagicMock(side_effect=[
            {'retcode': 0, 'stdout': 'pip 1.4.0 /path/to/site-pacakges/pip'},
            {'retcode': 0, 'stdout': ''}
        ])
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(
                'pep8', pre_releases=True
            )
            mock.assert_called_with(
                'pip install --pre pep8',
                runas=None,
                cwd=None
            )
    def test_load(self):
        """tests load method"""

        mock_run_statement = MagicMock()
        MySqlDatabase.run_statement = mock_run_statement

        config = MagicMock()
        config.schema = self.schema
        config.data = self.data
        fixture = MySqlFixture(
            config=config
        )

        fixture.load()

        # Brittle way of testing that insert statement is run
        # Assumes the keys of first row in self.data are the fields to insert
        data_row = self.data[0]
        stmnt_fields, expected_statement = MySqlInsertStatementMixin.create_insert_statement(
            table=self.schema.config.get_table(),
            fields=data_row.keys(),
            statement_string=True
        )

        expected_params = [data_row[field] for field in stmnt_fields]

        mock_run_statement.assert_called_with(
            expected_statement,
            params=expected_params,
            commit=True
        )
Exemple #12
0
    def test_list(self):
        # Patch S3Connection and its get_bucket method:
        with patch('gifshare.s3.S3Connection',
                   name='S3Connection') as MockS3Connection:
            mock_get_bucket = MagicMock(name='get_bucket')
            mock_bucket = MagicMock(name='bucket')
            mock_get_bucket.return_value = mock_bucket
            mock_bucket.list.return_value = [
                DummyKey('image1.jpeg'),
                DummyKey('image2.jpeg')
            ]
            MockS3Connection.return_value.get_bucket = mock_get_bucket

            self.bucket = gifshare.s3.Bucket(config_stub)
            keys = list(self.bucket.list())

            self.assertEqual(keys, [
                'http://dummy.web.root/image1.jpeg',
                'http://dummy.web.root/image2.jpeg',
            ])

            MockS3Connection.assert_called_with(
                'dummy-access-id', 'dummy-secret-access-key')
            mock_get_bucket.assert_called_with('not.a.bucket')
            mock_bucket.list.assert_called_once_with()
Exemple #13
0
def test_refresh_invalid_response(monkeypatch, tmpdir):
    tokens.configure(dir=str(tmpdir), url='https://example.org')
    tokens.manage('mytok', ['myscope'])
    tokens.start()  # this does not do anything..

    response = MagicMock()
    response.json.return_value = {'foo': 'bar'}
    post = MagicMock()
    post.return_value = response
    monkeypatch.setattr('requests.post', post)
    monkeypatch.setattr('tokens.read_credentials', lambda path: (VALID_USER_JSON, VALID_CLIENT_JSON))

    with pytest.raises(tokens.InvalidTokenResponse) as exc_info:
        tokens.get('mytok')
    assert str(exc_info.value) == """Invalid token response: Expected a JSON object with keys "expires_in" and "access_token": 'expires_in'"""

    # verify that we use a proper HTTP timeout..
    post.assert_called_with('https://example.org',
                            data={'username': '******', 'scope': 'myscope', 'password': '******', 'grant_type': 'password'},
                            headers={'User-Agent': 'python-tokens/{}'.format(tokens.__version__)},
                            timeout=(1.25, 2.25), auth=('cid', 'sec'))

    response.json.return_value = {'access_token': '', 'expires_in': 100}
    with pytest.raises(tokens.InvalidTokenResponse) as exc_info:
        tokens.get('mytok')
    assert str(exc_info.value) == 'Invalid token response: Empty "access_token" value'
Exemple #14
0
class TestDisableInterface(unittest.TestCase):
    def setUp(self):
        self.connection = MagicMock(name='connection')
        self.html = MagicMock(name='html')
        self.connection.return_value = self.html
        self.html.text = open('radio_5_asp.html').read()
        return

    def test_24_ghz(self):
        """
        Does it setup the right data dictionary and make the right call?
        """
        command = DisableInterface(connection=self.connection,
                                   band='2.4')
        expected_data = {'action':'Apply',
                        'wl_unit':'0',
                        'wl_radio':'0'}
        self.assertEqual(command.data, expected_data)
        command()
        self.connection.assert_called_with(data=expected_data)
        self.assertEqual(self.connection.path, 'radio.asp')
        return

    def test_5_ghz(self):
        """
        Does it set up the right data dictionary to disable the 5 Ghz interface?
        """
        command = DisableInterface(connection=self.connection,
                                   band='5')
        expected_data = {'action':'Apply',
                        'wl_unit':'1',
                        'wl_radio':'0'}
        self.assertEqual(command.data, expected_data)
    def test_open(self):
        """
        Does it open a file with the given filename?
        """
        name = 'aoeu'
        dict_writer = MagicMock()
        dict_writer_instance = MagicMock()
        storage = MagicMock()
        dict_writer.return_value = dict_writer_instance
        self.file_storage.open = MagicMock()
        opened = MagicMock()
        self.file_storage.open.return_value = opened
        
        with patch('csv.DictWriter', dict_writer):
            # the call to `open`
            writer = self.storage.open(name)

            # did it open a file using the filename?
            self.file_storage.open.assert_called_with(name)

            # Did it create and store a DictWriter?
            self.assertEqual(writer.writer, dict_writer_instance)

            # Did it create the DictWriter using the opened file and headers?
            dict_writer.assert_called_with(opened,
                                           self.headers)

            # Did it write the header to the file?
            dict_writer_instance.writeheader.assert_called_with()

            # did it return a copy of itself?
            self.assertIsInstance(writer, CsvDictStorage)
            self.assertNotEqual(writer, self.storage)
        return        
    def test_execute_fails(self):
        engine = Mock()
        engine.log = Mock()
        engine.log.info = MagicMock()
        engine.log.failed = MagicMock()

        topics = [Mock()]
        get_topics_mock = Mock(return_value=topics)

        execute_mock1 = MagicMock(side_effect=Exception)
        execute_mock2 = MagicMock(side_effect=Exception)

        self.tracker1.execute = execute_mock1
        self.tracker1.get_topics = get_topics_mock

        self.tracker2.execute = execute_mock2
        self.tracker2.get_topics = get_topics_mock

        self.trackers_manager.execute(engine, None)

        self.assertTrue(engine.log.info.called)
        self.assertTrue(engine.log.failed.called)
        get_topics_mock.assert_called_with(None)
        execute_mock1.assert_called_with(topics, engine)
        execute_mock2.assert_called_with(topics, engine)
    def pyodbc_exception_test(self):
        """
        Test that exceptions raised by pyodbc are handled
        """
        # GIVEN: A mocked out SongImport class, a mocked out pyodbc module, a mocked out translate method,
        #       a mocked "manager" and a mocked out logError method.
        with patch('openlp.plugins.songs.lib.worshipcenterproimport.SongImport'), \
            patch('openlp.plugins.songs.lib.worshipcenterproimport.pyodbc.connect') as mocked_pyodbc_connect, \
            patch('openlp.plugins.songs.lib.worshipcenterproimport.translate') as mocked_translate:
            mocked_manager = MagicMock()
            mocked_log_error = MagicMock()
            mocked_translate.return_value = 'Translated Text'
            importer = WorshipCenterProImport(mocked_manager)
            importer.logError = mocked_log_error
            importer.import_source = 'import_source'
            pyodbc_errors = [pyodbc.DatabaseError, pyodbc.IntegrityError, pyodbc.InternalError, pyodbc.OperationalError]
            mocked_pyodbc_connect.side_effect = pyodbc_errors

            # WHEN: Calling the doImport method
            for effect in pyodbc_errors:
                return_value = importer.doImport()

                # THEN: doImport should return None, and pyodbc, translate & logError are called with known calls
                self.assertIsNone(return_value, 'doImport should return None when pyodbc raises an exception.')
                mocked_pyodbc_connect.assert_called_with( 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=import_source')
                mocked_translate.assert_called_with('SongsPlugin.WorshipCenterProImport',
                    'Unable to connect the WorshipCenter Pro database.')
                mocked_log_error.assert_called_with('import_source', 'Translated Text')
def test_scalyr_timeseries_aligned(monkeypatch, fx_timeseries_aligned):
    kwargs, res, exp = fx_timeseries_aligned

    read_key = '123'

    post = MagicMock()
    post.return_value.json.return_value = res

    monkeypatch.setattr('requests.post', post)

    scalyr = ScalyrWrapper(read_key)
    result = scalyr.timeseries(**kwargs)

    assert result == exp

    query = get_query('facet', kwargs.get('function', 'count'), read_key, **kwargs)

    query.pop('queryType')

    final_q = {
        'token': query.pop('token'),
        'queries': [query]
    }

    post.assert_called_with(
        scalyr._ScalyrWrapper__timeseries_url, json=final_q, headers={'Content-Type': 'application/json'})
    def test_aws_relationship_external(self):
        fake_class_instance = MagicMock()
        FakeClass = MagicMock(return_value=fake_class_instance)

        mock_func = MagicMock()

        @decorators.aws_relationship(class_decl=FakeClass)
        def test_with_mock(*args, **kwargs):
            mock_func(*args, **kwargs)

        _ctx = self._gen_decorators_realation_context(test_properties={
            'use_external_resource': True
        })

        test_with_mock(ctx=_ctx)

        mock_func.assert_not_called()

        # force run
        test_with_mock(ctx=_ctx, force_operation=True)

        mock_func.assert_called_with(
            ctx=_ctx,
            iface=fake_class_instance, resource_config={},
            force_operation=True, resource_type='AWS Resource')
    def test_no_error_loading_users(self, base, toolkit, model, g, logic):

        # actions
        default_user = {'user_name': 'test', 'another_val': 'example value'}
        user_show = MagicMock(return_value=default_user)
        acquisitions_list = MagicMock()

        toolkit.get_action = MagicMock(side_effect=lambda action: user_show if action == 'user_show' else acquisitions_list)

        # Call the function
        returned = views.acquired_datasets()

        # User_show called correctly
        expected_context = {
            'auth_user_obj': g.userobj,
            'for_view': True,
            'model': model,
            'session': model.Session,
            'user': g.user,
        }

        user_show.assert_called_once_with(expected_context, {'user_obj': g.userobj})
        acquisitions_list.assert_called_with(expected_context, None)

        # Check that the render method has been called
        base.render.assert_called_once_with('user/dashboard_acquired.html', {'user_dict': default_user, 'acquired_datasets': acquisitions_list()})
        self.assertEqual(returned, base.render())
    def test_setup_func(self):
        # Run it when the collection doesn't exist
        with mock.patch('anki.storage.Collection') as anki_storage_Collection:
            col = anki_storage_Collection.return_value
            setup_new_collection = MagicMock()
            self.assertFalse(os.path.exists(self.collection_path))
            wrapper = CollectionWrapper(self.collection_path, setup_new_collection)
            wrapper.open()
            anki_storage_Collection.assert_called_with(self.collection_path)
            setup_new_collection.assert_called_with(col)
            wrapper = None

        # Make sure that no collection was actually created
        self.assertFalse(os.path.exists(self.collection_path))
        
        # Create a faux collection file
        with file(self.collection_path, 'wt') as fd:
            fd.write('Collection!')

        # Run it when the collection does exist
        with mock.patch('anki.storage.Collection'):
            setup_new_collection = lambda col: self.fail("Setup function called when collection already exists!")
            self.assertTrue(os.path.exists(self.collection_path))
            wrapper = CollectionWrapper(self.collection_path, setup_new_collection)
            wrapper.open()
            anki_storage_Collection.assert_called_with(self.collection_path)
            wrapper = None
Exemple #22
0
    def test_user_not_allowed_actions_user(self, caching_mock):
        """Test POST, PUT and DELETE for USER actions are not allowed for user
        in the API"""
        clean_user_mock = MagicMock()
        caching_mock.get.return_value = dict(refresh=clean_user_mock)
        admin = UserFactory.create()
        auth = UserFactory.create()
        user = UserFactory.create()
        url = 'api/user'
        res = self.app.post(url + '?api_key=%s' % auth.api_key,
                            data=json.dumps(user.to_public_json()))
        data = json.loads(res.data)
        assert res.status_code == 405, res.status_code
        assert data['status_code'] == 405, data

        # Update another user
        url += '/%s' % user.id
        res = self.app.put(url + '?api_key=%s' % auth.api_key,
                           data=json.dumps(dict(name='new')))
        assert res.status_code == 403, res.data

        res = self.app.delete(url + '?apikey=%s' % auth.api_key)
        assert res.status_code == 405, res.status_code

        # Update the same user
        url = 'api/user/%s' % auth.id
        res = self.app.put(url + '?api_key=%s' % auth.api_key,
                           data=json.dumps(dict(name='new')))
        data = json.loads(res.data)
        assert res.status_code == 200, res.data
        assert data['name'] == 'new', data
        clean_user_mock.assert_called_with(data['id'])
Exemple #23
0
    def it_calls_the_actions_passing_the_program_name(self):
        on_raw = MagicMock()
        parser = Parser()
        parser.add_option('raw', on_raw)

        parser(['trash-list', '--raw'])

        on_raw.assert_called_with('trash-list')
Exemple #24
0
    def test_from_settings(self, stringport):
        mock_backend = MagicMock('Mock Backend')
        stringport.return_value = mock_backend

        with self.settings(OPAL_SEARCH_BACKEND='mybackend'):
            backend = queries.create_query(self.user, [])
            self.assertEqual(mock_backend.return_value, backend)
            mock_backend.assert_called_with(self.user, [])
Exemple #25
0
def test_get_client_missing(config):
    mock_factory = MagicMock()
    mock_factory.return_value = None
    registry = config.registry
    registry.registerUtility(mock_factory, interfaces.IClientFactory)
    request = testing.DummyRequest(registry=config.registry)
    assert auth.get_client(request, '9876') is None
    mock_factory.assert_called_with(request, '9876')
Exemple #26
0
 def test_cluster_complete(self):
     mock_set_status = MagicMock()
     self.manager.appStatus.set_status = mock_set_status
     self.manager.appStatus._get_actual_db_status = MagicMock(
         return_value=rd_instance.ServiceStatuses.RUNNING)
     self.manager.cluster_complete(self.context)
     mock_set_status.assert_called_with(
         rd_instance.ServiceStatuses.RUNNING, force=True)
Exemple #27
0
    def how_getopt_works_with_an_invalid_option(self):
        invalid_option_callback = MagicMock()
        parser = Parser()
        parser.on_invalid_option(invalid_option_callback)

        parser(['command-name', '-x'])

        invalid_option_callback.assert_called_with('command-name', 'x')
def test_get_upsi_config(monkeypatch):
    service_guid = 'some-fake-guid'
    mock_cf_curl_get = MagicMock(return_value=json.loads(UPSI_CONFIG))
    monkeypatch.setattr('apployer.cf_api._cf_curl_get', mock_cf_curl_get)

    assert cf_api.get_upsi_credentials(service_guid) == {'creds-key-44': 'creds-val-44'}
    mock_cf_curl_get.assert_called_with(
        '/v2/user_provided_service_instances/{}'.format(service_guid))
    def test_update_topic_1(self, value):
        topic_settings = {'display_name': self.DISPLAY_NAME1}
        update_topic_mock = MagicMock(return_value=value)
        self.tracker1.update_topic = update_topic_mock

        self.assertEqual(value, self.trackers_manager.update_topic(self.tracker1_id1, topic_settings))

        update_topic_mock.assert_called_with(self.tracker1_id1, topic_settings)
Exemple #30
0
 def test_get_data_request_uri(self):
     mock = MagicMock(return_value=RequestsResponse(
         {'votering': {'dokvotering': []}})
     )
     with patch('requests.get', mock):
         get_votation(self.votation_id)
     mock.assert_called_with(
         '{0}/votering/{1}/json'.format(API_URL, self.votation_id))
def test_initialize():
    model_fn = MagicMock()

    _transformer.Transformer(model_fn=model_fn).initialize()

    model_fn.assert_called_with(_env.model_dir)
Exemple #32
0
    def test_set_author_flair(self):
        post = helpers.post()
        mod = Moderator(post)
        flair_mock = MagicMock()
        post.subreddit.flair.set = flair_mock
        old_get_flair = ModeratorAuthorChecks.flair_text.__wrapped__
        get_flair_mock = MagicMock(return_value=None)
        ModeratorAuthorChecks.flair_text.__wrapped__ = get_flair_mock

        # Sets text
        mod.moderate(Rule({'id': post.id, 'author': {'set_flair': 'test'}}))
        flair_mock.assert_called_with(text='test')

        # Sets both text and css
        flair_mock.reset_mock()
        mod.moderate(
            Rule({
                'id': post.id,
                'author': {
                    'set_flair': ['test', 'csstest']
                }
            }))
        flair_mock.assert_called_with(text='test', css_class='csstest')

        # Raises an exception if a dictionary is passed with no template_id
        with self.assertRaises(Exception):
            mod.moderate(
                Rule({
                    'id': post.id,
                    'author': {
                        'set_flair': {
                            'text': 'test'
                        }
                    }
                }))

        # Sets template_id, text, and css
        flair_mock.reset_mock()
        mod.moderate(
            Rule({
                'id': post.id,
                'author': {
                    'set_flair': {
                        'template_id': 'idtest',
                        'text': 'test',
                        'css_class': 'csstest'
                    }
                }
            }))
        flair_mock.assert_called_with(text='test',
                                      css_class='csstest',
                                      template_id='idtest')

        # Does not set new flair, because overwrite_flair is not set
        flair_mock.reset_mock()
        get_flair_mock.return_value = 'before'
        mod.moderate(Rule({'id': post.id, 'author': {'set_flair': 'test'}}))
        flair_mock.assert_not_called()

        mod.moderate(
            Rule({
                'id': post.id,
                'author': {
                    'set_flair': 'test',
                    'overwrite_flair': True
                }
            }))
        flair_mock.assert_called_with(text='test')

        ModeratorAuthorChecks.flair_text.__wrapped__ = old_get_flair
Exemple #33
0
class TestVTab(unittest.TestCase):
    def setUp(self):
        self.log = Log("testlog.txt")
        self.log.add = MagicMock()

        self.root = Tk()
        self.root.title("kbase test")
        self.root.geometry("400x500")

        self.dummy = MagicMock()

        self.actionlist = {"tabChangeAction": self.dummy}

        self.vtab = VTab(parent=self.root,
                         log=self.log,
                         actions=self.actionlist)

        self.results = None

        self.vsearchdrawtemp = VSearch.drawSearchResults
        VSearch.drawSearchResults = MagicMock()
        self.vsearchremovetemp = VSearch.removeOldResults
        VSearch.removeOldResults = MagicMock()

        self.entryDrawTemp = VEntry.drawEntry

    def tearDown(self):
        VEntry.drawEntry = self.entryDrawTemp
        VSearch.removeOldResults = self.vsearchremovetemp
        VSearch.drawSearchResults = self.vsearchdrawtemp
        self.vtab.grid()
        self.root.update()
        self.root.destroy()

    def testTabChangedEvent(self):
        '''Tests if right method is called at tab change event'''
        # test with overview active
        self.vtab.setOverview(dict())
        self.vtab.grid()
        self.root.update()
        self.vtab.focus_force()
        self.vtab.event_generate("<<NotebookTabChanged>>")
        self.dummy.assert_called_with(self.vtab.overview.name)

        # test with search active
        self.vtab.setSearch(self.results)
        self.vtab.grid()
        self.root.update()
        self.vtab.focus_force()
        self.vtab.event_generate("<<NotebookTabChanged>>")
        self.dummy.assert_called_with(self.vtab.vsearch.name)

        # test with entry active
        e = ModelEntry(self.log, "entry")
        self.vtab.addEntry(e)
        self.vtab.grid()
        self.root.update()
        self.vtab.focus_force()
        self.vtab.event_generate("<<NotebookTabChanged>>")
        self.dummy.assert_called_with(e.name)

    def testHasTabs(self):
        '''Tests whether hasTabs works correctly'''
        self.assertFalse(self.vtab.hasTabs())
        self.vtab.setSearch(self.results)
        self.assertTrue(self.vtab.hasTabs())

    def testSetSearchInitial(self):
        '''Tests whether initial search works'''
        self.vtab.setSearch(self.results)
        # get all tab names. The names also include vtab's name
        tabs = self.vtab.tabs()
        # gets the full name of vsearch widget
        vsearchName = "." + self.vtab._name + "." + self.vtab.vsearch._name
        # first tab should be
        self.assertEqual(vsearchName, tabs[0])
        self.vtab.vsearch.drawSearchResults.assert_called_with(self.results)
        self.assertEqual(vsearchName, self.vtab.select(),
                         "wrong tab is active")

    def testSetSearchASecondTime(self):
        '''Tests whether a second search overwrites the first one'''
        secondResults = None
        self.vtab.setSearch(self.results)
        self.vtab.setSearch(secondResults)
        # get all tab names. The names also include vtab's name
        tabs = self.vtab.tabs()
        # gets the full name of vsearch widget
        vsearchName = "." + self.vtab._name + "." + self.vtab.vsearch._name
        # first tab should be
        self.assertEqual(vsearchName, tabs[0])
        self.vtab.vsearch.removeOldResults.assert_called()
        self.vtab.vsearch.drawSearchResults.assert_called_with(secondResults)
        self.assertEqual(vsearchName, self.vtab.select(),
                         "wrong tab is active")

    def testAddEntry(self):
        '''Tests whether add works'''
        e = ModelEntry(self.log, "entry")
        self.vtab.addEntry(e)

        # get all tab names. The names also include vtab's name
        tabs = self.vtab.tabs()
        # gets the full name of ventry widget
        ventryName = "." + self.vtab._name + "." + self.vtab.ventries[
            e.name]._name
        # first tab should be
        self.assertEqual(ventryName, tabs[0])
        self.assertEqual(ventryName, self.vtab.select(), "wrong tab is active")

    def testAddExistingEntry(self):
        '''Trys to add an already existing entry'''
        e1 = ModelEntry(self.log, "e1")
        e2 = ModelEntry(self.log, "e2")
        self.vtab.addEntry(e1)
        self.vtab.addEntry(e2)
        self.vtab.addEntry(e1)
        self.assertEqual(2, self.vtab.tabs().__len__())
        self.assertEqual(2, self.vtab.ventries.__len__())

        # check if e1 is active tab
        ventryName = "." + self.vtab._name + "." + self.vtab.ventries[
            e1.name]._name
        self.assertEqual(ventryName, self.vtab.select(), "wrong tab is active")

    def testRemoveEntry(self):
        '''Removes an existing entry'''
        e = ModelEntry(self.log, "entry")
        self.vtab.addEntry(e)
        self.assertEqual(1, self.vtab.tabs().__len__())
        self.assertEqual(1, self.vtab.ventries.__len__())

        self.vtab.removeEntry(e)
        self.assertEqual(0, self.vtab.tabs().__len__())
        self.assertEqual(0, self.vtab.ventries.__len__())

    def testRemoveNotExistingEntry(self):
        '''Trys to remove a not existing entry'''
        e1 = ModelEntry(self.log, "e1")
        e2 = ModelEntry(self.log, "e2")
        self.vtab.addEntry(e1)
        self.vtab.addEntry(e2)
        self.assertEqual(2, self.vtab.tabs().__len__())
        self.assertEqual(2, self.vtab.ventries.__len__())

        self.vtab.removeEntry(e1)
        self.assertEqual(1, self.vtab.tabs().__len__())
        self.assertEqual(1, self.vtab.ventries.__len__())

        # get all tab names. The names also include vtab's name
        tabs = self.vtab.tabs()
        # gets the full name of ventry widget
        ventryName = "." + self.vtab._name + "." + self.vtab.ventries[
            e2.name]._name
        # first tab should be
        self.assertEqual(ventryName, tabs[0])

    def testRemoveSearch(self):
        self.vtab.setSearch(self.results)
        self.assertTrue(self.vtab.vsearchDrawn)
        self.assertEqual(1, self.vtab.children.values().__len__())

        self.vtab.removeSearch()
        self.assertEqual(0, self.vtab.children.values().__len__())

    def testGetActiveTabId(self):
        exp = "2342342"
        inp = "98739457345." + exp
        self.vtab.select = MagicMock()
        self.vtab.select.return_value = inp
        act = self.vtab.getActiveTabId()
        self.assertEqual(exp, act)

    def testGetNameOfActiveTab(self):
        # test overview
        self.vtab.setOverview(dict())
        self.vtab.grid()
        self.vtab.update()
        id = self.vtab.getTabId(self.vtab.overview)
        self.vtab.select(id)
        self.vtab.update()
        exp = self.vtab.overview.name
        act = self.vtab.getNameOfActiveTab()
        self.assertEqual(exp, act)

        # test search
        self.vtab.setSearch(None)
        self.vtab.grid()
        self.vtab.update()
        id = self.vtab.getTabId(self.vtab.vsearch)
        self.vtab.select(id)
        self.vtab.update()
        exp = self.vtab.vsearch.name
        act = self.vtab.getNameOfActiveTab()
        self.assertEqual(exp, act)

        # test entry
        self.vtab.addEntry(ModelEntry(self.log, "blu"))
        self.vtab.grid()
        self.vtab.update()
        id = self.vtab.getTabId(self.vtab.ventries["blu"])
        self.vtab.select(id)
        self.vtab.update()
        exp = self.vtab.ventries["blu"].getName()
        act = self.vtab.getNameOfActiveTab()
        self.assertEqual(exp, act)
Exemple #34
0
 def test_formats_output(self):
     for format in self.expected_formats:
         mock_f = MagicMock()
         setattr(self.of, format, mock_f)
         self.of.format_output(self.output_data, format)
         mock_f.assert_called_with(self.output_data)
Exemple #35
0
 def test_with_empty_args(self):
     callback = MagicMock()
     cuckoo = Cuckoo(callback=callback)
     cuckoo()
     callback.assert_called_with()
Exemple #36
0
 def test_file_loaded(self, content_mock: mock.MagicMock) -> None:
     """Test file loaded."""
     FileLookup.handle("plain:file://tmp/test")
     content_mock.assert_called_with("file://tmp/test")
Exemple #37
0
class TestDeleteTagsByAge(unittest.TestCase):
    def setUp(self):
        self.registry = Registry()
        self.registry.http = MockRequests()

        self.get_tag_config_mock = MagicMock(
            return_value={
                'mediaType':
                'application/vnd.docker.container.image.v1+json',
                'size':
                12953,
                'digest':
                'sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8'
            })
        self.registry.get_tag_config = self.get_tag_config_mock
        self.get_image_age_mock = MagicMock(
            return_value="2017-12-27T12:47:33.511765448Z")
        self.registry.get_image_age = self.get_image_age_mock
        self.list_tags_mock = MagicMock(return_value=["image"])
        self.registry.list_tags = self.list_tags_mock
        self.get_tag_digest_mock = MagicMock()
        self.registry.get_tag_digest = self.get_tag_digest_mock
        self.registry.http = MockRequests()
        self.registry.hostname = "http://testdomain.com"
        self.registry.http.reset_return_value(200, "MOCK_DIGEST")

    @patch('registry.delete_tags')
    def test_delete_tags_by_age_no_keep(self, delete_tags_patched):
        delete_tags_by_age(self.registry, "imagename", False, 24, [])
        self.list_tags_mock.assert_called_with("imagename")
        self.list_tags_mock.assert_called_with("imagename")
        self.get_tag_config_mock.assert_called_with("imagename", "image")
        delete_tags_patched.assert_called_with(self.registry, "imagename",
                                               False, ["image"], [])

    @patch('registry.delete_tags')
    def test_delete_tags_by_age_keep_tags(self, delete_tags_patched):
        delete_tags_by_age(self.registry, "imagename", False, 24, ["latest"])
        self.list_tags_mock.assert_called_with("imagename")
        self.list_tags_mock.assert_called_with("imagename")
        self.get_tag_config_mock.assert_called_with("imagename", "image")
        delete_tags_patched.assert_called_with(self.registry, "imagename",
                                               False, ["image"], ["latest"])

    @patch('registry.delete_tags')
    def test_delete_tags_by_age_dry_run(self, delete_tags_patched):
        delete_tags_by_age(self.registry, "imagename", True, 24, ["latest"])
        self.list_tags_mock.assert_called_with("imagename")
        self.list_tags_mock.assert_called_with("imagename")
        self.get_tag_config_mock.assert_called_with("imagename", "image")
        delete_tags_patched.assert_called_with(self.registry, "imagename",
                                               True, ["image"], ["latest"])
def test_lambda_handler(ami_pattern, pipeline_override_ami, event_override_ami,
                        expected_error, exception_message, monkeypatch):
    """Test trigger_build_function.lambda_handler"""

    # Setup mock input
    soe_image_name = 'plt-baking-soe-ami-for-unit-test'
    mock_automation_execution_id = 'mock_automation_execution_id'
    ssm_document = 'SSMDocument'
    soe_type = 'lnx'
    ami_owner = 'self'

    # Set Environment Variables
    monkeypatch.setenv("SSMDocument", ssm_document)
    monkeypatch.setenv("SOEType", soe_type)
    monkeypatch.setenv("AMIPattern", ami_pattern)
    monkeypatch.setenv("AMIOwner", ami_owner)
    monkeypatch.setenv("OverrideAMI", pipeline_override_ami)
    # We need to reload the module so it re-reads the os.environ values we set above
    reload(trigger_build_function)

    # patch trigger_ssm as moto does NOT support start_automation_execution yet
    # https://github.com/spulec/moto/blame/603f7c58a230919da3ee836575351366e46cc26c/IMPLEMENTATION_COVERAGE.md#L4022
    mock_trigger_ssm = MagicMock(return_value=mock_automation_execution_id)
    monkeypatch.setattr('trigger_build.trigger_build_function.trigger_ssm',
                        mock_trigger_ssm)

    if pipeline_override_ami:
        ami_id = pipeline_override_ami
    else:
        # Setup mock Public AMI (we need to create a AMI and modify launch permissions)
        # 1. Create a mock SOE image from a instance
        ec2_client = boto3.client('ec2', region_name=CONST_REGION)
        run_ec2_response = ec2_client.run_instances(ImageId='ami-12345678',
                                                    MaxCount=1,
                                                    MinCount=1)
        instance_id = run_ec2_response['Instances'][0]['InstanceId']
        print(instance_id)
        create_ami_response = ec2_client.create_image(
            Description='Moto unit test image 1',
            InstanceId=instance_id,
            Name=soe_image_name)
        ami_id = create_ami_response['ImageId']

        # 2. Make mock SOE image Public
        exec_user_id = '123456789012'
        # We need to override the EXEC_USERS in the actual module as moto does not support 'all' yet
        # https://github.com/spulec/moto/blob/d8dbc6a49ccf969f50ed3f7b52f341db3a7715f0/moto/ec2/models.py#L1190
        monkeypatch.setattr('trigger_build.trigger_build_function.EXEC_USERS',
                            exec_user_id)
        modify_image_response = ec2_client.modify_image_attribute(
            Attribute='launchPermission',
            ImageId=ami_id,
            OperationType='add',
            UserIds=[exec_user_id],
            UserGroups=['all'])
        print("modify_image_response")
        print(modify_image_response)

    # Setup Input
    event = {}
    context = ContextMock()

    if event_override_ami:
        event['OverrideAMI'] = event_override_ami
        ami_id = event_override_ami

    # Test Lambda handler
    if isinstance(expected_error, type):
        with pytest.raises(expected_error) as excinfo:
            trigger_build_function.lambda_handler(event, context)
        #TODO: Improve the error handling in the lambda_handler
        assert exception_message in str(excinfo.value)
        mock_trigger_ssm.assert_not_called()
    else:
        output_event = trigger_build_function.lambda_handler(
            copy.deepcopy(event), context)
        print("output_event")
        print(output_event)

        # Verify the output
        assert output_event != event  # Assert that the event has been modified
        assert output_event[
            "BuildAutomationExecutionId"] == mock_automation_execution_id

        mock_trigger_ssm.assert_called_with(CONST_SOL_NAMING, CONST_REGION,
                                            ssm_document, soe_type, ami_id)
def test_should_calls_load_account_by_id_correct_values(
        mock_load: MagicMock, sut: AuthMiddleware):
    sut.handle(HttpRequest(headers={"x-access-token": "any_token"}, body=None))
    mock_load.assert_called_with(access_token="any_token", role=None)
Exemple #40
0
class TestClient(unittest.TestCase):
    def setUp(self):
        self.api_key = 'heythere'
        self.api_url = taxjar.DEFAULT_API_URL + "/" + taxjar.API_VERSION + "/"
        self.headers = {"Authorization": "Bearer heythere"}
        self.responder_mock = MagicMock()
        self.client = taxjar.Client(api_key=self.api_key, options={}, responder=self.responder_mock)

    def test_client_params(self):
        self.client = taxjar.Client(api_key=self.api_key, api_url='https://api.sandbox.taxjar.com', options={
            'headers': {
                'X-TJ-Expected-Response': '422'
            }
        }, responder=self.responder_mock)
        self.assertEqual(self.client.api_url, 'https://api.sandbox.taxjar.com/v2/')
        self.assertEqual(self.client.headers, { 'X-TJ-Expected-Response': '422' })

    def test_set_api_config(self):
        self.client.set_api_config('api_url', 'https://api.sandbox.taxjar.com')
        self.assertEqual(self.client.api_url, 'https://api.sandbox.taxjar.com/v2/')

    def test_get_api_config(self):
        self.client.set_api_config('api_url', 'https://api.sandbox.taxjar.com')
        self.assertEqual(self.client.get_api_config('api_url'), self.client.api_url)

    def test_custom_headers(self):
        self.client.set_api_config('headers', {
            'X-TJ-Expected-Response': '422'
        })
        self.assertEqual(self.client.headers, {
            'X-TJ-Expected-Response': '422'
        })
        self.assertEqual(self.client._headers()['X-TJ-Expected-Response'], '422')
        self.assertEqual(self.client._headers()['Authorization'], 'Bearer heythere')
        self.assertRegexpMatches(self.client._headers()['User-Agent'], re.compile('TaxJar/Python \\(.+\\) taxjar-python/\\d+\\.\\d+\\.\\d+'))

    def test_rates_for_location(self):
        action = lambda _: self.client.rates_for_location('90210')
        self.assert_request_occurred(action, 'get', 'rates/90210', {})

    def test_rates_for_location_with_deets(self):
        action = lambda _: self.client.rates_for_location('90210', {
            'city': 'Beverly Hills',
            'country': 'US'
        })
        self.assert_request_occurred(action, 'get', 'rates/90210', {
            'city': 'Beverly Hills',
            'country': 'US'
        })

    def test_categories(self):
        action = lambda _: self.client.categories()
        self.assert_request_occurred(action, 'get', 'categories', {})

    def test_tax_for_order(self):
        data = {'shipping': 0}
        action = lambda _: self.client.tax_for_order(data)
        self.assert_request_occurred(action, 'post', 'taxes', data)

    def test_list_orders(self):
        data = {'dummy': 'data'}
        action = lambda _: self.client.list_orders(data)
        self.assert_request_occurred(action, 'get', 'transactions/orders', data)
        action = lambda _: self.client.list_orders()
        self.assert_request_occurred(action, 'get', 'transactions/orders', {})

    def test_show_order(self):
        action = lambda _: self.client.show_order('1001')
        self.assert_request_occurred(action, 'get', 'transactions/orders/1001', {})
        action = lambda _: self.client.show_order('1001', {'provider': 'api'})
        self.assert_request_occurred(action, 'get', 'transactions/orders/1001', {
            'provider': 'api'
        })

    def test_create_order(self):
        data = {'dummy': 'data'}
        action = lambda _: self.client.create_order(data)
        self.assert_request_occurred(action, 'post', 'transactions/orders', data)

    def test_update_order(self):
        data = {'dummy': 'data'}
        action = lambda _: self.client.update_order(1, data)
        self.assert_request_occurred(action, 'put', 'transactions/orders/1', data)

    def test_delete_order(self):
        action = lambda _: self.client.delete_order(1)
        self.assert_request_occurred(action, 'delete', 'transactions/orders/1', {})
        action = lambda _: self.client.delete_order(1, {'provider': 'api'})
        self.assert_request_occurred(action, 'delete', 'transactions/orders/1', {
            'provider': 'api'
        })

    def test_list_refunds(self):
        data = {'from_transaction_date': '2016/01/01', 'to_transaction_date': '2017/01/01'}
        action = lambda _: self.client.list_refunds(data)
        self.assert_request_occurred(action, 'get', 'transactions/refunds', data)
        action = lambda _: self.client.list_refunds()
        self.assert_request_occurred(action, 'get', 'transactions/refunds', {})

    def test_show_refund(self):
        action = lambda _: self.client.show_refund('1001')
        self.assert_request_occurred(action, 'get', 'transactions/refunds/1001', {})
        action = lambda _: self.client.show_refund('1001', {'provider': 'api'})
        self.assert_request_occurred(action, 'get', 'transactions/refunds/1001', {
            'provider': 'api'
        })

    def test_create_refund(self):
        data = {'dummy': 'data'}
        action = lambda _: self.client.create_refund(data)
        self.assert_request_occurred(action, 'post', 'transactions/refunds', data)

    def test_update_refund(self):
        data = {'dummy': 'data'}
        action = lambda _: self.client.update_refund(1, data)
        self.assert_request_occurred(action, 'put', 'transactions/refunds/1', data)

    def test_delete_refund(self):
        action = lambda _: self.client.delete_refund(1)
        self.assert_request_occurred(action, 'delete', 'transactions/refunds/1', {})
        action = lambda _: self.client.delete_refund(1, {'provider': 'api'})
        self.assert_request_occurred(action, 'delete', 'transactions/refunds/1', {
            'provider': 'api'
        })

    def test_list_customers(self):
        action = lambda _: self.client.list_customers()
        self.assert_request_occurred(action, 'get', 'customers', {})

    def test_show_customer(self):
        action = lambda _: self.client.show_customer('123')
        self.assert_request_occurred(action, 'get', 'customers/123', {})

    def test_create_customer(self):
        data = {'dummy': 'data'}
        action = lambda _: self.client.create_customer(data)
        self.assert_request_occurred(action, 'post', 'customers', data)

    def test_update_customer(self):
        data = {'dummy': 'data'}
        action = lambda _: self.client.update_customer('123', data)
        self.assert_request_occurred(action, 'put', 'customers/123', data)

    def test_delete_customer(self):
        action = lambda _: self.client.delete_customer('123')
        self.assert_request_occurred(action, 'delete', 'customers/123', {})

    def test_nexus_regions(self):
        action = lambda _: self.client.nexus_regions()
        self.assert_request_occurred(action, 'get', 'nexus/regions', {})

    def test_validate_address(self):
        data = {'country': 'US', 'state': 'AZ', 'zip': '85297', 'city': 'Gilbert', 'street': '3301 South Greenfield Rd'}
        action = lambda _: self.client.validate_address(data)
        self.assert_request_occurred(action, 'post', 'addresses/validate', data)

    def test_validate(self):
        action = lambda _: self.client.validate({'vat': '1234'})
        self.assert_request_occurred(action, 'get', 'validation', {'vat': '1234'})

    def test_summary_rates(self):
        action = lambda _: self.client.summary_rates()
        self.assert_request_occurred(action, 'get', 'summary_rates', {})

    def assert_request_occurred(self, action, request_method, uri, params):
        url = self.api_url + uri
        with patch.object(requests, request_method) as request_mock:
            action(0)
            request_mock.assert_called_with(
                url,
                headers=self.client._headers(),
                **self._request_args(request_method, params)
            )
            self.responder_mock.assert_called_with(request_mock.return_value)

    def _request_args(self, method, params):
        args = {'timeout': 5}
        if method == 'get' or method == 'delete':
            args['params'] = params
        else:
            args['json'] = params
        return args
class TestReverseEngineerDDL(BaseTestGenerator):
    scenarios = [
        ('#execute When retriving the DDL for the creation of external '
         'tables, '
         'it retrieves information of the columns and the tables '
         'and generate the SQL to create the table',
         dict(test_type='execute',
              function_parameters=dict(table_oid=14),
              find_columns_return_value=dict(somevalue='value'),
              table_information_return_value=dict(someother='bamm'),
              expect_find_columns_called_with=14,
              expect_table_information_called_with=14,
              expect_render_template_called_with=dict(
                  template_name_or_list='sql/#gpdb#80323#/create.sql',
                  table=dict(someother='bamm',
                             columns=dict(somevalue='value'))))),
        ('#find_columns When an external table exists, '
         'and have 3 columns, '
         'it returns a list with 1 object that as the table name to inherit '
         'from',
         dict(
             test_type='find_columns',
             function_parameters={'table_oid': 123},
             execute_2darray_return_value=(True,
                                           dict(rows=[{
                                               'name': 'column_1',
                                               'cltype': 'text',
                                               'inheritedFrom': 'other_table',
                                               'inheritedid': '1234',
                                           }, {
                                               'name': 'column_2',
                                               'cltype': 'int',
                                               'inheritedFrom': 'other_table',
                                               'inheritedid': '1234',
                                           }, {
                                               'name': 'column_3',
                                               'cltype': 'numeric',
                                               'inheritedFrom': 'other_table',
                                               'inheritedid': '1234',
                                           }])),
             expect_render_template_called_with=dict(
                 template_name_or_list='sql/#gpdb#80323#/get_columns.sql',
                 table_oid=123),
             expected_result=[
                 {
                     'name': 'column_1',
                     'type': 'text'
                 },
                 {
                     'name': 'column_2',
                     'type': 'int'
                 },
                 {
                     'name': 'column_3',
                     'type': 'numeric'
                 },
             ],
         )),
        ('#find_columns When error happens while retrieving '
         'column information, '
         'it raise an exception',
         dict(
             test_type='find_columns',
             function_parameters={'table_oid': 123},
             execute_2darray_return_value=(False, 'Some error message'),
             expect_render_template_called_with=dict(
                 template_name_or_list='sql/#gpdb#80323#/get_columns.sql',
                 table_oid=123),
             expected_exception=ReverseEngineerDDLException(
                 'Some error message'),
         )),
        ('#table_information When error happens while retrieving '
         'table generic information, '
         'it raise an exception',
         dict(
             test_type='table_information',
             function_parameters={'table_oid': 123},
             execute_2darray_return_value=(False, 'Some error message'),
             expect_render_template_called_with=dict(
                 template_name_or_list='sql/#gpdb#80323#/'
                 'get_table_information.sql',
                 table_oid=123),
             expected_exception=ReverseEngineerDDLException(
                 'Some error message'),
         )),
        ('#table_information When cannot find the table, '
         'it raise an exception',
         dict(
             test_type='table_information',
             function_parameters={'table_oid': 123},
             execute_2darray_return_value=(True, {
                 'rows': []
             }),
             expect_render_template_called_with=dict(
                 template_name_or_list='sql/#gpdb#80323#/'
                 'get_table_information.sql',
                 table_oid=123),
             expected_exception=ReverseEngineerDDLException('Table not found'),
         )),
        ('#table_information When retrieving generic information '
         'about a Web table, '
         'it returns the table information',
         dict(
             test_type='table_information',
             function_parameters={'table_oid': 123},
             execute_2darray_return_value=(
                 True,
                 dict(rows=[{
                     'urilocation': '{http://someurl.com}',
                     'execlocation': ['ALL_SEGMENTS'],
                     'fmttype': 'a',
                     'fmtopts': 'delimiter \',\' null \'\' '
                     'escape \'"\' quote \'"\'',
                     'command': None,
                     'rejectlimit': None,
                     'rejectlimittype': None,
                     'errtblname': None,
                     'errortofile': None,
                     'pg_encoding_to_char': 'UTF8',
                     'writable': False,
                     'options': None,
                     'distribution': None,
                     'name': 'some_table',
                     'namespace': 'public'
                 }])),
             expect_render_template_called_with=dict(
                 template_name_or_list='sql/#gpdb#80323#/'
                 'get_table_information.sql',
                 table_oid=123),
             expected_result={
                 'uris': ['http://someurl.com'],
                 'isWeb': True,
                 'executionLocation': dict(type='all_segments', value=None),
                 'formatType': 'avro',
                 'formatOptions': 'delimiter = $$,$$,escape = $$"$$,'
                 'null = $$$$,quote = $$"$$',
                 'command': None,
                 'rejectLimit': None,
                 'rejectLimitType': None,
                 'errorTableName': None,
                 'erroToFile': None,
                 'pgEncodingToChar': 'UTF8',
                 'writable': False,
                 'options': None,
                 'distribution': None,
                 'name': 'some_table',
                 'namespace': 'public'
             },
         )),
    ]

    def __init__(self, *args, **kwargs):
        super(TestReverseEngineerDDL, self).__init__(*args, **kwargs)
        self.connection = None
        self.subject = None
        self.render_template_mock = None

    def runTest(self):
        self.render_template_mock = MagicMock()
        self.connection = MagicMock(execute_2darray=MagicMock())
        if hasattr(self, 'execute_2darray_return_value'):
            self.connection.execute_2darray.return_value = \
                self.execute_2darray_return_value
        self.subject = ReverseEngineerDDL('sql/#gpdb#80323#/',
                                          self.render_template_mock,
                                          self.connection, 1, 2, 3)
        if self.test_type == 'find_columns':
            self.__test_find_columns()
        elif self.test_type == 'table_information':
            self.__test_table_information()
        elif self.test_type == 'execute':
            self.__test_execute()

    def __test_find_columns(self):
        if hasattr(self, 'expected_exception'):
            try:
                self.subject.find_columns(**self.function_parameters)
                self.fail('Exception not raise')
            except ReverseEngineerDDLException as exception:
                self.assertEqual(str(exception), str(self.expected_exception))
        else:
            result = self.subject.find_columns(**self.function_parameters)
            self.assertEqual(self.expected_result, result)

        self.render_template_mock.assert_called_with(
            **self.expect_render_template_called_with)

    def __test_table_information(self):
        if hasattr(self, 'expected_exception'):
            try:
                self.subject.table_information(**self.function_parameters)
                self.fail('Exception not raise')
            except ReverseEngineerDDLException as exception:
                self.assertEqual(str(exception), str(self.expected_exception))
        else:
            result = self.subject.table_information(**self.function_parameters)
            self.assertEqual(self.expected_result, result)

        self.render_template_mock.assert_called_with(
            **self.expect_render_template_called_with)

    def __test_execute(self):
        self.subject.find_columns = MagicMock(
            return_value=self.find_columns_return_value)
        self.subject.table_information = MagicMock(
            return_value=self.table_information_return_value)

        self.subject.execute(**self.function_parameters)

        self.subject.find_columns.assert_called_with(
            self.expect_find_columns_called_with)
        self.subject.table_information.assert_called_with(
            self.expect_table_information_called_with)
        self.render_template_mock.assert_called_with(
            **self.expect_render_template_called_with)
Exemple #42
0
 def test_callback_with_mixed_args_and_kwargs(self):
     callback = MagicMock()
     cuckoo = Cuckoo(callback=callback)
     cuckoo(1, 2, c=3, d=4)
     callback.assert_called_with(1, 2, c=3, d=4)
class SessionAwareSemaphoreMockTest(unittest.TestCase):
    def setUp(self):
        self.acquire_session = MagicMock()
        self.release_session = MagicMock()
        self.invalidate_session = MagicMock()
        self.session_manager = MagicMock(
            acquire_session=self.acquire_session,
            release_session=self.release_session,
            invalidate_session=self.invalidate_session,
        )
        context = MagicMock(proxy_session_manager=self.session_manager)
        self.group_id = RaftGroupId("test", 0, 42)
        self.semaphore = SessionAwareSemaphore(
            context, self.group_id, SEMAPHORE_SERVICE, "semaphore@mygroup", "semaphore"
        ).blocking()

    def test_acquire(self):
        # Everything works
        self.prepare_acquire_session(1)
        self.mock_request_acquire(True)
        self.assertIsNone(self.semaphore.acquire())
        self.assert_call_counts(1, 0, 0)
        self.assert_acquire_count(1)

    def test_acquire_when_acquire_session_fails(self):
        # First call to acquire session fails, should not retry
        self.prepare_acquire_session(-1, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.acquire()

        self.assert_call_counts(1, 0, 0)
        self.assert_acquire_count(1)

    def test_acquire_on_session_expired_error(self):
        # Session expired error comes from the server on acquire request,
        # retries and succeeds
        self.prepare_acquire_session(1)
        self.mock_request_acquire(True, SessionExpiredError())
        self.assertIsNone(self.semaphore.acquire())
        self.assert_call_counts(2, 0, 1)
        self.assert_acquire_count(1)

    def test_acquire_on_wait_key_cancelled_error(self):
        # Wait key cancelled error comes from the server, should not retry
        self.prepare_acquire_session(12)
        self.mock_request_acquire(True, WaitKeyCancelledError())

        with self.assertRaises(IllegalStateError):
            self.semaphore.acquire()

        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(1)
        self.assert_release_count(12, 1)

    def test_acquire_on_unspecified_error(self):
        # Server sends another error, should not retry
        self.prepare_acquire_session(123)
        self.mock_request_acquire(False, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.acquire(15)

        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(15)
        self.assert_release_count(123, 15)

    def test_drain(self):
        # Everything works
        self.prepare_acquire_session(42)
        self.mock_request_drain(10)
        self.assertEqual(10, self.semaphore.drain_permits())
        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(DRAIN_SESSION_ACQ_COUNT)
        self.assert_release_count(42, DRAIN_SESSION_ACQ_COUNT - 10)

    def test_drain_when_acquire_session_fails(self):
        # First call to acquire session fails, should not retry
        self.prepare_acquire_session(-1, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.drain_permits()

        self.assert_call_counts(1, 0, 0)
        self.assert_acquire_count(DRAIN_SESSION_ACQ_COUNT)

    def test_drain_on_session_expired_error(self):
        # Session expired error comes from the server on drain request,
        # retries and succeeds
        self.prepare_acquire_session(99)
        self.mock_request_drain(101, SessionExpiredError())
        self.assertEqual(101, self.semaphore.drain_permits())
        self.assert_call_counts(2, 1, 1)
        self.assert_acquire_count(DRAIN_SESSION_ACQ_COUNT)
        self.assert_release_count(99, DRAIN_SESSION_ACQ_COUNT - 101)

    def test_drain_on_unspecified_error(self):
        # Server sends another error, should not retry
        self.prepare_acquire_session(123)
        self.mock_request_drain(False, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.drain_permits()

        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(DRAIN_SESSION_ACQ_COUNT)
        self.assert_release_count(123, DRAIN_SESSION_ACQ_COUNT)

    def test_reduce_permits(self):
        # Everything works
        self.prepare_acquire_session(42)
        self.mock_request_change()
        self.assertIsNone(self.semaphore.reduce_permits(15))
        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(1)
        self.assert_release_count(42, 1)

    def test_reduce_permits_when_acquire_session_fails(self):
        # First call to acquire session fails, should not retry
        self.prepare_acquire_session(-1, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.reduce_permits(12)

        self.assert_call_counts(1, 0, 0)
        self.assert_acquire_count(1)

    def test_reduce_permits_on_session_expired_error(self):
        # Session expired error comes from the server on change request
        self.prepare_acquire_session(99)
        self.mock_request_change(SessionExpiredError())

        with self.assertRaises(IllegalStateError):
            self.semaphore.reduce_permits(123)

        self.assert_call_counts(1, 1, 1)
        # Session will be invalidated before released, so release call is actually a no-op
        self.assert_acquire_count(1)
        self.assert_release_count(99, 1)

    def test_reduce_permits_on_unspecified_error(self):
        # Server sends another error
        self.prepare_acquire_session(1123)
        self.mock_request_change(HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.reduce_permits(54)

        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(1)
        self.assert_release_count(1123, 1)

    def test_increase_permits(self):
        # Everything works
        self.prepare_acquire_session(42)
        self.mock_request_change()
        self.assertIsNone(self.semaphore.increase_permits(15))
        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(1)
        self.assert_release_count(42, 1)

    def test_increase_permits_when_acquire_session_fails(self):
        # First call to acquire session fails, should not retry
        self.prepare_acquire_session(-1, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.increase_permits(12)

        self.assert_call_counts(1, 0, 0)
        self.assert_acquire_count(1)

    def test_increase_permits_on_session_expired_error(self):
        # Session expired error comes from the server on change request
        self.prepare_acquire_session(99)
        self.mock_request_change(SessionExpiredError())

        with self.assertRaises(IllegalStateError):
            self.semaphore.increase_permits(123)

        self.assert_call_counts(1, 1, 1)
        # Session will be invalidated before released, so release call is actually a no-op
        self.assert_acquire_count(1)
        self.assert_release_count(99, 1)

    def test_increase_permits_on_unspecified_error(self):
        # Server sends another error
        self.prepare_acquire_session(1123)
        self.mock_request_change(HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.increase_permits(54)

        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(1)
        self.assert_release_count(1123, 1)

    def test_release(self):
        # Everything works
        self.prepare_get_session(42)
        self.mock_request_release()
        self.assertIsNone(self.semaphore.release(15))
        self.assert_call_counts(0, 1, 0)
        self.assert_release_count(42, 15)

    def test_release_no_session(self):
        # No session found for the release request on the client.
        self.prepare_get_session(-1)

        with self.assertRaises(IllegalStateError):
            self.semaphore.release()

        self.assert_call_counts(0, 0, 0)

    def test_release_on_session_expired_error(self):
        # Session expired error comes from the server on release request,
        self.prepare_get_session(99)
        self.mock_request_release(SessionExpiredError())

        with self.assertRaises(IllegalStateError):
            self.semaphore.release(123)

        self.assert_call_counts(0, 1, 1)
        # Session will be invalidated before released, so release call is actually a no-op
        self.assert_release_count(99, 123)

    def test_release_on_unspecified_error(self):
        # Server sends another error
        self.prepare_get_session(1123)
        self.mock_request_release(HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.release(54)

        self.assert_call_counts(0, 1, 0)
        self.assert_release_count(1123, 54)

    def test_try_acquire(self):
        # Everything works
        self.prepare_acquire_session(1)
        self.mock_request_acquire(True)
        self.assertTrue(self.semaphore.try_acquire(15))
        self.assert_call_counts(1, 0, 0)
        self.assert_acquire_count(15)

    def test_try_acquire_when_acquire_session_fails(self):
        # First call to acquire session fails, should not retry
        self.prepare_acquire_session(-1, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.try_acquire()

        self.assert_call_counts(1, 0, 0)
        self.assert_acquire_count(1)

    def test_try_acquire_on_session_expired_error(self):
        # Session expired error comes from the server on acquire request,
        # determines the timeout
        self.prepare_acquire_session(1)
        self.mock_request_acquire(True, SessionExpiredError())
        self.assertFalse(self.semaphore.try_acquire())
        self.assert_call_counts(1, 0, 1)
        self.assert_acquire_count(1)

    def test_try_acquire_on_session_expired_error_when_not_timed_out(self):
        # Session expired error comes from the server on acquire request,
        # retries and succeeds
        self.prepare_acquire_session(123)
        self.mock_request_acquire(True, SessionExpiredError())
        self.assertTrue(self.semaphore.try_acquire(15, 3))
        self.assert_call_counts(2, 0, 1)
        self.assert_acquire_count(15)

    def test_try_acquire_on_wait_key_cancelled_error(self):
        # Wait key cancelled error comes from the server, should not retry
        self.prepare_acquire_session(12)
        self.mock_request_acquire(True, WaitKeyCancelledError())
        self.assertFalse(self.semaphore.try_acquire())
        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(1)
        self.assert_release_count(12, 1)

    def test_try_acquire_on_unspecified_error(self):
        # Server sends another error, should not retry
        self.prepare_acquire_session(123)
        self.mock_request_acquire(False, HazelcastRuntimeError())

        with self.assertRaises(HazelcastRuntimeError):
            self.semaphore.try_acquire()

        self.assert_call_counts(1, 1, 0)
        self.assert_acquire_count(1)
        self.assert_release_count(123, 1)

    def assert_call_counts(self, acquire, release, invalidate):
        self.assertEqual(acquire, self.acquire_session.call_count)
        self.assertEqual(release, self.release_session.call_count)
        self.assertEqual(invalidate, self.invalidate_session.call_count)

    def assert_acquire_count(self, count):
        self.acquire_session.assert_called_with(self.group_id, count)

    def assert_release_count(self, session_id, count):
        self.release_session.assert_called_with(self.group_id, session_id, count)

    def prepare_acquire_session(self, session_id, err=None):
        if err:
            val = ImmediateExceptionFuture(err)
        else:
            val = ImmediateFuture(session_id)

        acquire_mock = MagicMock(return_value=val)
        release_mock = MagicMock()
        invalidate_mock = MagicMock()
        self.session_manager.acquire_session = acquire_mock
        self.session_manager.release_session = release_mock
        self.session_manager.invalidate_session = invalidate_mock
        self.acquire_session = acquire_mock
        self.release_session = release_mock
        self.invalidate_session = invalidate_mock

    def prepare_get_session(self, session_id):
        self.session_manager.get_session_id = MagicMock(return_value=session_id)

    def mock_request_acquire(self, acquired, first_call_err=None):
        mock_request(self.semaphore, "_request_acquire", acquired, first_call_err)

    def mock_request_drain(self, count, first_call_err=None):
        mock_request(self.semaphore, "_request_drain", count, first_call_err)

    def mock_request_change(self, first_call_err=None):
        mock_request(self.semaphore, "_request_change", None, first_call_err)

    def mock_request_release(self, first_call_err=None):
        mock_request(self.semaphore, "_request_release", None, first_call_err)
Exemple #44
0
 def test_callback_with_multiple_args(self):
     callback = MagicMock()
     cuckoo = Cuckoo(callback=callback)
     cuckoo(1, 2, 3)
     callback.assert_called_with(1, 2, 3)
def test_opsgenie_notification(monkeypatch, is_alert, priority, override_description):
    post = MagicMock()

    monkeypatch.setattr('requests.post', post)

    alert = {
        'alert_changed': True, 'changed': True, 'is_alert': is_alert, 'entity': {'id': 'e-1'}, 'worker': 'worker-1',
        'alert_evaluation_ts': 1234,
        'alert_def': {
            'name': 'Alert',
            'team': 'zmon',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 1,
        }
    }

    NotifyOpsgenie._config = {'notifications.opsgenie.apikey': API_KEY}

    kwargs = {}
    if priority:
        kwargs['priority'] = priority
    else:
        priority = 'P1'

    if override_description:
        r = NotifyOpsgenie.notify(
            alert,
            message=MESSAGE,
            include_alert=False,
            teams=['team-1', 'team-2'],
            description=override_description,
            **kwargs
        )
    else:
        r = NotifyOpsgenie.notify(
            alert,
            message=MESSAGE,
            include_alert=False,
            teams=['team-1', 'team-2'],
            **kwargs
        )

    params = {}

    if is_alert:
        data = {
            'alias': 'ZMON-123',
            'message': '[zmon] - {}'.format(MESSAGE),
            'description': '',
            'entity': 'e-1',
            'priority': priority,
            'tags': [],
            'teams': [{'name': 'team-1'}, {'name': 'team-2'}],
            'source': 'worker-1',
            'note': '',
            'details': {'alert_evaluation_ts': 1234},
        }

        if override_description:
            data['description'] = override_description

    else:
        data = {
            'user': '******',
            'source': 'worker-1',
            'note': '',

        }

        params = {'identifierType': 'alias'}

    assert r == 0

    URL = URL_CREATE if is_alert else URL_CLOSE.format('ZMON-123')

    post.assert_called_with(URL, data=json.dumps(data, cls=JsonDataEncoder, sort_keys=True), headers=HEADERS, timeout=5,
                            params=params)
Exemple #46
0
 def test_nested_simple(self):
     np1_sub1 = MagicMock()
     np1_sub2 = MagicMock()
     np2_sub1 = MagicMock()
     p = Publisher()
     np1 = Publisher()
     np2 = Publisher()
     np1_subs = p.subscribe(np1, start=False)
     np2_subs = p.subscribe(np2, start=False)
     self.assertEqual(p.active, False)
     self.assertEqual(np1.active, False)
     self.assertEqual(np2.active, False)
     #subscribe to np1
     np1.subscribe(np1_sub1, start=False)
     np1.subscribe(np1_sub2, start=False)
     self.assertEqual(p.active, False)
     self.assertEqual(np1.active, False)
     self.assertEqual(np2.active, False)
     np1_sub1_subs = np1.subscribe(np1_sub1)
     self.assertEqual(p.active, True)
     self.assertEqual(np1.active, True)
     self.assertEqual(np2.active, False)
     np1_sub2_subs = np1.subscribe(np1_sub2)
     self.assertEqual(p.active, True)
     self.assertEqual(np1.active, True)
     self.assertEqual(np2.active, False)
     #send message to p
     p.send(1)
     np1_sub1.assert_called_with(1)
     np1_sub2.assert_called_with(1)
     self.assertEqual(np2_sub1.call_count, 0)
     #subscribe to np2
     np2_sub1_subs = np2.subscribe(np2_sub1)
     self.assertEqual(p.active, True)
     self.assertEqual(np1.active, True)
     self.assertEqual(np2.active, True)
     #send message to p
     p.send(2)
     np1_sub1.assert_called_with(2)
     np1_sub2.assert_called_with(2)
     np2_sub1.assert_called_with(2)
     self.assertEqual(np1_sub1.call_count, 2)
     self.assertEqual(np1_sub2.call_count, 2)
     self.assertEqual(np2_sub1.call_count, 1)
     #unsubscribe to np2
     np2_sub1_subs.stop()
     self.assertEqual(p.active, True)
     self.assertEqual(np1.active, True)
     self.assertEqual(np2.active, False)
     #send message to p
     p.send(3)
     np1_sub1.assert_called_with(3)
     np1_sub2.assert_called_with(3)
     np2_sub1.assert_called_with(2)
     self.assertEqual(np1_sub1.call_count, 3)
     self.assertEqual(np1_sub2.call_count, 3)
     self.assertEqual(np2_sub1.call_count, 1)
     #unsubscribe to np1_sub2
     np1_sub2_subs.stop()
     self.assertEqual(p.active, True)
     self.assertEqual(np1.active, True)
     self.assertEqual(np2.active, False)
     #send message to p
     p.send(4)
     np1_sub1.assert_called_with(4)
     np1_sub2.assert_called_with(3)
     np2_sub1.assert_called_with(2)
     self.assertEqual(np1_sub1.call_count, 4)
     self.assertEqual(np1_sub2.call_count, 3)
     self.assertEqual(np2_sub1.call_count, 1)
     #unsubscribe to np1_sub1
     np1_sub1_subs.stop()
     self.assertEqual(p.active, False)
     self.assertEqual(np1.active, False)
     self.assertEqual(np2.active, False)
     #send message to p
     p.send(5)
     np1_sub1.assert_called_with(4)
     np1_sub2.assert_called_with(3)
     np2_sub1.assert_called_with(2)
     self.assertEqual(np1_sub1.call_count, 4)
     self.assertEqual(np1_sub2.call_count, 3)
     self.assertEqual(np2_sub1.call_count, 1)
Exemple #47
0
class TestVSearch(unittest.TestCase):
    def setUp(self):
        self.log = Log("testlog.txt")
        self.log.add = MagicMock()

        self.root = Tk()
        self.root.title("kbase test")
        self.root.geometry("400x500")

        self.dummy = MagicMock()

        self.actionlist = {"showEntryAction": self.dummy}

        self.vsearch = VSearch(self.root, self.log, self.actionlist)

        self.e1 = ModelEntry(self.log, "e1")
        self.e2 = ModelEntry(self.log, "e2")
        self.e3 = ModelEntry(self.log, "e3")
        self.e4 = ModelEntry(self.log, "e4")

        self.results = {
            "name": [self.e1],
            "tag": [self.e2],
            "description": [self.e3, self.e4]
        }

    def tearDown(self):
        self.vsearch.grid()
        self.root.update()
        self.root.destroy()

    def testRemoveOldResults(self):
        '''Tests whether the remove method removes entire content'''
        self.vsearch.drawSearchResults(self.results)
        n = self.vsearch.children.__len__()
        self.assertGreater(n, 0)

        self.vsearch.removeOldResults()
        n = self.vsearch.children.__len__()
        self.assertEqual(0, n)

    def testDrawSearchResults(self):
        '''Tests whether all buttons are drawn'''
        self.vsearch.drawSearchResults(self.results)
        self.assertEqual(self.e1.name, self.vsearch.buttonName[0]["text"])
        self.assertEqual(self.e2.name, self.vsearch.buttonTag[0]["text"])
        self.assertEqual(self.e3.name,
                         self.vsearch.buttonDescription[0]["text"])
        self.assertEqual(self.e4.name,
                         self.vsearch.buttonDescription[1]["text"])

    def testButtonClicked(self):
        '''Tests whether the right buttons are clicked'''
        self.vsearch.drawSearchResults(self.results)
        self.vsearch.grid()
        self.root.update()

        # by name
        self.vsearch.buttonName[0].focus_force()
        self.vsearch.buttonName[0].invoke()
        self.dummy.assert_called_with(self.e1.name)

        # by tag
        self.vsearch.buttonTag[0].focus_force()
        self.vsearch.buttonTag[0].invoke()
        self.dummy.assert_called_with(self.e2.name)

        # by description
        self.vsearch.buttonDescription[1].focus_force()
        self.vsearch.buttonDescription[1].invoke()
        self.dummy.assert_called_with(self.e4.name)
def test_should_call_load_by_survey_id_on_load_survey_result_repo_correct_values(
        load_by_survey_id: MagicMock, sut: DbLoadSurveyResult):
    sut.load("any_survey_id")
    load_by_survey_id.assert_called_with("any_survey_id")
Exemple #49
0
 def test_simple(self):
     c1_sub1 = MagicMock()
     c1_sub2 = MagicMock()
     c2_sub1 = MagicMock()
     p = MultitopicPublisher()
     self.assertEqual(p.active, False)
     #send messages to random topics
     p.send(9, "c1")
     p.send(9, "c2")
     p.send(9, "something")
     p.send(9, "mytopic")
     #subscribe to c1
     c1_sub1_subs = p.subscribe(c1_sub1, "c1")
     self.assertEqual(p.active, True)
     c1_sub2_subs = p.subscribe(c1_sub2, "c1")
     #send message to c1
     p.send(1, "c1")
     c1_sub1.assert_called_with(1)
     c1_sub2.assert_called_with(1)
     self.assertEqual(c2_sub1.call_count, 0)
     #subscribe to c2
     c2_sub1_subs = p.subscribe(c2_sub1, "c2")
     #send message to c2
     p.send(2, "c2")
     c1_sub1.assert_called_with(1)
     c1_sub2.assert_called_with(1)
     c2_sub1.assert_called_with(2)
     self.assertEqual(c1_sub1.call_count, 1)
     self.assertEqual(c1_sub2.call_count, 1)
     self.assertEqual(c2_sub1.call_count, 1)
     #unsubscribe to c2
     c2_sub1_subs.stop()
     self.assertEqual(p.active, True)
     #send message to c2
     p.send(3, "c2")
     c1_sub1.assert_called_with(1)
     c1_sub2.assert_called_with(1)
     c2_sub1.assert_called_with(2)
     self.assertEqual(c1_sub1.call_count, 1)
     self.assertEqual(c1_sub2.call_count, 1)
     self.assertEqual(c2_sub1.call_count, 1)
     #unsubscribe to c1_sub2
     c1_sub2_subs.stop()
     self.assertEqual(p.active, True)
     #send message to c1
     p.send(4, "c1")
     c1_sub1.assert_called_with(4)
     c1_sub2.assert_called_with(1)
     c2_sub1.assert_called_with(2)
     self.assertEqual(c1_sub1.call_count, 2)
     self.assertEqual(c1_sub2.call_count, 1)
     self.assertEqual(c2_sub1.call_count, 1)
     #unsubscribe to c1_sub1
     c1_sub1_subs.stop()
     self.assertEqual(p.active, False)
     #send message to c1
     p.send(5, "c1")
     c1_sub1.assert_called_with(4)
     c1_sub2.assert_called_with(1)
     c2_sub1.assert_called_with(2)
     self.assertEqual(c1_sub1.call_count, 2)
     self.assertEqual(c1_sub2.call_count, 1)
     self.assertEqual(c2_sub1.call_count, 1)
     self.assertEqual(p.active, False)
Exemple #50
0
 def test_callback(self):
     callback = MagicMock()
     message = 'a'
     cuckoo = Cuckoo(callback=callback)
     cuckoo(message)
     callback.assert_called_with(message)
Exemple #51
0
def test_should_call_hash_with_correct_values(mock_hashpw: MagicMock,
                                              sut: BcryptAdapter):
    value = "any_value"
    sut.hash(value)
    mock_hashpw.assert_called_with(value.encode("utf-8"), SALT)
Exemple #52
0
 def test_all_channels_send(self):
     c1_sub = MagicMock()
     c2_sub = MagicMock()
     all_sub = MagicMock()
     p = MultitopicPublisher()
     #subscribe
     c1_sub_subs = p.subscribe(c1_sub, "c1")
     c2_sub_subs = p.subscribe(c2_sub, "c2")
     all_sub_subs = p.subscribe(all_sub, MultitopicPublisher.ALL_TOPICS)
     #send message to ALL_TOPICS
     p.send(1,MultitopicPublisher.ALL_TOPICS)
     c1_sub.assert_called_with(1)
     c2_sub.assert_called_with(1)
     all_sub.assert_called_with(1)
     self.assertEqual(c1_sub.call_count, 1)
     self.assertEqual(c2_sub.call_count, 1)
     self.assertEqual(all_sub.call_count, 1)
     #send message to ALL_TOPICS
     p.send(2, MultitopicPublisher.ALL_TOPICS)
     c1_sub.assert_called_with(2)
     c2_sub.assert_called_with(2)
     all_sub.assert_called_with(2)
     self.assertEqual(c1_sub.call_count, 2)
     self.assertEqual(c2_sub.call_count, 2)
     self.assertEqual(all_sub.call_count, 2)
def test_opsgenie_notification_per_entity(monkeypatch):
    post = MagicMock()
    monkeypatch.setattr('requests.post', post)

    alert = {
        'changed': True,
        'is_alert': True,
        'entity': {
            'id': 'e-1'
        },
        'worker': 'worker-1',
        'time': datetime.now(),
        'alert_def': {
            'name': 'Alert',
            'team': 'team-1',
            'responsible_team': 'zmon',
            'id': 123,
            'priority': 3,
            'tags': ['tag-1']
        },
    }

    NotifyOpsgenie._config = {
        'notifications.opsgenie.apikey': API_KEY,
        'zmon.host': 'https://zmon.example.org/'
    }

    r = NotifyOpsgenie.notify(alert,
                              message=MESSAGE,
                              per_entity=True,
                              teams='team-1')

    data = {
        'alias': 'ZMON-123-e-1',
        'message': '[zmon] - {}'.format(MESSAGE),
        'description': '',
        'source': 'worker-1',
        'note': 'https://zmon.example.org/#/alert-details/123',
        'entity': 'e-1',
        'details': {
            'worker': alert['worker'],
            'id': alert['alert_def']['id'],
            'name': alert['alert_def']['name'],
            'team': alert['alert_def']['team'],
            'responsible_team': alert['alert_def']['responsible_team'],
            'entity': alert['entity']['id'],
            'infrastructure_account': 'UNKNOWN',
        },
        'priority': 'P3',
        'tags': ['tag-1'],
        'teams': [{
            'name': 'team-1'
        }],
    }

    assert r == 0

    post.assert_called_with(URL_CREATE,
                            data=json.dumps(data,
                                            cls=JsonDataEncoder,
                                            sort_keys=True),
                            headers=HEADERS,
                            timeout=5,
                            params={})
def test_should_call_load_accout_by_email_correct_value(
        mock_load_by_email: MagicMock, sut: DbAuthentication):
    sut.auth(
        AuthenticationModel(email="*****@*****.**",
                            password="******"))
    mock_load_by_email.assert_called_with("*****@*****.**")
def test_should_call_hash_compare_correct_values(mock_compare: MagicMock,
                                                 sut: DbAuthentication):
    authentication = AuthenticationModel(email="*****@*****.**",
                                         password="******")
    sut.auth(authentication)
    mock_compare.assert_called_with("valid_password", "hashed_password")
 def test_bootstrap(self):
     mock = MagicMock()
     with patch('omnimax.sdk.base_sdk.execute_file', mock):
         sdk = omnimax.sdk.BaseSDK('ruby')
         sdk.bootstrap()
     mock.assert_called_with(self.sdk_dir + '/bootstrap.sh', wrapper='bash', cwd=self.sdk_dir)
class TestRosControlAdapter(unittest.TestCase):
    def select_mock(self, *args, **kwargs):
        mock = {
            '/gazebo/get_physics_properties': self.__get_physics,
            '/gazebo/get_world_properties': self.__get_world,
            '/gazebo/set_physics_properties': self.__set_physics,
            '/gazebo/pause_physics': self.__pause_physics,
            '/gazebo/unpause_physics': self.__unpause_physics,
            '/gazebo/reset_sim': self.__reset_sim,
            '/gazebo/end_world': self.__end_world,
            # These are due to the GazeboHelper
            '/gazebo/spawn_sdf_entity': self.__spawn_sdf_entity,
            '/gazebo/set_model_state': self.__set_model_state,
            '/gazebo/delete_model': self.__delete_model,
            '/gazebo/delete_light': self.__delete_light,
            '/gazebo/delete_lights': self.__delete_lights,
            '/gazebo/get_lights_name': self.__get_lights_name,
            '/gazebo/wait_for_rendering': self.__wait_for_rendering
        }[args[0]]

        for key, value in kwargs.items():
            setattr(mock, key, value)

        return mock

    @patch(
        'hbp_nrp_cle.robotsim.RosControlAdapter.AsynchonousRospyServiceProxy')
    @patch(
        'hbp_nrp_cle.robotsim.RosCommunicationAdapter.rospy.wait_for_service')
    @patch('hbp_nrp_cle.robotsim.RosCommunicationAdapter.rospy.ServiceProxy')
    def setUp(self, rospy_proxy, rospy_wfs, async_proxy_mock):
        self.__advance_simulation = MagicMock()
        self.__get_physics = MagicMock()
        self.__get_world = MagicMock()
        self.__set_physics = MagicMock()
        self.__pause_physics = MagicMock()
        self.__unpause_physics = MagicMock()
        self.__reset_sim = MagicMock()
        self.__end_world = MagicMock()
        # These are due to GazeboHelper
        self.__spawn_sdf_entity = MagicMock()
        self.__set_model_state = MagicMock()
        self.__delete_light = MagicMock()
        self.__delete_model = MagicMock()
        self.__delete_lights = MagicMock()
        self.__get_lights_name = MagicMock()
        self.__wait_for_rendering = MagicMock()

        async_proxy_mock.return_value = self.__advance_simulation

        rospy_proxy.side_effect = self.select_mock

        self._rca = RosControlAdapter()
        self._rca.initialize()

    @patch(
        'hbp_nrp_cle.robotsim.RosControlAdapter.AsynchonousRospyServiceProxy')
    @patch(
        'hbp_nrp_cle.robotsim.RosCommunicationAdapter.rospy.wait_for_service')
    @patch('hbp_nrp_cle.robotsim.RosCommunicationAdapter.rospy.ServiceProxy')
    def test_initialize(self, rospy_proxy, rospy_wfs, async_proxy_mock):

        self.__pause_physics = MagicMock()
        self.__get_physics = MagicMock()
        physics_mock = MagicMock(pause=False, time_step=1.0)
        physics_mock.pause = False
        physics_mock.time_step = 1.0
        self.__get_physics.return_value = physics_mock

        rospy_proxy.side_effect = self.select_mock

        with LogCapture('hbp_nrp_cle.robotsim.RosControlAdapter') as l:
            rca = RosControlAdapter()
            self.assertFalse(self.__pause_physics.called)
            rca.initialize()
            self.assertTrue(self.__pause_physics.called)
            self.assertEqual(rca.time_step, 1.0)

            l.check(('hbp_nrp_cle.robotsim.RosControlAdapter', 'INFO',
                     'Robot control adapter initialized'))

    def test_time_step(self):
        with LogCapture(
                'hbp_nrp_cle.robotsim.RosControlAdapter') as logcapture:
            self.assertEquals(self.__get_physics.call_count, 1)
            self.__set_physics.return_value = True

            self.assertTrue(self._rca.set_time_step(0.01))
            self.assertEquals(self._rca.time_step, 0.01)

            self.__set_physics.return_value = False
            self.assertFalse(self._rca.set_time_step(42))
            self.assertEquals(self._rca.time_step, 0.01)
            logcapture.check(
                ('hbp_nrp_cle.robotsim.RosControlAdapter', 'INFO',
                 'new time step = 0.010000'),
                ('hbp_nrp_cle.robotsim.RosControlAdapter', 'WARNING',
                 'impossible to set the new time step'))

            self.assertEquals(self.__get_physics.call_count, 3)

    def test_is_paused(self):
        self.__get_physics.return_value.pause = True
        self.assertTrue(self._rca.is_paused)

        self.__get_physics.return_value.pause = False
        self.assertFalse(self._rca.is_paused)

    def test_is_alive(self):
        self.__get_world.return_value.success = True
        self.assertTrue(self._rca.is_alive)

        self.__get_world.return_value.success = False
        self.assertFalse(self._rca.is_alive)

    def test_run_step_logging(self):
        with LogCapture(
                'hbp_nrp_cle.robotsim.RosControlAdapter') as logcapture:
            self.__set_physics.return_value = True
            self._rca.set_time_step(0.01)
            with self.assertRaises(ValueError):
                self._rca.run_step(0.0001)
            logcapture.check(
                ('hbp_nrp_cle.robotsim.RosControlAdapter', 'INFO',
                 'new time step = 0.010000'),
                ('hbp_nrp_cle.robotsim.RosControlAdapter', 'ERROR',
                 'dt is not multiple of the physics time step'))

    def test_run_step(self):
        future_mock = MagicMock()
        self.__advance_simulation.return_value = future_mock
        future_mock.result.return_value = 100

        self._rca.set_time_step(0.01)

        result = self._rca.run_step(0.01)
        self.__advance_simulation.assert_called_with(1.0)

        self.assertEqual(result, 100)

    def test_run_step_async(self):
        future_mock = MagicMock()
        self.__advance_simulation.return_value = future_mock
        self._rca.set_time_step(0.01)
        result = self._rca.run_step_async(0.01)
        self.assertEqual(result, future_mock)
        self.__advance_simulation.assert_called_with(1.0)

    def test_reset(self):
        with LogCapture(
                'hbp_nrp_cle.robotsim.RosControlAdapter') as logcapture:
            self.__set_physics.return_value = True
            self._rca.set_time_step(0.01)
            self._rca.run_step(0.05)
            self._rca.reset()
            logcapture.check(('hbp_nrp_cle.robotsim.RosControlAdapter', 'INFO',
                              'new time step = 0.010000'),
                             ('hbp_nrp_cle.robotsim.RosControlAdapter',
                              'DEBUG', 'Advancing simulation'),
                             ('hbp_nrp_cle.robotsim.RosControlAdapter', 'INFO',
                              'Resetting the world simulation'))

    def test_reset_world(self):
        rca_module_name = 'hbp_nrp_cle.robotsim.RosControlAdapter'
        user_notifications_module_name = 'hbp_nrp_cle.user_notifications'
        robots = {}
        robots["robot"] = "robot"
        self._rca.set_robots(robots)
        with LogCapture(rca_module_name) as logcapture:
            with LogCapture(
                    user_notifications_module_name) as logcapture_user_notif:
                # mock world (which is loaded during simulation startup)
                mock_sdf = '<sdf/>'
                world_models_sdf = {
                    'model1': {
                        'model_sdf': mock_sdf,
                        'model_state_sdf': mock_sdf
                    },
                    'model2': {
                        'model_sdf': mock_sdf,
                        'model_state_sdf': mock_sdf
                    }
                }
                world_lights_sdf = {"light1": mock_sdf, "light2": mock_sdf}

                # mock current world status
                mock_world_properties = GetWorldProperties()
                mock_world_properties.model_names = [
                    "model1", "model2", "robot"
                ]

                mock_world_lights = GetLightsName()
                mock_world_lights.light_names = ["light1", "light2", "sun"]

                # mock ros services
                self._rca.gazebo_helper.get_lights_name_proxy = Mock(
                    return_value=mock_world_lights)
                self._rca._RosControlAdapter__get_world_properties = Mock(
                    return_value=mock_world_properties)
                # delete services
                self._rca.gazebo_helper.delete_light_proxy = Mock(
                    return_value=True)
                self._rca.gazebo_helper.delete_model_proxy = Mock(
                    return_value=True)

                # spawn sdf service
                self._rca.gazebo_helper.spawn_sdf_entity_proxy = Mock(
                    return_value=True)

                # call the method under test
                self._rca.reset_world(world_models_sdf, world_lights_sdf)

                # check deletion
                lights_to_delete_and_respawn = ["light1", "light2"]
                models_to_delete_and_respawn = ["model1", "model2"]

                # LIGHTS
                for light in lights_to_delete_and_respawn:
                    self._rca.gazebo_helper.delete_light_proxy.assert_any_call(
                        light)

                # MODELS
                self.assertTrue(
                    False in map(
                        lambda c: 'robot' in c[0], self._rca.gazebo_helper.
                        delete_model_proxy.call_args_list),
                    'The robot must not be deleted from the scene')

                for model in models_to_delete_and_respawn:
                    self._rca.gazebo_helper.delete_model_proxy.assert_any_call(
                        model)

                # check reLoading
                self.assertFalse(
                    False in map(
                        lambda c: c[0][0] in models_to_delete_and_respawn +
                        lights_to_delete_and_respawn, self._rca.gazebo_helper.
                        spawn_sdf_entity_proxy.call_args_list),
                    'Some entity has not been re-spawned')

                # check log
                logcapture.check(
                    (rca_module_name, 'DEBUG', 'Resetting the Environment'),
                    (rca_module_name, 'DEBUG',
                     "active_model_set: set(['model2', 'model1'])"),
                    (rca_module_name, 'DEBUG',
                     "original_model_set: frozenset(['model2', 'model1'])"),
                    (rca_module_name, 'DEBUG',
                     "active_lights_set: set(['light2', 'light1'])"),
                    (rca_module_name, 'DEBUG',
                     "original_lights_set: frozenset(['light2', 'light1'])"))

                # check log on user notification logger
                logcapture_user_notif.check(
                    (user_notifications_module_name, 'INFO',
                     "Deleting: light2"), (user_notifications_module_name,
                                           'INFO', "Deleting: light1"),
                    (user_notifications_module_name, 'INFO',
                     "Deleting: model2"), (user_notifications_module_name,
                                           'INFO', "Deleting: model1"),
                    (user_notifications_module_name, 'INFO',
                     "Loading: light2"), (user_notifications_module_name,
                                          'INFO', "Loading: light1"),
                    (user_notifications_module_name, 'INFO',
                     "Loading: model2"), (user_notifications_module_name,
                                          'INFO', "Loading: model1"))

    def test_shutdown(self):
        with LogCapture(
                'hbp_nrp_cle.robotsim.RosControlAdapter') as logcapture:
            self._rca.shutdown()
            logcapture.check(('hbp_nrp_cle.robotsim.RosControlAdapter', 'INFO',
                              'Shutting down the world simulation'),
                             ('hbp_nrp_cle.robotsim.RosControlAdapter', 'INFO',
                              'Robot control adapter stopped'))
def test_perform_get_mds_when_not_managed_via_omci(mds_task):
    test = MagicMock()
    mds_task.deferred.addCallback(test)
    mds_task.perform_get_mds()
    test.assert_called_with(mds_task.omci_agent.get_device().mib_synchronizer.mib_data_sync)
Exemple #59
0
 def test_callback_with_multiple_kwargs(self):
     callback = MagicMock()
     cuckoo = Cuckoo(callback=callback)
     cuckoo(a=1, b=2)
     callback.assert_called_with(a=1, b=2)
Exemple #60
0
def test_scalyr_logs(monkeypatch, fx_logs):
    kwargs, res, exp = fx_logs

    read_key = '123'

    post = MagicMock()
    post.return_value.json.return_value = res

    monkeypatch.setattr('requests.post', post)

    def expected_query():
        query = get_query('log', None, read_key, **kwargs)

        query.pop('function', None)
        query.pop('buckets', None)
        query['maxCount'] = kwargs.get('max_count', 100)

        if 'continuation_token' in kwargs:
            query['continuationToken'] = kwargs['continuation_token']
        if 'columns' in kwargs:
            query['columns'] = ','.join(kwargs['columns']) if type(
                kwargs['columns']) is list else kwargs['columns']

        return query

    scalyr = ScalyrWrapper(read_key)
    try:
        result = scalyr.logs(**kwargs)
        assert result == exp

        query = expected_query()

        post.assert_called_with(scalyr._ScalyrWrapper__query_url,
                                json=query,
                                headers={
                                    'Content-Type': 'application/json',
                                    'errorStatus': 'always200'
                                })

    except CheckError as e:
        if not res:
            assert '{}'.format(
                e) == 'query "{}" is not allowed to be blank'.format(
                    kwargs['query'])
            post.assert_not_called
        elif 'message' in res:
            assert '{}'.format(e) == res['message']
            query = expected_query()
            post.assert_called_with(scalyr._ScalyrWrapper__query_url,
                                    json=query,
                                    headers={
                                        'Content-Type': 'application/json',
                                        'errorStatus': 'always200'
                                    })
        elif not exp:
            assert '{}'.format(
                e) == 'No logs or error message was returned from scalyr'
            query = expected_query()
            post.assert_called_with(scalyr._ScalyrWrapper__query_url,
                                    json=query,
                                    headers={
                                        'Content-Type': 'application/json',
                                        'errorStatus': 'always200'
                                    })
        else:
            raise