Exemple #1
0
    def test_updates_pid_values_on_control(self, pid_mock_class):
        pid_mock = pid_mock_class.return_value

        tunings_mock = PropertyMock()
        type(pid_mock).tunings = tunings_mock
        tunings_mock.return_value = (1, 2, 3)

        components_mock = PropertyMock()
        type(pid_mock).components = components_mock
        components_mock.return_value = (4, 3, 2)

        controller = Controller(self.config, 5, 0.5, self.heater, self.cooler,
                                self.limiter, self.current_temp,
                                self.fridge_temp, [])

        self.config.get.side_effect = lambda key: {
            "p": 4,
            "i": 5,
            "d": 6,
            "target": 23,
            "heating_limit": 40,
            "limit_window": 5
        }.get(key)

        pid_mock.return_value = 5

        controller.control()

        tunings_mock.assert_called_with((4, 5, 6))
Exemple #2
0
    def test_switch_heating_and_cooling_without_threshold(
            self, pid_mock_class, control, h_current, h_switch, c_current,
            c_switch):
        pid_mock = pid_mock_class.return_value

        self.heater.get.return_value = h_current
        self.cooler.get.return_value = c_current

        pid_mock.return_value = control

        tunings_mock = PropertyMock()
        type(pid_mock).tunings = tunings_mock
        tunings_mock.return_value = (1, 2, 3)

        components_mock = PropertyMock()
        type(pid_mock).components = components_mock
        components_mock.return_value = (4, 3, 2)

        controller = Controller(self.config, 5, 0, self.heater, self.cooler,
                                self.limiter, self.current_temp,
                                self.fridge_temp, [])

        controller.control()

        if h_switch is None:
            self.heater.set.assert_not_called()
        else:
            self.heater.set.assert_called_with(h_switch)

        if c_switch is None:
            self.cooler.set.assert_not_called()
        else:
            self.cooler.set.assert_called_with(c_switch)
Exemple #3
0
 def test_step_visibility(self, _step: PropertyMock):
     """Should return values from the internal _step object."""
     _step.return_value = MagicMock(is_visible=True)
     es = exposed.ExposedStep()
     self.assertTrue(es.visible)
     es.visible = False
     self.assertFalse(es.visible)
Exemple #4
0
 def test_step_visibility(self, _step: PropertyMock):
     """Should return values from the internal _step object."""
     _step.return_value = MagicMock(is_visible=True)
     es = exposed.ExposedStep()
     self.assertTrue(es.visible)
     es.visible = False
     self.assertFalse(es.visible)
Exemple #5
0
    def test_check_reorgs(self, current_block_number_mock: PropertyMock,
                          get_block_mock: MagicMock):
        reorg_service = ReorgServiceProvider()

        block = block_child
        block_number = block["number"]

        def get_block_fn(number: int, full_transactions=False):
            if number == block_number:
                return block_child

            if number == block_number + 1:
                return block_parent

        get_block_mock.side_effect = get_block_fn
        current_block_number = block_number + 100
        current_block_number_mock.return_value = current_block_number

        ethereum_block: EthereumBlock = EthereumBlockFactory(
            number=block_number, confirmed=False)
        self.assertEqual(reorg_service.check_reorgs(), block_number)

        ethereum_block.block_hash = block["hash"]
        ethereum_block.save(update_fields=["block_hash"])
        self.assertIsNone(reorg_service.check_reorgs())
        ethereum_block.refresh_from_db()
        self.assertTrue(ethereum_block.confirmed)
    def testRunner(self):
        # Verify BatchTrial without runner will fail
        with self.assertRaises(ValueError):
            self.batch.run()

        # Verify mark running without runner will fail
        with self.assertRaises(ValueError):
            self.batch.mark_running()

        self.batch.runner = SyntheticRunner()
        self.batch.run()
        self.assertEqual(self.batch.deployed_name, "test_0")
        self.assertNotEqual(len(self.batch.run_metadata.keys()), 0)
        self.assertEqual(self.batch.status, TrialStatus.RUNNING)

        # Verify setting runner on experiment but not BatchTrial
        # Also mock staging_required to be false
        staging_mock = PropertyMock()
        with patch.object(SyntheticRunner, "staging_required", staging_mock):
            mock_runner = SyntheticRunner()
            staging_mock.return_value = True

            self.experiment.runner = mock_runner
            b2 = self.experiment.new_batch_trial()
            b2.run()
            self.assertEqual(b2.deployed_name, "test_1")
            self.assertEqual(b2.status, TrialStatus.STAGED)
