def test_normal_send(self):
        """ Test normal messages sending """
        socket_mock = Mock()
        logger_mock = Mock()

        output_wrapper = Output(socket_mock, logger_mock)
        output_wrapper.info('info(%s)', 'arg1')
        output_wrapper.debug('debug(%s)', 'arg2')
        output_wrapper.error('error(%s)', 'arg3')
        output_wrapper.error('no_args_error(%s)')
        output_wrapper.log('log(%s)', 'arg4')
        output_wrapper.say('say(%s)', 'arg5')
        output_wrapper.say('no_args_say(%s)')

        socket_mock.assert_has_calls([
            call.send(b'{"text": "info(arg1)"}\x00'),
            call.send(b'{"error": "error(arg3)"}\x00'),
            call.send(b'{"error": "no_args_error(%s)"}\x00'),
            call.send(b'{"text": "log(arg4)"}\x00'),
            call.send(b'{"text": "say(arg5)"}\x00'),
            call.send(b'{"text": "no_args_say(%s)"}\x00'),
        ])
        logger_mock.assert_has_calls([
            call.info('info(%s)', 'arg1'),
            call.debug('debug(%s)', 'arg2'),
            call.error('error(%s)', 'arg3'),
            call.error('no_args_error(%s)'),
            call.info('log(%s)', 'arg4'),
            call.info('say(%s)', 'arg5'),
            call.info('no_args_say(%s)'),
        ])
Пример #2
0
    def test_sourceData_CurrentSeason(self):
        with Database(self.dbName, SQLite3Impl()) as db, \
                db.transaction() as t:
            seasonMap = db.select(Source_Season_Map(98))[0]
            seasonMap.setActive(1)
            db.upsert(seasonMap)
            seasonMap = Source_Season_Map(98, 'season name TD2', \
                    'source_season_map moniker TD2', \
                    'source_season_map data_url TD2', 1)
            db.upsert(seasonMap)

        sourceData(self.mock_Logger, 'source name TD', True)

        self.mock_readCSVFileAsDict.assert_any_call( \
                'source_season_map data_url TD2')

        calls = (
                    call.info(
                        'Downloading data from source: source name TD'),
                    call.debug('Opening database: ./db/test.db'),
                    call.debug(
                        "source : Keys {'id': 98} : Values {'name': " \
                        "'source name TD', 'fixtures_url': 'source " \
                        "fixtures_url TD', 'url': 'source url TD'}"),
                    call.debug(
                        "[source_season_map : Keys {'source_id': 98, "\
                        "'season': 'season name TD2'} : Values {'moniker'" \
                        ": 'source_season_map moniker TD2', 'data_url': " \
                        "'source_season_map data_url TD2', 'active': 1}]"),
                    call.debug(
                        "[source_league_map : Keys {'source_id': 98, " \
                        "'league': 'league mnemonic TD'} : Values " \
                        "{'moniker': 'source_league_map moniker TD'}]"),
                    call.debug(
                        "[team : Keys {'name': 'team name TD'} : Values " \
                        "{'league': 'league mnemonic TD'}, " \
                        "team : Keys {'name': 'team name TD2'} : Values " \
                        "{'league': 'league mnemonic TD2'}]"),
                    call.info('Downloading...source_season_map data_url TD2'),
                )
        self.mock_Logger.assert_has_calls(calls)

        with Database(self.dbName, SQLite3Impl()) as db:
            ht = db.select(Team('Coventry', 'league mnemonic TD'))[0]
            at = db.select(Team('Cardiff', 'league mnemonic TD'))[0]
            match = db.select(Match(201010191))[0]

            self.assertTrue(ht and at and match)
            self.assertEquals(match.getDate(), '2010-10-19')
            self.assertEquals(match.getLeague(), 'league mnemonic TD')
            self.assertEquals(match.getHome_Team(), 'Coventry')
            self.assertEquals(match.getAway_Team(), 'Cardiff')
            self.assertEquals(match.getResult(), 'A')
            self.assertEquals(match.getBest_Odds_H(), 3.12)
            self.assertEquals(match.getBest_Odds_D(), 3.4)
            self.assertEquals(match.getBest_Odds_A(), 2.4)
            self.assertEquals(match.getHome_Goals(), 1)
            self.assertEquals(match.getAway_Goals(), 2)
            self.assertEquals(match.getHome_Lp(), None)
            self.assertEquals(match.getAway_Lp(), None)