Exemple #7
0
    def test_get_installed_local(self):
        """Test get_installed_local used to find
        installed napps in local machine"""
        # Mock kytos.json path
        mock_path = Mock()

        def glob_side_effect(args):
            """Path.glob to mock finding paths with kytos.json file."""
            self.assertEqual(args, "*/*/kytos.json")

            mock_path1 = Mock()
            mock_path1.parts = ['kytos', 'of_core', 'kytos.json']
            return [mock_path1]

        mock_path.glob = glob_side_effect

        mock_prop_installed = PropertyMock()
        with patch.object(NAppsManager, '_installed', mock_prop_installed):
            mock_prop_installed.return_value = mock_path

            get_return = self.napps_manager.get_installed_local()

            self.assertEqual(get_return[0][0], 'kytos')
            self.assertEqual(get_return[0][1], 'of_core')
            self.assertEqual(mock_prop_installed.call_count, 1)
Exemple #8
0
async def test_get_commits_to_cherry_pick_merge(
    commits: mock.PropertyMock,
    context_getter: conftest.ContextGetterFixture,
) -> None:
    c1 = github_types.CachedGitHubBranchCommit({
        "sha":
        github_types.SHAType("c1f"),
        "parents": [],
        "commit_message":
        "foobar",
        "commit_verification_verified":
        False,
    })
    c2 = github_types.CachedGitHubBranchCommit({
        "sha":
        github_types.SHAType("c2"),
        "parents": [c1["sha"]],
        "commit_message":
        "foobar",
        "commit_verification_verified":
        False,
    })

    async def fake_commits(
    ) -> typing.List[github_types.CachedGitHubBranchCommit]:
        return [c1, c2]

    commits.return_value = fake_commits()

    client = mock.Mock()
    client.auth.get_access_token.return_value = "<token>"

    ctxt = await context_getter(github_types.GitHubPullRequestNumber(1))
    ctxt.repository.installation.client = client

    base_branch = github_types.CachedGitHubBranchCommit({
        "sha":
        github_types.SHAType("base_branch"),
        "parents": [],
        "commit_message":
        "foobar",
        "commit_verification_verified":
        False,
    })
    merge_commit = github_types.CachedGitHubBranchCommit({
        "sha":
        github_types.SHAType("merge_commit"),
        "parents": [base_branch["sha"], c2["sha"]],
        "commit_message":
        "foobar",
        "commit_verification_verified":
        False,
    })

    assert await duplicate_pull._get_commits_to_cherrypick(ctxt,
                                                           merge_commit) == [
                                                               c1,
                                                               c2,
                                                           ]
Exemple #9
0
 def test_step_stop_aborted(self, _step: PropertyMock):
     """
     Should abort stopping and not raise an error when no internal step
     is available to stop.
     """
     _step.return_value = None
     es = exposed.ExposedStep()
     es.stop()
def interpolation_method(mocker, method):
    # This uses the pytest-mock package in order to provide a fixture that will
    # mock the global variable in the image module that determines if OpenCV
    # should be used or not. Useful for running the unit tests with and without
    # opencv
    interp = PropertyMock()
    interp.return_value = method
    mocker.patch("menpo.image.base.cv2_perspective_interpolation", new_callable=interp)
Exemple #11
0
 def test_step_stop_aborted(self, _step: PropertyMock):
     """
     Should abort stopping and not raise an error when no internal step
     is available to stop.
     """
     _step.return_value = None
     es = exposed.ExposedStep()
     es.stop()
Exemple #12
0
 def test_write_to_console_fail(self, _step: PropertyMock):
     """
     Should raise a ValueError when there is no current step to operate
     upon by the write function call.
     """
     _step.return_value = None
     step = exposed.ExposedStep()
     with self.assertRaises(ValueError):
         step.write_to_console('hello')
Exemple #13
0
 def test_write_to_console_fail(self, _step: PropertyMock):
     """
     Should raise a ValueError when there is no current step to operate
     upon by the write function call.
     """
     _step.return_value = None
     step = exposed.ExposedStep()
     with self.assertRaises(ValueError):
         step.write_to_console('hello')
Exemple #14
0
 def test_step_properties(self, _step: PropertyMock):
     """Should return values from the internal _step object."""
     now = datetime.utcnow()
     _step.return_value = MagicMock(start_time=now,
                                    end_time=now,
                                    elapsed_time=0)
     es = exposed.ExposedStep()
     self.assertEqual(now, es.start_time)
     self.assertEqual(now, es.end_time)
     self.assertEqual(0, es.elapsed_time)
Exemple #15
0
    def test_only_updates_pid_values_if_changed(self, pid_mock_class):
        pid_mock = pid_mock_class.return_value

        tunings_mock = PropertyMock()
        type(pid_mock).tunings = tunings_mock
        tunings_mock.return_value = (1, 2, 3)

        components_mock = PropertyMock()
        type(pid_mock).components = components_mock
        components_mock.return_value = (4, 3, 2)

        controller = Controller(self.config, 5, 0.5, self.heater, self.cooler,
                                self.limiter, self.current_temp,
                                self.fridge_temp, [])

        pid_mock.return_value = 5

        controller.control()

        tunings_mock.assert_called_once_with()  # the getter, not the setter
Exemple #16
0
    def test_publishes_to_listeners(self, pid_mock_class):
        pid_mock = pid_mock_class.return_value

        tunings_mock = PropertyMock()
        type(pid_mock).tunings = tunings_mock
        tunings_mock.return_value = (1, 2, 3)

        components_mock = PropertyMock()
        type(pid_mock).components = components_mock
        components_mock.return_value = (4, 3, 2)

        controller = Controller(self.config, 5, 0.5, self.heater, self.cooler,
                                self.limiter, self.current_temp,
                                self.fridge_temp, [self.listener])

        pid_mock.return_value = .4

        controller.control()

        self.listener.handle_controller.assert_called_with(4, 3, 2, .4)
Exemple #17
0
    def testBatchLifecycle(self):
        staging_mock = PropertyMock()
        with patch.object(SyntheticRunner, "staging_required", staging_mock):
            mock_runner = SyntheticRunner()
            staging_mock.return_value = True
            self.batch.runner = mock_runner
            self.batch.run()
            self.assertEqual(self.batch.status, TrialStatus.STAGED)
            self.assertIsNotNone(self.batch.time_staged)
            self.assertTrue(self.batch.status.is_deployed)
            self.assertFalse(self.batch.status.expecting_data)

            # Cannot change arms or runner once run
            with self.assertRaises(ValueError):
                self.batch.add_arms_and_weights(arms=self.arms,
                                                weights=self.weights)

            with self.assertRaises(ValueError):
                self.batch.runner = None

            # Cannot run batch that was already run
            with self.assertRaises(ValueError):
                self.batch.run()

            self.batch.mark_running()
            self.assertEqual(self.batch.status, TrialStatus.RUNNING)
            self.assertIsNotNone(self.batch.time_run_started)
            self.assertTrue(self.batch.status.expecting_data)

            self.batch.complete()
            # Cannot complete that which is already completed
            with self.assertRaises(ValueError):
                self.batch.complete()

            # Verify trial is completed
            self.assertEqual(self.batch.status, TrialStatus.COMPLETED)
            self.assertIsNotNone(self.batch.time_completed)
            self.assertTrue(self.batch.status.is_terminal)

            # Cannot change status after BatchTrial is completed
            with self.assertRaises(ValueError):
                self.batch.mark_staged()

            with self.assertRaises(ValueError):
                self.batch.mark_completed()

            with self.assertRaises(ValueError):
                self.batch.mark_running()

            with self.assertRaises(ValueError):
                self.batch.mark_abandoned()

            with self.assertRaises(ValueError):
                self.batch.mark_failed()