Пример #3
0
    def test_malfomed_request(self, setup, dependency_mocks):
        post_data = {
            "malformed": "penguin",
            "connections": "sarah, michael and jonny"
        }
        with dependency_mocks as mocks:
            mocks["credential_offer_accept"].return_value = None

            response = self.client.post(
                path=f"/{self.path}",
                data=post_data,
                format="json",
            )

            returns_status_code_http_200_ok(response)

            mocks["credential_offer_accept"].assert_not_called()
            mocks["credential_offer_create"].assert_not_called()
            mocks["LOGGER"].assert_has_calls([
                call.info(
                    "webhook: received: topic: 'issue_credential' - state: 'None' - message: {'malformed': 'penguin', 'connections': 'sarah, michael and jonny'}"
                ),
                call.info(
                    "webhook: topic: issue_credential and state: None is invalid"
                ),
            ])
 def test_load_me_data(self):
     with patch('multiecho.combination.logger') as log_mock:
         multiecho.combination.load_me_data("", TEs=None)
         calls = [
             call.info('Loading: []'),
             call.info('Echotimes: []')
         ]
         log_mock.assert_has_calls(calls)
    def test_unequal_images(self, mocker):
        ref_image_path = non_existent_path('test_unequal_images.png')

        class ImgDiffer:
            def get_diff(self, image, ref_image):
                return QImage(image)

            def report(self):
                return "report"

        # generate reference:
        widget = QLabel('test')
        assert check_widget_snapshot(widget, __file__, ref_image_path.stem)

        # pretend label has changed, but less than tolerance (get_diff() returns None):
        widget = QLabel('test2')
        widget.setObjectName('label')
        mock_log = Mock()
        files_before = set(Path(__file__).parent.glob('*'))
        mock_timer = mocker.patch.object(pyqt_test_sandals,
                                         'perf_counter',
                                         side_effect=[0, 123])
        assert not check_widget_snapshot(widget,
                                         __file__,
                                         ref_image_path.stem,
                                         img_differ=ImgDiffer(),
                                         log=mock_log)
        assert mock_log.method_calls == [
            call.info('Widget %s vs ref %s in %s (%.2f sec):',
                      'label', ref_image_path.name,
                      ref_image_path.parent.resolve(), 123),
            call.info('    report'),
            call.warn(
                '    Snapshot has changed beyond tolerances, saving actual and diff images to folder %s:',
                ref_image_path.parent.resolve()),
            call.warn('    Saving actual image to %s',
                      'test_unequal_images_actual.png'),
            call.warn('    Saving diff image (White - |ref - widget|) to %s',
                      'test_unequal_images_diff.png')
        ]
        check_log_format(
            mock_log.info.call_args_list[0],
            'Widget label vs ref test_unequal_images.png in ***\\tests (123.00 sec):'
        )
        # confirm that no results files were create:
        files_after = set(Path(__file__).parent.glob('*'))
        ref_image_path.unlink()
        assert files_after.issuperset(files_before)
        actual_img_path = Path('test_unequal_images_actual.png')
        diff_img_path = Path('test_unequal_images_diff.png')
        assert files_after.difference(files_before) == set(
            [actual_img_path.resolve(),
             diff_img_path.resolve()])
        actual_img_path.unlink()
        diff_img_path.unlink()
Пример #6
0
 def test_populate_zone_id_cache(self):
     """
     Test that populating the zone ID cache results in the expected API calls.
     """
     self.api.get_zone_id('test.com')  # Implicitly calls _populate_zone_id_cache()
     self.assertEqual(len(self.api.client.domain.mock_calls), 4)
     self.api.client.domain.assert_has_calls([
         call.list('TEST_GANDI_API_KEY'),
         call.info('TEST_GANDI_API_KEY', 'test.com'),
         call.info('TEST_GANDI_API_KEY', 'example.com'),
         call.info('TEST_GANDI_API_KEY', 'opencraft.co.uk'),
     ], any_order=True)