Exemple #18
0
def test_alt_return():
    filer_image = mock.Mock(name='FilerImage', spec=True)

    original_filename = PropertyMock(name='original_filename')
    type(filer_image).original_filename = original_filename
    original_filename.return_value = 'foo'

    result = FilerImageAdapter().alt(filer_image)

    assert result == 'foo'
    # It's 2 because once for checking if the attribute exists and once for returning it
    assert original_filename.call_count == 2
Exemple #19
0
def test_alt_empty_return():
    """ Douplex doesn't support mocked properties on free doubles so we need to use the standard mock library """
    filer_image = mock.Mock(name='FilerImage', spec=True)

    original_filename = PropertyMock(name='original_filename')
    type(filer_image).original_filename = original_filename
    original_filename.return_value = None

    name = PropertyMock(name='name')
    type(filer_image).name = name
    name.return_value = None

    default_alt_text = PropertyMock(name='default_alt_text')
    type(filer_image).default_alt_text = default_alt_text
    default_alt_text.return_value = None

    result = FilerImageAdapter().alt(filer_image)

    assert result == ''
    assert original_filename.call_count == 1
    assert name.call_count == 1
    assert default_alt_text.call_count == 1
Exemple #20
0
 def test_get_internal_project_fail(self, sleep: MagicMock,
                                    time_time: MagicMock,
                                    internal_project: PropertyMock):
     """
     Should fail to get internal project and return None after
     eventually timing out.
     """
     project = exposed.ExposedProject()
     time_time.side_effect = range(20)
     internal_project.return_value = None
     result = project.get_internal_project()
     self.assertIsNone(result)
     self.assertEqual(10, sleep.call_count)
Exemple #21
0
 def test_step_properties(self, _step: PropertyMock):
     """Should return values from the internal _step object."""
     now = datetime.utcnow()
     _step.return_value = MagicMock(
         start_time=now,
         end_time=now,
         elapsed_time=0,
         is_visible=True
     )
     es = exposed.ExposedStep()
     self.assertEqual(now, es.start_time)
     self.assertEqual(now, es.end_time)
     self.assertEqual(0, es.elapsed_time)
Exemple #22
0
    def test_dont_switch_heating_on_if_under_heating_threshold(
            self, pid_mock_class):
        pid_mock = pid_mock_class.return_value

        self.heater.get.return_value = False

        pid_mock.return_value = 0.4

        tunings_mock = PropertyMock()
        type(pid_mock).tunings = tunings_mock
        tunings_mock.return_value = (1, 2, 3)

        components_mock = PropertyMock()
        type(pid_mock).components = components_mock
        components_mock.return_value = (4, 3, 2)

        controller = Controller(self.config, 5, 0.5, self.heater, self.cooler,
                                self.limiter, self.current_temp,
                                self.fridge_temp, [])

        controller.control()

        self.heater.set.assert_not_called()
Exemple #23
0
    def test_feeds_current_temperature_to_pid(self, pid_mock_class):
        pid_mock = pid_mock_class.return_value

        current_temp = Mock()
        self.current_temp.get_average.return_value = current_temp

        tunings_mock = PropertyMock()
        type(pid_mock).tunings = tunings_mock
        tunings_mock.return_value = (1, 2, 3)

        components_mock = PropertyMock()
        type(pid_mock).components = components_mock
        components_mock.return_value = (4, 3, 2)

        controller = Controller(self.config, 5, 0.5, self.heater, self.cooler,
                                self.limiter, self.current_temp,
                                self.fridge_temp, [])

        pid_mock.return_value = 5

        controller.control()

        pid_mock.assert_called_with(current_temp)
Exemple #24
0
 def test_run_calls_submit_task_for_each_sensor(self, psubmit_task, prun):
     sensors_collection = [[MagicMock() for _ in range(num)]
                           for num in range(4)]
     mocked_sensors = PropertyMock()
     type(self.simple_instance).sensors = mocked_sensors
     for sensors in sensors_collection:
         expected_calls = [
             call(sensor, self.simple_instance._sensors_queue)
             for sensor in sensors
         ]
         mocked_sensors.return_value = sensors
         #self.simple_instance.sensors = sensors
         self.simple_instance.run()
         psubmit_task.assert_has_calls(expected_calls, any_order=True)
Exemple #25
0
    def test_switch_off_heating_if_over_heating_limit(self, pid_mock_class,
                                                      fridge_temperature,
                                                      cb_current, cb_switch,
                                                      h_current, h_switch):
        pid_mock = pid_mock_class.return_value

        self.fridge_temp.get.return_value = fridge_temperature

        self.heater.get.return_value = h_current
        self.cooler.get.return_value = False
        self.limiter.get.return_value = cb_current

        pid_mock.return_value = 3  # would trigger the heater

        tunings_mock = PropertyMock()
        type(pid_mock).tunings = tunings_mock
        tunings_mock.return_value = (1, 2, 3)

        components_mock = PropertyMock()
        type(pid_mock).components = components_mock
        components_mock.return_value = (4, 3, 2)

        controller = Controller(self.config, 5, 0, self.heater, self.cooler,
                                self.limiter, self.current_temp,
                                self.fridge_temp, [])

        controller.control()

        if cb_switch is None:
            self.limiter.set.assert_not_called()
        else:
            self.limiter.set.assert_called_with(cb_switch)

        if h_switch is None:
            self.heater.set.assert_not_called()
        else:
            self.heater.set.assert_called_with(h_switch)
Exemple #26
0
def test_compare_generated_with_data(mock_permalink_as_str: PropertyMock,
                                     layout_description: LayoutDescription,
                                     echoes_pickup_database: PickupDatabase):
    debug._DEBUG_LEVEL = 0
    status_update = MagicMock()
    mock_permalink_as_str.return_value = "fixed-seed!"

    generated_description = generator.generate_list(
        layout_description.permalink, status_update=status_update, timeout=None)

    indices: List[int] = [None] * echoes_pickup_database.total_pickup_count
    for index, pickup in generated_description.patches.pickup_assignment.items():
        indices[index.index] = echoes_pickup_database.original_index(pickup).index
    print(indices)

    assert generated_description.without_solver_path == layout_description
Exemple #27
0
 def test_get_internal_project_fail(
         self,
         sleep: MagicMock,
         time_time: MagicMock,
         internal_project: PropertyMock
 ):
     """
     Should fail to get internal project and return None after
     eventually timing out.
     """
     project = exposed.ExposedProject()
     time_time.side_effect = range(20)
     internal_project.return_value = None
     result = project.get_internal_project()
     self.assertIsNone(result)
     self.assertEqual(10, sleep.call_count)
Exemple #28
0
    def test_render_to_console(self, _step: PropertyMock):
        """
        Should render to the console using a write_source function
        call on the internal step report's stdout_interceptor.
        """
        message = '   {{ a }} is not {{ b }}.'

        _step_mock = MagicMock()
        write_source = MagicMock()
        _step_mock.report.stdout_interceptor.write_source = write_source
        _step.return_value = _step_mock
        step = exposed.ExposedStep()
        step.render_to_console(message, a=7, b='happy')

        args, kwargs = write_source.call_args
        self.assertEqual('7 is not happy.', args[0])