Пример #7
0
 def test_populate_zone_id_cache(self):
     """
     Test that populating the zone ID cache results in the expected API calls.
     """
     self.api.get_zone_id('test.com')  # Implicitly calls _populate_zone_id_cache()
     self.assertEqual(len(self.api.client.domain.mock_calls), 4)
     self.api.client.domain.assert_has_calls([
         call.list('TEST_GANDI_API_KEY'),
         call.info('TEST_GANDI_API_KEY', 'test.com'),
         call.info('TEST_GANDI_API_KEY', 'example.com'),
         call.info('TEST_GANDI_API_KEY', 'opencraft.co.uk'),
     ], any_order=True)
Пример #8
0
    def test_run(self, logger):
        """Test the basic run behavior: logging and managing the alarm time"""
        # Prepare test
        self.alarm.is_alive = MagicMock(side_effect=[True, False])
        self.alarm.manage_time = MagicMock()
        # Run test
        self.alarm.run()

        # Evaluate test
        calls = [call.info(MSG_INFO_START), call.info(MSG_INFO_STOP)]
        logger.assert_has_calls(calls)
        self.alarm.manage_time.assert_called_once()
Пример #9
0
 def test_success_all_options(self):
     m_sts = Mock()
     m_sts.assume_role.return_value = {
         'Credentials': {
             'AccessKeyId': 'AKID',
             'SecretAccessKey': 'SKey',
             'SessionToken': 'SToken',
             'Expiration': datetime(2018, 10, 8, 12, 13, 14)
         },
         'AssumedRoleUser': {
             'AssumedRoleId': 'ARid',
             'Arn': 'UserARN'
         },
         'PackedPolicySize': 123
     }
     m_sess = Mock()
     m_sess.client.return_value = m_sts
     type(self.m_conf).assume_role = PropertyMock(
         return_value={
             'role_arn': 'assumeRoleArn',
             'external_id': 'eID',
             'duration_seconds': '1234'
         })
     with patch('%s.logger' % pbm, autospec=True) as mock_logger:
         with patch.dict(os.environ, {}, clear=True):
             with patch('%s.boto3.session.Session' % pbm) as mock_boto:
                 mock_boto.return_value = m_sess
                 assume_role(self.m_conf)
                 assert os.environ == {
                     'AWS_ACCESS_KEY_ID': 'AKID',
                     'AWS_SECRET_ACCESS_KEY': 'SKey',
                     'AWS_SESSION_TOKEN': 'SToken'
                 }
     expected_args = {
         'RoleArn': 'assumeRoleArn',
         'RoleSessionName': 'manheim-c7n-tools_aName',
         'ExternalId': 'eID',
         'DurationSeconds': 1234
     }
     assert mock_boto.mock_calls == [
         call(region_name='us-east-1'),
         call().client('sts'),
         call().client().assume_role(**expected_args)
     ]
     assert mock_logger.mock_calls == [
         call.info('Calling sts:AssumeRole via boto3 with arguments: %s',
                   expected_args),
         call.info(
             'Exported AssumeRole credentials; AccessKeyId %s expires at '
             '%s; AssumedRoleUser ARN: %s', 'AKID',
             datetime(2018, 10, 8, 12, 13, 14), 'UserARN')
     ]
Пример #10
0
    def test_invalid_connection_id(self, setup, dependency_mocks):
        post_data = {
            "state": "response",
            "connection_id": "random test connection id"
        }
        with dependency_mocks as mocks:
            mocks["connection_invitation_accept"].return_value = None

            response = self.client.post(
                path=f"/{self.path}",
                data=post_data,
                format="json",
            )
            returns_status_code_http_200_ok(response)
            mocks["connection_invitation_accept"].assert_called_once_with(
                "random test connection id")
            mocks["credential_offer_create"].assert_not_called()
            mocks["LOGGER"].assert_has_calls([
                call.info(
                    "webhook: received: topic: 'connections' - state: 'response' - message: {'state': 'response', 'connection_id': 'random test connection id'}"
                ),
                call.error(
                    "webhook: connection_invitation_accept: connection_id: random test connection id not found"
                ),
            ])
    def test_skill_load(self):
        with patch(self.mock_package + 'time') as time_mock:
            time_mock.return_value = 100
            with patch(self.mock_package + 'SettingsMetaUploader'):
                self.loader.load()

        self.assertTrue(self.loader.load_attempted)
        self.assertTrue(self.loader.loaded)
        self.assertEqual(100, self.loader.last_loaded)
        self.assertListEqual(['mycroft.skills.loaded'],
                             self.message_bus_mock.message_types)
        log_messages = [
            call.info('ATTEMPTING TO LOAD SKILL: test_skill'),
            call.info('Skill test_skill loaded successfully')
        ]
        self.assertListEqual(log_messages, self.log_mock.method_calls)