Exemple #29
0
async def test_queue_cleanup(mocker, conduit_mock, sparky, app):
    mocker.patch(TESTED + '.CLEANUP_INTERVAL', timedelta(milliseconds=10))
    fresh_mock = PropertyMock(return_value=True)
    type(commander.TimestampedQueue()).fresh = fresh_mock

    await sparky.startup(app)
    await sparky._on_data(conduit_mock, '05 00 |00 00 00')

    # Still fresh
    await asyncio.sleep(0.1)
    assert len(sparky._requests) == 1

    # Assert stale was removed
    fresh_mock.return_value = False
    await asyncio.sleep(0.1)
    assert len(sparky._requests) == 0
Exemple #30
0
    def test_write_to_console(self, _step: PropertyMock):
        """
        Should write to the console using a write_source function
        call on the internal step report's stdout_interceptor.
        """
        trials = [2, True, None, 'This is a test', b'hello']

        for message in trials:
            _step_mock = MagicMock()
            write_source = MagicMock()
            _step_mock.report.stdout_interceptor.write_source = write_source
            _step.return_value = _step_mock
            step = exposed.ExposedStep()
            step.write_to_console(message)

            args, kwargs = write_source.call_args
            self.assertEqual('{}'.format(message), args[0])
Exemple #31
0
    def test_write_to_console(self, _step: PropertyMock):
        """
        Should write to the console using a write_source function
        call on the internal step report's stdout_interceptor.
        """
        trials = [2, True, None, 'This is a test', b'hello']

        for message in trials:
            _step_mock = MagicMock()
            write_source = MagicMock()
            _step_mock.report.stdout_interceptor.write_source = write_source
            _step.return_value = _step_mock
            step = exposed.ExposedStep()
            step.write_to_console(message)

            args, kwargs = write_source.call_args
            self.assertEqual('{}'.format(message), args[0])
Exemple #32
0
def test_compare_generated_with_data(mock_permalink_as_str: PropertyMock,
                                     layout_description: LayoutDescription):
    debug.set_level(0)
    status_update = MagicMock()
    mock_permalink_as_str.return_value = "fixed-seed!"

    generated_description = generator.generate_description(
        layout_description.permalink,
        status_update=status_update,
        validate_after_generation=True,
        timeout=None)

    # indices: List[int] = [None] * echoes_pickup_database.total_pickup_count
    # for index, pickup in generated_description.patches.pickup_assignment.items():
    #     indices[index.index] = echoes_pickup_database.original_index(pickup).index
    # print(indices)

    assert generated_description.without_solver_path == layout_description
def test_output_name_for(mock_shareable_hash: PropertyMock, empty_patches):
    # Setup
    permalink_mock = MagicMock(spec=Permalink(
        seed_number=15000,
        spoiler=True,
        preset=None,
    ))
    layout = LayoutDescription(version="0.15.0",
                               permalink=permalink_mock,
                               patches=empty_patches,
                               solver_path=())
    mock_shareable_hash.return_value = "PermalinkStr"

    # Run
    result = simplified_patcher._output_name_for(layout)

    # Assert
    assert result == "Echoes Randomizer - PermalinkStr"
Exemple #34
0
    def test_check_reorgs(self, current_block_number_mock: PropertyMock,
                          get_block_mock: MagicMock):
        reorg_service = ReorgServiceProvider()

        block = block_result[0]
        block_number = block['number']
        get_block_mock.return_value = block
        current_block_number = block_number + 100
        current_block_number_mock.return_value = current_block_number

        ethereum_block: EthereumBlock = EthereumBlockFactory(
            number=block_number, confirmed=False)
        self.assertEqual(reorg_service.check_reorgs(), block_number)

        ethereum_block.block_hash = block['hash']
        ethereum_block.save(update_fields=['block_hash'])
        self.assertIsNone(reorg_service.check_reorgs())
        ethereum_block.refresh_from_db()
        self.assertTrue(ethereum_block.confirmed)