Пример #12
0
    def test_show_after_1_indent_2_dedent(self):
        common.indent()
        common.dedent()
        common.dedent()
        common.show("|\n", log=self.log, color=None)

        assert [call.info("|")] == self.log.mock_calls
Пример #13
0
    def test_execute(self, ZubMock):
        # mocks
        logger: Logger = Mock()
        helper: OdsUpdaterHelper = Mock()
        zub: ZipUpdaterBuilder = Mock()

        ZubMock.return_value = zub

        # play
        directive = UpdateCommand(logger, helper, Path("source.ods"),
                                  Path("dest.ods"), "3.1", None)
        execute = directive.execute(10)

        # verify
        self.assertEqual((10, Path("dest.ods")), execute)
        self.assertEqual(
            [call.info("Update. Generating '%s' (source: %s) for Python '%s'",
                       Path('dest.ods'), Path('source.ods'), '3.1')],
            logger.mock_calls)
        self.assertEqual(
            [call.get_destination_scripts(), call.get_assets()],
            helper.mock_calls)
        self.assertEqual(
            call.build().update(Path('source.ods'), Path('dest.ods')),
            zub.mock_calls[-1])
Пример #14
0
 def test_list_accounts(self):
     with patch('%s.logger' % pbm, autospec=True) as mock_logger:
         with patch('%s.open' % pbm,
                    mock_open(read_data='foo'),
                    create=True) as m_open:
             with patch('%s.yaml.load' % pbm, autospec=True) as mock_load:
                 with patch('%s.ManheimConfig' % pbm,
                            autospec=True) as mock_conf:
                     mock_load.return_value = [{
                         'account_name': 'a1',
                         'account_id': '1111',
                         'foo': 'bar',
                         'baz': 2,
                         'regions': ['us-east-1']
                     }, {
                         'account_name': 'a2',
                         'account_id': 2222,
                         'foo': 'bar1',
                         'baz': 4,
                         'regions': ['us-east-2']
                     }]
                     res = ManheimConfig.list_accounts('/tmp/conf.yml')
     assert res == {'a1': '1111', 'a2': '2222'}
     assert mock_logger.mock_calls == [
         call.info('Loading config from: %s', '/tmp/conf.yml')
     ]
     assert m_open.mock_calls == [
         call('/tmp/conf.yml', 'r'),
         call().__enter__(),
         call().read(),
         call().__exit__(None, None, None)
     ]
     assert mock_load.mock_calls == [call('foo', Loader=yaml.SafeLoader)]
     assert mock_conf.mock_calls == []
Пример #15
0
    def test_show_after_indent(self):
        common.indent()
        common.show("|\n", log=self.log)

        assert [
            call.info("|"),
        ] == self.log.mock_calls
Пример #16
0
    def test(self, Zupdater):
        # mocks
        logger: Logger = Mock()
        helper: OdsUpdaterHelper = Mock()
        t1: TempScript = Mock()
        t2: TempScript = Mock()
        sources: Sources = Mock()
        destinations: Destinations = Mock()

        dest_path = Path("dest.ods")
        inc_path = Path("inc/debug.ods")
        python_version = "3.1"
        helper.get_temp_scripts.side_effect = [[t1, t2]]
        destinations.dest_ods_file.parent.joinpath.return_value = dest_path
        sources.inc_dir.joinpath.return_value = inc_path
        d = DebugCommand(logger, helper, sources, destinations, python_version)

        d.execute([])

        self.assertEqual([
            call.info("Debug or init. Generating '%s' for Python '%s'",
                      Path('dest.ods'), '3.1')
        ], logger.mock_calls)
        print(Zupdater.mock_calls)
        self.assertEqual(
            call().update(Path('inc/debug.ods'), Path('dest.ods')),
            Zupdater.mock_calls[-1])
Пример #17
0
    def test_show_after_indent(self):
        common.indent()
        common.show("|\n", log=self.log)

        assert [
            call.info("|"),
        ] == self.log.mock_calls
Пример #18
0
 def test_download_eval_file(self):
     WHOIS.get_registrar_certification_list.return_value = self._get_registrar_certs(
     )
     FILE_MANAGER.info.return_value = FileInfo(
         id=2,
         name='test.html',
         path='2015/12/9/1',
         mimetype='text/html',
         filetype=6,
         crdate='2015-12-09 16:16:28.598757',
         size=5)
     content = "<html><body>The content.</body></html>"
     FILE_MANAGER.load.return_value.download.return_value = content
     response = self.client.get(
         reverse("webwhois:download_evaluation_file",
                 kwargs={"handle": "REG-MOJEID"}))
     self.assertEqual(response.content, content.encode())
     self.assertEqual(response['Content-Type'], 'text/html')
     self.assertEqual(response['Content-Disposition'],
                      'attachment; filename="test.html"')
     self.assertEqual(WHOIS.mock_calls,
                      [call.get_registrar_certification_list()])
     self.assertEqual(FILE_MANAGER.mock_calls, [
         call.info(2),
         call.load(2),
         call.load().download(5),
         call.load().finalize_download()
     ])
    def test_skill_load_blacklisted(self):
        """Skill should not be loaded if it is blacklisted"""
        self.loader.config['skills']['blacklisted_skills'] = ['test_skill']
        with patch(self.mock_package + 'SettingsMetaUploader'):
            self.loader.load()

        self.assertTrue(self.loader.load_attempted)
        self.assertFalse(self.loader.loaded)
        self.assertListEqual(['mycroft.skills.loading_failure'],
                             self.message_bus_mock.message_types)
        log_messages = [
            call.info('ATTEMPTING TO LOAD SKILL: test_skill'),
            call.info(
                'Skill test_skill is blacklisted - it will not be loaded'),
            call.error('Skill test_skill failed to load')
        ]
        self.assertListEqual(log_messages, self.log_mock.method_calls)
Пример #20
0
 def test_calls_credential_workflow(self, setup, dependency_mocks):
     with dependency_mocks as mocks:
         response = self.client.post(
             path=f"/{self.path}",
             data=self.message,
             format="json",
         )
         returns_status_code_http_200_ok(response)
         mocks["credential_offer_create"].assert_not_called()
         mocks["credential_offer_accept"].assert_called_once_with("1")
         mocks["LOGGER"].assert_has_calls([
             call.info(
                 "webhook: received: topic: 'issue_credential' - state: 'credential_issued' - message: {'state': 'credential_issued', 'connection_id': '1'}"
             ),
             call.info(
                 "webhook: processing: credential accepted - connection_id: 1"
             ),
         ])
Пример #21
0
 def test_invalid_state(self, setup, dependency_mocks):
     post_data = {"state": "random test state", "connection_id": "1"}
     with dependency_mocks as mocks:
         response = self.client.post(
             path=f"/{self.path}",
             data=post_data,
             format="json",
         )
         returns_status_code_http_200_ok(response)
         mocks["connection_invitation_accept"].assert_not_called()
         mocks["credential_offer_create"].assert_not_called()
         mocks["LOGGER"].assert_has_calls([
             call.info(
                 "webhook: received: topic: 'connections' - state: 'random test state' - message: {'state': 'random test state', 'connection_id': '1'}"
             ),
             call.info(
                 "webhook: topic: connections and state: random test state is invalid"
             ),
         ])
Пример #22
0
def test_log_params_return(mock_getLogger):
    mock_log = MagicMock(autospec=True)
    mock_getLogger.return_value = mock_log
    assert 1 == log_params_return()(lambda x: x)(1)
    assert [call('schmetterling.core.tests.test_log')] == mock_getLogger.mock_calls
    assert [call.info(
        '%s: %s %s\n=> %s',
        '<lambda>',
        (1,),
        {},
        1,
    )] == mock_log.mock_calls