Exemple #35
0
    def test_datpiff_player_response(self):
        # test DatpiffPlayer response return correct request response
        # when dpp_link is set correctly
        with patch.object(mediasetup, "Album", autospec=True) as dp:
            link = PropertyMock(return_value=dp_real_link)
            dp.dpp_link = link
            dp.datpiff_player_response = PropertyMock(
                return_value=mocked_session.text)
            self.assertEqual(dummy_text,
                             dp.datpiff_player_response.return_value)

        with patch.object(mediasetup.Album,
                          "dpp_link",
                          new_callable=PropertyMock) as link:
            # test DatpiffPlayer link is return correct value
            link.return_value = dp_real_link
            dp = self.dp
            dp.dpp_link = link
            self.assertEqual(dp_real_link, self.dp.dpp_link)
Exemple #36
0
    def test_is_service_synced(self, current_block_number_mock: PropertyMock):
        current_block_number_mock.return_value = 500
        self.assertTrue(self.index_service.is_service_synced())
        reorg_blocks = self.index_service.eth_reorg_blocks

        safe_master_copy = SafeMasterCopyFactory(
            tx_block_number=current_block_number_mock.return_value -
            reorg_blocks - 1)
        self.assertFalse(self.index_service.is_service_synced())
        safe_master_copy.tx_block_number = safe_master_copy.tx_block_number + 1
        safe_master_copy.save(update_fields=["tx_block_number"])
        self.assertTrue(self.index_service.is_service_synced())

        safe_contract = SafeContractFactory(
            erc20_block_number=current_block_number_mock.return_value -
            reorg_blocks - 1)
        self.assertFalse(self.index_service.is_service_synced())
        safe_contract.erc20_block_number = safe_contract.erc20_block_number + 1
        safe_contract.save(update_fields=["erc20_block_number"])
        self.assertTrue(self.index_service.is_service_synced())

        # Less than 10% of contracts out of sync will be alright (by default). Try with 1 of 20 out of sync
        SafeContract.objects.all().delete()
        SafeContractFactory(
            erc20_block_number=current_block_number_mock.return_value -
            reorg_blocks - 1)
        for _ in range(19):
            safe_contract_synced = SafeContractFactory(
                erc20_block_number=current_block_number_mock.return_value -
                reorg_blocks)
        self.assertTrue(self.index_service.is_service_synced())

        # Set one more of sync, so 2 of 20 out of sync
        safe_contract_synced.erc20_block_number -= 1
        safe_contract_synced.save(update_fields=["erc20_block_number"])
        self.assertFalse(self.index_service.is_service_synced())