Пример #23
0
 def test_calls_credential_workflow(self, setup, dependency_mocks):
     with dependency_mocks as mocks:
         mocks[
             "connection_invitation_accept"].return_value = "mock connection invitation"
         response = self.client.post(
             path=f"/{self.path}",
             data=self.post_data,
             format="json",
         )
         returns_status_code_http_200_ok(response)
         mocks["connection_invitation_accept"].assert_called_once_with("1")
         mocks["credential_offer_create"].assert_called_once_with(
             "1", "mock connection invitation")
         mocks["LOGGER"].assert_has_calls([
             call.info(
                 "webhook: received: topic: 'connections' - state: 'response' - message: {'state': 'response', 'connection_id': '1'}"
             ),
             call.info(
                 "webhook: processing: connection accepted - connection_id: 1"
             ),
         ], )
def test_logs_start_and_exit_of_the_service():
    forwarder = MagicMock()
    forwarder.is_mailbox_empty.return_value = False
    exit_event = MagicMock()
    exit_event.is_set.return_value = True

    forwarder_service = MeshToS3ForwarderService(forwarder=forwarder,
                                                 poll_frequency_sec=0,
                                                 exit_event=exit_event)

    logger = logging.getLogger("s3mesh.forwarder_service")
    with patch.object(logger, "info") as mock_info:
        forwarder_service.start()

    mock_info.assert_has_calls(
        [
            call.info("Started forwarder service"),
            call.info("Exiting forwarder service")
        ],
        any_order=False,
    )
Пример #25
0
async def test_writer_worker():
    w_queue, rst_queue = asyncio.Queue(), asyncio.Queue()
    w_queue.put_nowait([])

    main.logging = Mock()
    await main.writer_worker(0, w_queue, rst_queue, True)

    main.logging.assert_has_calls([
        call.debug('writer0: writing 0 results.'),
        call.info('writer0: wrote 0 results with status "OK".')
    ],
                                  any_order=True)
    def test_skill_reload(self):
        """Test reloading a skill that was modified."""
        self.loader.instance = Mock()
        self.loader.loaded = True
        self.loader.last_loaded = 0

        with patch(self.mock_package + 'time') as time_mock:
            time_mock.return_value = 100
            with patch(self.mock_package + 'SettingsMetaUploader'):
                self.loader.reload()

        self.assertTrue(self.loader.load_attempted)
        self.assertTrue(self.loader.loaded)
        self.assertEqual(100, self.loader.last_loaded)
        self.assertListEqual(
            ['mycroft.skills.shutdown', 'mycroft.skills.loaded'],
            self.message_bus_mock.message_types)
        log_messages = [
            call.info('ATTEMPTING TO RELOAD SKILL: test_skill'),
            call.info('Skill test_skill shut down successfully'),
            call.info('Skill test_skill loaded successfully')
        ]
        self.assertListEqual(log_messages, self.log_mock.method_calls)
Пример #27
0
 def test_broken_config(self):
     cp = configparser.ConfigParser()
     cp['DEFAULT']['account_type'] = 'unknown_type'
     with open(self.accounts_dir + '/error_account.ini', 'w') as f:
         cp.write(f)
     error_conf = mbm.config.Global(self.conf_file, self.accounts_dir)
     error_conf.delete_account("error_account")
     self.assertListEqual(mbm.config.log.mock_calls,
                          [call.error("Could not instantiate account 'error"
                                      "_account': Unknown account type 'unk"
                                      "nown_type'"),
                           call.info("Deleted errornous account 'error_acco"
                                     "unt'")])
     mbm.config.log.mock_reset()
Пример #28
0
 def test_broken_config(self):
     cp = configparser.ConfigParser()
     cp['DEFAULT']['account_type'] = 'unknown_type'
     with open(self.accounts_dir + '/error_account.ini', 'w') as f:
         cp.write(f)
     error_conf = mbm.config.Global(self.conf_file, self.accounts_dir)
     error_conf.delete_account("error_account")
     self.assertListEqual(mbm.config.log.mock_calls, [
         call.error("Could not instantiate account 'error"
                    "_account': Unknown account type 'unk"
                    "nown_type'"),
         call.info("Deleted errornous account 'error_acco"
                   "unt'")
     ])
     mbm.config.log.mock_reset()
Пример #29
0
    def test_send_email(self):
        with patch('%s.logger' % pbm, autospec=True) as mock_logger:

            self.cls.send_email(sender='*****@*****.**',
                                recipient='*****@*****.**',
                                subject='foo',
                                body_text='body',
                                body_html='<html></html>',
                                attachments={'report.html': '<html></html>'})

            assert self.mock_boto.mock_calls == [
                call.send_raw_email(Destinations=['*****@*****.**'],
                                    RawMessage={'Data': ANY},
                                    Source='*****@*****.**')
            ]

            assert mock_logger.mock_calls == [call.info('Email sent!')]
Пример #30
0
    def test_analyseMatches(self):
        analyseMatches(self.mock_Logger, 1, 'league mnemonic TD')

        calls = (
                    call.info('Analysing matches for league <league ' \
                            'mnemonic TD> with algo <1>'),
                    call.debug('Opening database: ./db/test.db'),
                    call.debug('Last rating for match 99'),
                    call.debug('7 matches found to mark'),
                )
        self.mock_Logger.assert_has_calls(calls)

        with Database(self.dbName, SQLite3Impl()) as db:
            stats = db.select(Statistics())
            ratings = db.select(Rating())

            self.assertEquals(len(stats), 2)
            self.assertEquals(stats[0].getGeneration_Date(), \
                    str(datetime.now().date()))
            self.assertEquals(stats[0].getAlgo_Id(), 1)
            self.assertEquals(stats[0].getLeague(), 'league mnemonic TD')
            self.assertEquals(stats[0].getMark(), -3)
            self.assertEquals(stats[0].getMark_Freq(), 50.0)
            self.assertEquals(stats[0].getHome_Freq(), 100.0)
            self.assertEquals(stats[0].getAway_Freq(), 0.0)
            self.assertEquals(stats[0].getDraw_Freq(), 0.0)

            self.assertEquals(stats[1].getGeneration_Date(), \
                    str(datetime.now().date()))
            self.assertEquals(stats[1].getAlgo_Id(), 1)
            self.assertEquals(stats[1].getLeague(), 'league mnemonic TD')
            self.assertEquals(stats[1].getMark(), -2)
            self.assertEquals(stats[1].getMark_Freq(), 50.0)
            self.assertEquals(stats[1].getHome_Freq(), 100.0)
            self.assertEquals(stats[1].getAway_Freq(), 0.0)
            self.assertEquals(stats[1].getDraw_Freq(), 0.0)

            self.assertEquals(len(ratings), 2)
            self.assertEquals(ratings[0].getMatch_Oid(), 6)
            self.assertEquals(ratings[0].getAlgo_Id(), 1)
            self.assertEquals(ratings[0].getMark(), -3)

            self.assertEquals(ratings[1].getMatch_Oid(), 7)
            self.assertEquals(ratings[1].getAlgo_Id(), 1)
            self.assertEquals(ratings[1].getMark(), -2)
Пример #31
0
    def test_calling_tracker_with_payload_indicating_queued_informs_user(
            self, emissary_class_mock, *args, **mocks):
        emissary_mock = emissary_class_mock()

        factory = APIRequestFactory()
        request = factory.get(
            reverse('job_progress:tracker',
                    kwargs=dict(export_id=self.export.id)),
            data=dict(status='queued',
                      job='http://localhost:8901/api/conversion_job/1/'))

        views.tracker(request, export_id=str(self.export.id))
        assert_that(
            emissary_mock.mock_calls,
            contains_in_any_order(
                call.info(
                    'Export #{export_id} "Neverland" to Esri File Geodatabase has been queued.'
                    .format(export_id=self.export.id), ), ))