Exemple #37
0
async def test_get_commits_to_cherry_pick_rebase(
    commits: mock.PropertyMock,
    redis_cache: utils.RedisCache,
) -> None:
    gh_owner = github_types.GitHubAccount({
        "login":
        github_types.GitHubLogin("user"),
        "id":
        github_types.GitHubAccountIdType(0),
        "type":
        "User",
        "avatar_url":
        "",
    })

    gh_repo = github_types.GitHubRepository({
        "full_name":
        "user/name",
        "name":
        github_types.GitHubRepositoryName("name"),
        "private":
        False,
        "id":
        github_types.GitHubRepositoryIdType(0),
        "owner":
        gh_owner,
        "archived":
        False,
        "url":
        "",
        "html_url":
        "",
        "default_branch":
        github_types.GitHubRefType("ref"),
    })

    c1 = github_types.GitHubBranchCommit({
        "sha": github_types.SHAType("c1f"),
        "parents": [],
        "commit": {
            "message": "foobar"
        },
    })
    c2 = github_types.GitHubBranchCommit({
        "sha": github_types.SHAType("c2"),
        "parents": [c1],
        "commit": {
            "message": "foobar"
        },
    })
    commits.return_value = [c1, c2]

    client = mock.Mock()
    client.auth.get_access_token.return_value = "<token>"
    client.items.side_effect = fake_get_github_pulls_from_sha

    installation = context.Installation(
        github_types.GitHubAccountIdType(123),
        github_types.GitHubLogin("user"),
        subscription.Subscription(redis_cache, 0, False, "", frozenset()),
        client,
        redis_cache,
    )
    repository = context.Repository(installation, gh_repo)
    ctxt = await context.Context.create(
        repository,
        {
            "labels": [],
            "draft": False,
            "merge_commit_sha": github_types.SHAType(""),
            "title": "",
            "commits": 1,
            "rebaseable": False,
            "maintainer_can_modify": False,
            "id": github_types.GitHubPullRequestId(0),
            "number": github_types.GitHubPullRequestNumber(6),
            "merged": True,
            "state": "closed",
            "html_url": "<html_url>",
            "changed_files": 1,
            "base": {
                "label": "",
                "sha": github_types.SHAType("sha"),
                "user": {
                    "login": github_types.GitHubLogin("user"),
                    "id": github_types.GitHubAccountIdType(0),
                    "type": "User",
                    "avatar_url": "",
                },
                "ref": github_types.GitHubRefType("ref"),
                "repo": {
                    "full_name": "user/ref",
                    "name": github_types.GitHubRepositoryName("name"),
                    "private": False,
                    "id": github_types.GitHubRepositoryIdType(0),
                    "owner": {
                        "login": github_types.GitHubLogin("user"),
                        "id": github_types.GitHubAccountIdType(0),
                        "type": "User",
                        "avatar_url": "",
                    },
                    "archived": False,
                    "url": "",
                    "html_url": "",
                    "default_branch": github_types.GitHubRefType(""),
                },
            },
            "head": {
                "label": "",
                "sha": github_types.SHAType("sha"),
                "ref": github_types.GitHubRefType("fork"),
                "user": {
                    "login": github_types.GitHubLogin("user"),
                    "id": github_types.GitHubAccountIdType(0),
                    "type": "User",
                    "avatar_url": "",
                },
                "repo": {
                    "full_name": "fork/other",
                    "name": github_types.GitHubRepositoryName("other"),
                    "private": False,
                    "archived": False,
                    "url": "",
                    "html_url": "",
                    "default_branch": github_types.GitHubRefType(""),
                    "id": github_types.GitHubRepositoryIdType(0),
                    "owner": {
                        "login": github_types.GitHubLogin("user"),
                        "id": github_types.GitHubAccountIdType(0),
                        "type": "User",
                        "avatar_url": "",
                    },
                },
            },
            "user": {
                "login": github_types.GitHubLogin("user"),
                "id": github_types.GitHubAccountIdType(0),
                "type": "User",
                "avatar_url": "",
            },
            "merged_by": None,
            "merged_at": None,
            "mergeable_state": "clean",
        },
    )

    base_branch = github_types.GitHubBranchCommitParent(
        {"sha": github_types.SHAType("base_branch")})
    rebased_c1 = github_types.GitHubBranchCommit({
        "sha":
        github_types.SHAType("rebased_c1"),
        "parents": [base_branch],
        "commit": {
            "message": "hello c1"
        },
    })
    rebased_c2 = github_types.GitHubBranchCommit({
        "sha":
        github_types.SHAType("rebased_c2"),
        "parents": [rebased_c1],
        "commit": {
            "message": "hello c2"
        },
    })

    async def fake_get_github_commit_from_sha(url, api_version=None):
        if url.endswith("/commits/rebased_c1"):
            return rebased_c1
        if url.endswith("/commits/rebased_c2"):
            return rebased_c2
        raise RuntimeError(f"Unknown URL {url}")

    client.item.side_effect = fake_get_github_commit_from_sha

    assert await duplicate_pull._get_commits_to_cherrypick(ctxt,
                                                           rebased_c2) == [
                                                               rebased_c1,
                                                               rebased_c2,
                                                           ]