Пример #32
0
    def test_generate_and_send_email_enabled(self):
        with patch('%s.logger' % pbm, autospec=True) as mock_logger, \
            patch('%s.open' % pbm, mock_open(read_data='foo'),
                  create=True) as m_open:

            cloudmapper_filename = datetime.datetime.now().strftime(
                'cloudmapper_report_%Y-%m-%d.html')

            self.cls.generate_and_send_email()

            assert m_open.mock_calls == [
                call('/opt/manheim_cloudmapper/web/account-data/report.html',
                     'r'),
                call().__enter__(),
                call().read(),
                call().__exit__(None, None, None),
                call('/opt/manheim_cloudmapper/web/js/chart.js', 'r'),
                call().__enter__(),
                call().read(),
                call().__exit__(None, None, None),
                call('/opt/manheim_cloudmapper/web/js/report.js', 'r'),
                call().__enter__(),
                call().read(),
                call().__exit__(None, None, None)
            ]

            assert self.mock_ses.mock_calls == [
                call.send_email(
                    '*****@*****.**', 'AWS SES <*****@*****.**>',
                    '[cloudmapper foo] Cloudmapper audit findings',
                    'Please see the attached file for '
                    'cloudmapper results.', '<html><head></head><body><p>foo'
                    '</p></body></html>', {
                        cloudmapper_filename:
                        '<html><head></head><body><p>foo'
                        '</p></body></html>'
                    })
            ]

            assert mock_logger.mock_calls == [call.info("Sending SES Email.")]
Пример #33
0
 def test_from_file(self):
     m_conf = Mock()
     with patch('%s.logger' % pbm, autospec=True) as mock_logger:
         with patch('%s.open' % pbm,
                    mock_open(read_data='foo'),
                    create=True) as m_open:
             with patch('%s.yaml.load' % pbm, autospec=True) as mock_load:
                 with patch('%s.ManheimConfig' % pbm,
                            autospec=True) as mock_conf:
                     mock_conf.return_value = m_conf
                     mock_load.return_value = [{
                         'account_name': 'a1',
                         'foo': 'bar',
                         'baz': 2,
                         'regions': ['us-east-1']
                     }, {
                         'account_name': 'a2',
                         'foo': 'bar1',
                         'baz': 4,
                         'regions': ['us-east-2']
                     }]
                     res = ManheimConfig.from_file('/tmp/conf.yml', 'a2')
     assert res == m_conf
     assert mock_logger.mock_calls == [
         call.info('Loading config from: %s', '/tmp/conf.yml')
     ]
     assert m_open.mock_calls == [
         call('/tmp/conf.yml', 'r'),
         call().__enter__(),
         call().read(),
         call().__exit__(None, None, None)
     ]
     assert mock_load.mock_calls == [call('foo', Loader=yaml.SafeLoader)]
     assert mock_conf.mock_calls == [
         call(account_name='a2',
              foo='bar1',
              baz=4,
              regions=['us-east-2'],
              config_path='/tmp/conf.yml')
     ]
Пример #34
0
 def test_from_file_name_missing(self):
     m_conf = Mock()
     with patch('%s.logger' % pbm, autospec=True) as mock_logger:
         with patch('%s.open' % pbm,
                    mock_open(read_data='foo'),
                    create=True) as m_open:
             with patch('%s.yaml.load' % pbm, autospec=True) as mock_load:
                 with patch('%s.ManheimConfig' % pbm,
                            autospec=True) as mock_conf:
                     mock_conf.return_value = m_conf
                     mock_load.return_value = [{
                         'account_name': 'a1',
                         'foo': 'bar',
                         'baz': 2,
                         'regions': ['us-east-1']
                     }, {
                         'account_name': 'a2',
                         'foo': 'bar1',
                         'baz': 4,
                         'regions': ['us-east-2']
                     }]
                     with pytest.raises(RuntimeError) as exc:
                         ManheimConfig.from_file('/tmp/conf.yml', 'BAD')
     assert str(exc.value) == 'ERROR: No account with name "BAD"' \
                              ' in /tmp/conf.yml'
     assert mock_logger.mock_calls == [
         call.info('Loading config from: %s', '/tmp/conf.yml')
     ]
     assert m_open.mock_calls == [
         call('/tmp/conf.yml', 'r'),
         call().__enter__(),
         call().read(),
         call().__exit__(None, None, None)
     ]
     assert mock_load.mock_calls == [call('foo', Loader=yaml.SafeLoader)]
     assert mock_conf.mock_calls == []
Пример #35
0
    def test_show(self):
        common.show("Hello, world!", log=self.log)

        assert [
            call.info("Hello, world!"),
        ] == self.log.mock_calls