def test_change_xy_log(self):
        view_x_log_mock = PropertyMock()
        view_y_log_mock = PropertyMock()
        model_x_log_mock = PropertyMock(return_value=True)
        model_y_log_mock = PropertyMock(return_value=False)
        model_x_range_mock = PropertyMock(return_value=(1, 2))
        model_y_range_mock = PropertyMock(return_value=(3, 4))
        type(self.view).x_log = view_x_log_mock
        type(self.view).y_log = view_y_log_mock
        type(self.model).x_log = model_x_log_mock
        type(self.model).y_log = model_y_log_mock
        type(self.model).x_range = model_x_range_mock
        type(self.model).y_range = model_y_range_mock

        # model -> view
        self.presenter = CutPlotOptionsPresenter(self.view, self.model)
        view_x_log_mock.assert_called_once_with(True)
        view_y_log_mock.assert_called_once_with(False)

        # view -> model
        view_x_log_mock.return_value = False
        view_y_log_mock.return_value = True
        self.presenter._xy_config_modified('x_log')
        self.presenter._xy_config_modified('y_log')
        self.presenter.get_new_config()
        self.model.change_axis_scale.assert_called_once_with({'x_range': (1, 2), 'y_range': (3, 4), 'modified': True,
                                                              'x_log': False,    'y_log': True})
Пример #2
0
class TestSharedFIFOfileClassSpoolerThreadClass(unittest.TestCase):
    def setUp(self):
        reload(te.fifo)
        self.writing_end_conn, self.reading_end_conn = te.multiprocessing.Pipe(
        )
        self.mock_spool_callable = Mock()
        self.tmpfile_name_mock_property = \
                                  PropertyMock(return_value='dummy_tempfile_name')
        type(self.mock_spool_callable.return_value).name = \
                                                    self.tmpfile_name_mock_property
        self.spooler = te.fifo.SharedFIFOfile.SpoolerThread(
            self.reading_end_conn, self.mock_spool_callable, interval_len=0.01)

    def test_SpoolerThread(self):
        self.assertEqual(self.spooler.name,
                         'MainProcess--TmpfileSpoolerThread')
        self.assertEqual(len(threading.enumerate()), 1)
        self.spooler.start()
        self.assertEqual(len(threading.enumerate()), 2)
        self.assertFalse(self.writing_end_conn.poll())
        self.assertFalse(self.mock_spool_callable.called)
        self.assertFalse(self.tmpfile_name_mock_property.called)
        self.writing_end_conn.send(None)
        time.sleep(
            0.1)  # Things don't happen instantaneously in the other thread
        self.mock_spool_callable.assert_called_once_with()
        self.tmpfile_name_mock_property.assert_called_once_with()
        self.assertTrue(self.writing_end_conn.poll())
        self.assertEqual(self.writing_end_conn.recv(), 'dummy_tempfile_name')

    def tearDown(self):
        self.spooler.stop.set()
        self.spooler.join()
Пример #3
0
    def test_nb_convert_engine(self):
        with patch.object(engines, 'PapermillExecutePreprocessor') as pep_mock:
            # Mock log_output calls
            log_out_mock = PropertyMock()
            type(pep_mock.return_value).log_output = log_out_mock

            with patch.object(NotebookExecutionManager, 'save') as save_mock:
                nb = NBConvertEngine.execute_notebook(
                    self.nb,
                    'python',
                    output_path='foo.ipynb',
                    progress_bar=False,
                    log_output=True,
                    bar='baz',
                    start_timeout=30,
                    execution_timeout=1000,
                )

                self.assertEqual(nb, AnyMock(NotebookNode))
                self.assertNotEqual(self.nb, nb)

                pep_mock.assert_called_once()
                pep_mock.assert_called_once_with(timeout=1000,
                                                 startup_timeout=30,
                                                 kernel_name='python',
                                                 log=logger)
                log_out_mock.assert_called_once_with(True)
                pep_mock.return_value.preprocess.assert_called_once_with(
                    AnyMock(NotebookExecutionManager), {'bar': 'baz'})
                # Once for start and once for complete (cell not called by mock)
                self.assertEqual(save_mock.call_count, 2)
Пример #4
0
    def test_get_scheduler(self):
        """Tests successful execution of the get_scheduler command."""
        mock_options = self.setup_mock_options()
        mock_proxy = create_autospec(spec=SchedulerProxy, instance=True)
        mock_scheduler_client = create_autospec(spec=SchedulerClient,
                                                instance=True)
        mock_raw_url = PropertyMock(return_value="url")
        mock_proxy.scheduler_client.return_value = mock_scheduler_client
        type(mock_scheduler_client).raw_url = mock_raw_url

        with contextlib.nested(
                patch('twitter.common.app.get_options',
                      return_value=mock_options),
                patch('apache.aurora.admin.admin.make_admin_client',
                      return_value=create_autospec(spec=AuroraClientAPI)),
                patch('apache.aurora.admin.admin.CLUSTERS',
                      new=self.TEST_CLUSTERS),
        ) as (_, mock_make_admin_client, _):

            api = mock_make_admin_client.return_value
            type(api).scheduler_proxy = PropertyMock(return_value=mock_proxy)

            get_scheduler([self.TEST_CLUSTER])

            mock_raw_url.assert_called_once_with()
    def test_change_colorbar_config(self):
        view_colorbar_range_mock = PropertyMock()
        view_colorbar_log_mock = PropertyMock()
        type(self.view).colorbar_range = view_colorbar_range_mock
        type(self.view).colorbar_log = view_colorbar_log_mock

        model_colorbar_range_mock = PropertyMock(return_value=(1, 5))
        model_colorbar_log_mock = PropertyMock(return_value=False)
        type(self.model).colorbar_range = model_colorbar_range_mock
        type(self.model).colorbar_log = model_colorbar_log_mock

        # passed model -> view
        self.presenter = SlicePlotOptionsPresenter(self.view, self.model)

        model_colorbar_range_mock.assert_called_with()
        model_colorbar_log_mock.assert_called_with()
        view_colorbar_range_mock.assert_called_once_with((1, 5))
        view_colorbar_log_mock.assert_called_once_with(False)

        # passed view -> model
        view_colorbar_range_mock.return_value = (2, 10)
        view_colorbar_log_mock.return_value = True
        self.presenter._set_c_range()
        self.presenter._set_colorbar_log()
        self.presenter.get_new_config()
        self.model.change_axis_scale.assert_called_once_with((2, 10), True)
Пример #6
0
def test_set_rf_config_all(runner, mock_rak811):
    p = PropertyMock()
    type(mock_rak811.return_value).rf_config = p
    result = runner.invoke(cli, [
        '-v', 'rf-config',
        'freq=868.200',
        'sf=8',
        'bw=1',
        'cr=2',
        'prlen=16',
        'pwr=8'
    ])
    p.assert_called_once_with({
        'freq': 868.200,
        'sf': 8,
        'bw': 1,
        'cr': 2,
        'prlen': 16,
        'pwr': 8
    })
    assert('freq=868.2') in result.output
    assert('sf=8') in result.output
    assert('bw=1') in result.output
    assert('cr=2') in result.output
    assert('prlen=16') in result.output
    assert('pwr=8') in result.output
    def test_change_xrange(self):

        view_x_range_mock = PropertyMock()
        type(self.view).x_range = view_x_range_mock

        model_x_range_mock = PropertyMock(return_value=(1, 5))
        type(self.model).x_range = model_x_range_mock

        # passed model -> view
        self.presenter1 = SlicePlotOptionsPresenter(self.view, self.model)

        model_x_range_mock.assert_called_with()
        view_x_range_mock.assert_called_once_with((1, 5))

        # passed view -> model through slice presenter
        model_x_range_mock.reset_mock()
        view_x_range_mock.return_value = (2, 10)
        self.presenter1._xy_config_modified('x_range')
        self.presenter1.get_new_config()
        model_x_range_mock.assert_called_once_with((2, 10))

        # passed view -> model through cut presenter
        self.presenter2 = CutPlotOptionsPresenter(self.view, self.model)
        self.presenter2._xy_config_modified('x_range')
        self.presenter2.get_new_config()
        self.model.change_axis_scale.assert_called_once()
Пример #8
0
def test_set_rf_config_one(runner, mock_rak811):
    p = PropertyMock()
    type(mock_rak811.return_value).rf_config = p
    result = runner.invoke(cli, ['-v', 'rf-config', 'sf=8'])
    p.assert_called_once_with({
        'sf': 8
    })
    assert result.output == 'rf_config set: sf=8\n'
Пример #9
0
def test_radio_status(runner, mock_rak811):
    p = PropertyMock(return_value=(8, 0, 1, 0, 0, -48, 28))
    type(mock_rak811.return_value).radio_status = p
    result = runner.invoke(cli, ['radio-status'])
    p.assert_called_once_with()
    assert result.output == (
        '8 0 1 0 0 -48 28\n'
    )
Пример #10
0
    def test_propertymock_returnvalue(self):
        m = MagicMock()
        p = PropertyMock()
        type(m).foo = p

        returned = m.foo
        p.assert_called_once_with()
        self.assertIsInstance(returned, MagicMock)
        self.assertNotIsInstance(returned, PropertyMock)
Пример #11
0
    def test_propertymock_returnvalue(self):
        m = MagicMock()
        p = PropertyMock()
        type(m).foo = p

        returned = m.foo
        p.assert_called_once_with()
        self.assertIsInstance(returned, MagicMock)
        self.assertNotIsInstance(returned, PropertyMock)
Пример #12
0
    def test_set_config_xml(self):
        expected_config_xml = "<Sample Config XML/>"
        mock_data_io = MagicMock()
        p = PropertyMock(return_value=expected_config_xml)
        type(mock_data_io).config_xml = p

        v = vView(mock_data_io, None)
        v.config_xml = expected_config_xml

        self.assertEqual(p.call_count, 1)
        p.assert_called_once_with(expected_config_xml)
Пример #13
0
def test_abp_info_verbose(runner, mock_rak811):
    p = PropertyMock(return_value=('13', '26dddddd',
                                   '9annnnnnnnnnnnnnnnnnnnnnnnnnnnnn',
                                   '0baaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'))
    type(mock_rak811.return_value).abp_info = p
    result = runner.invoke(cli, ['-v', 'abp-info'])
    p.assert_called_once_with()
    assert result.output == ('NwkId: 13\n'
                             'DevAddr: 26dddddd\n'
                             'Nwkskey: 9annnnnnnnnnnnnnnnnnnnnnnnnnnnnn\n'
                             'Appskey: 0baaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n')
Пример #14
0
def test_abp_info(runner, mock_rak811):
    p = PropertyMock(return_value=('13', '26dddddd',
                                   '9annnnnnnnnnnnnnnnnnnnnnnnnnnnnn',
                                   '0baaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'))
    type(mock_rak811.return_value).abp_info = p
    result = runner.invoke(cli, ['abp-info'])
    p.assert_called_once_with()
    assert result.output == ('13 '
                             '26dddddd '
                             '9annnnnnnnnnnnnnnnnnnnnnnnnnnnnn '
                             '0baaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
                             '\n')
Пример #15
0
def test_radio_status_verbose(runner, mock_rak811):
    p = PropertyMock(return_value=(8, 0, 1, 0, 0, -48, 28))
    type(mock_rak811.return_value).radio_status = p
    result = runner.invoke(cli, ['-v', 'radio-status'])
    p.assert_called_once_with()
    assert result.output == ('TxSuccessCnt: 8\n'
                             'TxErrCnt: 0\n'
                             'RxSuccessCnt: 1\n'
                             'RxTimeOutCnt: 0\n'
                             'RxErrCnt: 0\n'
                             'RSSI: -48\n'
                             'SNR: 28\n')
Пример #16
0
    def test_get_config_xml(self):
        expected_xml = "<sample_xml/>"

        p = PropertyMock(return_value=expected_xml)
        mock_data_io = MagicMock()
        type(mock_data_io).config_xml = p
        
        v = vView(mock_data_io, None)
        actual_xml = v.config_xml
        
        self.assertEqual(actual_xml, expected_xml)
        p.assert_called_once_with()
Пример #17
0
def test_get_rf_config(runner, mock_rak811):
    p = PropertyMock(return_value={
        'freq': 868.200,
        'sf': 8,
        'bw': 1,
        'cr': 2,
        'prlen': 16,
        'pwr': 8
    })
    type(mock_rak811.return_value).rf_config = p
    result = runner.invoke(cli, ['rf-config'])
    p.assert_called_once_with()
    assert result.output == '868.2 8 1 2 16 8\n'
Пример #18
0
    def test_get_size_data_from_camera_when_not_None(self):
        mock_camera = MagicMock()

        mock_xsize = PropertyMock(return_value=100)
        mock_ysize = PropertyMock(return_value=200)
        type(mock_camera).xsize = mock_xsize
        type(mock_camera).ysize = mock_ysize

        self.monitor.camera = mock_camera

        self.monitor._update_image()

        mock_xsize.assert_called_once_with()
        mock_ysize.assert_called_once_with()
Пример #19
0
    def verify_super_property_called_with_wait(self, prop_name):
        """
        Verifies that accessing the given property calls the equally
        named property on the super class.
        """
        with patch(super_str) as mock_super, patch.object(
                self.instance, 'wait_for_angular') as mock_wait_for_angular:
            # setup the mocked property
            mock_prop = PropertyMock(name='super.{}'.format(prop_name))
            setattr(type(mock_super.return_value), prop_name, mock_prop)

            result = getattr(self.instance, prop_name)

        mock_wait_for_angular.assert_called_once_with()
        mock_super.assert_called_once_with(WebDriverMixin, self.instance)
        mock_prop.assert_called_once_with()
        self.assertIs(result, mock_prop.return_value)
Пример #20
0
def test_get_rf_config_verbose(runner, mock_rak811):
    p = PropertyMock(return_value={
        'freq': 868.200,
        'sf': 8,
        'bw': 1,
        'cr': 2,
        'prlen': 16,
        'pwr': 8
    })
    type(mock_rak811.return_value).rf_config = p
    result = runner.invoke(cli, ['-v', 'rf-config'])
    p.assert_called_once_with()
    assert result.output == ('Frequency: 868.2\n'
                             'SF: 8\n'
                             'BW: 1\n'
                             'CR: 2\n'
                             'PrLen: 16\n'
                             'Power: 8\n')
Пример #21
0
    def verify_super_property_called_with_wait(self, prop_name):
        """
        Verifies that accessing the given property calls the equally
        named property on the super class.
        """
        with patch(
                super_str
        ) as mock_super, patch.object(
            self.instance, 'wait_for_angular'
        ) as mock_wait_for_angular:
            # setup the mocked property
            mock_prop = PropertyMock(name='super.{}'.format(prop_name))
            setattr(type(mock_super.return_value), prop_name, mock_prop)

            result = getattr(self.instance, prop_name)

        mock_wait_for_angular.assert_called_once_with()
        mock_super.assert_called_once_with(WebDriverMixin, self.instance)
        mock_prop.assert_called_once_with()
        self.assertIs(result, mock_prop.return_value)
Пример #22
0
  def test_get_scheduler(self):
    """Tests successful execution of the get_scheduler command."""
    mock_options = self.setup_mock_options()
    mock_proxy = create_autospec(spec=SchedulerProxy, instance=True)
    mock_scheduler_client = create_autospec(spec=SchedulerClient, instance=True)
    mock_raw_url = PropertyMock(return_value="url")
    mock_proxy.scheduler_client.return_value = mock_scheduler_client
    type(mock_scheduler_client).raw_url = mock_raw_url

    with contextlib.nested(
        patch('twitter.common.app.get_options', return_value=mock_options),
        patch('apache.aurora.admin.admin.make_admin_client',
              return_value=create_autospec(spec=AuroraClientAPI)),
        patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS),
    ) as (_, mock_make_admin_client, _):

      api = mock_make_admin_client.return_value
      type(api).scheduler_proxy = PropertyMock(return_value=mock_proxy)

      get_scheduler([self.TEST_CLUSTER])

      mock_raw_url.assert_called_once_with()
Пример #23
0
    def test_load_one_workspace(self, get_ws_handle_mock, load_mock):
        # Create a view that will return a path on call to get_workspace_to_load_path
        tempdir = gettempdir(
        )  # To ensure sample paths are valid on platform of execution
        path_to_nexus = join(tempdir, 'cde.nxs')
        workspace_name = 'cde'
        self.view.get_workspace_efixed = mock.Mock(return_value=(1.845, False))
        ws_mock = mock.Mock()
        get_ws_handle_mock.return_value = ws_mock
        e_fixed = PropertyMock()
        e_mode = PropertyMock(return_value="Indirect")
        ef_defined = PropertyMock(return_value=False)
        type(ws_mock).e_fixed = e_fixed
        type(ws_mock).e_mode = e_mode
        type(ws_mock).ef_defined = ef_defined

        self.presenter.load_workspace([path_to_nexus])
        load_mock.assert_called_with(filename=path_to_nexus,
                                     output_workspace=workspace_name)
        e_fixed.assert_called_once_with(1.845)
        self.main_presenter.show_workspace_manager_tab.assert_called_once()
        self.main_presenter.show_tab_for_workspace.assert_called_once()
        self.main_presenter.update_displayed_workspaces.assert_called_once()
Пример #24
0
    def test_nb_convert_engine(self):
        with patch.object(engines, 'PapermillExecutePreprocessor') as pep_mock:
            # Mock log_output calls
            log_out_mock = PropertyMock()
            type(pep_mock.return_value).log_output = log_out_mock

            with patch.object(NotebookExecutionManager, 'save') as save_mock:
                nb = NBConvertEngine.execute_notebook(
                    self.nb,
                    'python',
                    output_path='foo.ipynb',
                    progress_bar=False,
                    log_output=True,
                    bar='baz',
                    start_timeout=30,
                    execution_timeout=1000,
                )

                self.assertEqual(nb, AnyMock(NotebookNode))
                self.assertNotEqual(self.nb, nb)

                pep_mock.assert_called_once()

                args, kwargs = pep_mock.call_args
                expected = [('timeout', 1000), ('startup_timeout', 30),
                            ('kernel_name', 'python'), ('log', logger)]
                actual = set([(key, kwargs[key]) for key in kwargs])
                msg = 'Expected arguments {} are not a subset of actual {}'.format(
                    expected, actual)
                self.assertTrue(set(expected).issubset(actual), msg=msg)

                log_out_mock.assert_called_once_with(True)
                pep_mock.return_value.preprocess.assert_called_once_with(
                    AnyMock(NotebookExecutionManager), {'bar': 'baz'})
                # Once for start and once for complete (cell not called by mock)
                self.assertEqual(save_mock.call_count, 2)
    def test_change_title(self):

        mock_view_title = PropertyMock()
        type(self.view).title = mock_view_title

        mock_model_title = PropertyMock(return_value='Title 0')
        type(self.model).title = mock_model_title

        # title passed model -> view
        self.presenter = CutPlotOptionsPresenter(self.view, self.model)

        mock_model_title.assert_called_once_with()
        mock_view_title.assert_called_once_with('Title 0')

        # title passed view -> model
        mock_view_title.reset_mock()
        mock_model_title.reset_mock()
        mock_view_title.return_value = 'Title 1'
        self.presenter._value_modified('title')
        self.presenter.get_new_config()

        mock_view_title.assert_called_once_with()
        mock_model_title.assert_called_once_with('Title 1')
Пример #26
0
def test_version(runner, mock_rak811):
    p = PropertyMock(return_value='2.0.3.0')
    type(mock_rak811.return_value).version = p
    result = runner.invoke(cli, ['version'])
    p.assert_called_once_with()
    assert result.output == '2.0.3.0\n'
Пример #27
0
def test_link_cnt(runner, mock_rak811):
    p = PropertyMock(return_value=(15, 2))
    type(mock_rak811.return_value).link_cnt = p
    result = runner.invoke(cli, ['-v', 'link-cnt'])
    p.assert_called_once_with()
    assert result.output == 'Uplink: 15 - Downlink: 2\n'
Пример #28
0
def test_recv_ex_disabled(runner, mock_rak811):
    p = PropertyMock()
    type(mock_rak811.return_value).recv_ex = p
    result = runner.invoke(cli, ['-v', 'recv-ex', 'disable'])
    p.assert_called_once_with(RecvEx.Disabled)
    assert result.output == 'RSSI & SNR report on receive Disabled.\n'
Пример #29
0
def test_mode_lora(runner, mock_rak811):
    p = PropertyMock()
    type(mock_rak811.return_value).mode = p
    result = runner.invoke(cli, ['-v', 'mode', 'LoRawan'])
    p.assert_called_once_with(Mode.LoRaWan)
    assert result.output == 'Mode set to LoRaWan.\n'
Пример #30
0
def test_band_eu868(runner, mock_rak811):
    p = PropertyMock()
    type(mock_rak811.return_value).band = p
    result = runner.invoke(cli, ['-v', 'band', 'EU868'])
    p.assert_called_once_with('EU868')
    assert result.output == 'LoRaWan region set to EU868.\n'
    def test_change_axis(self):

        view_x_label_mock = PropertyMock()
        view_y_label_mock = PropertyMock()
        model_x_label_mock = PropertyMock(return_value='x0')
        model_y_label_mock = PropertyMock(return_value='y0')

        type(self.view).x_label = view_x_label_mock
        type(self.view).y_label = view_y_label_mock
        type(self.model).x_label = model_x_label_mock
        type(self.model).y_label = model_y_label_mock

        # labels passed model -> view
        self.presenter = SlicePlotOptionsPresenter(self.view, self.model)
        model_x_label_mock.assert_called_once_with()
        model_y_label_mock.assert_called_once_with()
        view_x_label_mock.assert_called_once_with('x0')
        view_y_label_mock.assert_called_once_with('y0')

        # labels passed view -> model
        model_x_label_mock.reset_mock()
        model_y_label_mock.reset_mock()
        view_x_label_mock.reset_mock()
        view_y_label_mock.reset_mock()

        view_x_label_mock.return_value = 'x1'
        view_y_label_mock.return_value = 'y1'
        self.presenter._value_modified('x_label')
        self.presenter._value_modified('y_label')
        self.presenter.get_new_config()

        view_x_label_mock.assert_called_once_with()
        view_y_label_mock.assert_called_once_with()
        model_x_label_mock.assert_called_once_with('x1')
        model_y_label_mock.assert_called_once_with('y1')
    def test_change_grid(self):

        view_x_grid_mock = PropertyMock()
        view_y_grid_mock = PropertyMock()
        model_x_grid_mock = PropertyMock(return_value=False)
        model_y_grid_mock = PropertyMock(return_value=False)

        type(self.view).x_grid = view_x_grid_mock
        type(self.view).y_grid = view_y_grid_mock
        type(self.model).x_grid = model_x_grid_mock
        type(self.model).y_grid = model_y_grid_mock

        # labels passed model -> view
        self.presenter = SlicePlotOptionsPresenter(self.view, self.model)
        model_x_grid_mock.assert_called_once_with()
        model_y_grid_mock.assert_called_once_with()
        view_x_grid_mock.assert_called_once_with(False)
        view_y_grid_mock.assert_called_once_with(False)

        # labels passed view -> model
        model_x_grid_mock.reset_mock()
        model_y_grid_mock.reset_mock()
        view_x_grid_mock.reset_mock()
        view_y_grid_mock.reset_mock()

        view_x_grid_mock.return_value = True
        view_y_grid_mock.return_value = True
        self.presenter._value_modified('x_grid')
        self.presenter._value_modified('y_grid')
        self.presenter.get_new_config()

        view_x_grid_mock.assert_called_once_with()
        view_y_grid_mock.assert_called_once_with()
        model_x_grid_mock.assert_called_once_with(True)
        model_y_grid_mock.assert_called_once_with(True)
Пример #33
0
def test_mode(runner, mock_rak811):
    p = PropertyMock(return_value=Mode.LoRaWan)
    type(mock_rak811.return_value).mode = p
    result = runner.invoke(cli, ['mode'])
    p.assert_called_once_with()
    assert result.output == 'LoRaWan\n'
Пример #34
0
def test_signal(runner, mock_rak811):
    p = PropertyMock(return_value=(-30, 26))
    type(mock_rak811.return_value).signal = p
    result = runner.invoke(cli, ['signal'])
    p.assert_called_once_with()
    assert result.output == '-30 26\n'
Пример #35
0
def test_recv_ex(runner, mock_rak811):
    p = PropertyMock(return_value=RecvEx.Enabled)
    type(mock_rak811.return_value).recv_ex = p
    result = runner.invoke(cli, ['recv-ex'])
    p.assert_called_once_with()
    assert result.output == 'Enabled\n'
Пример #36
0
def test_dr(runner, mock_rak811):
    p = PropertyMock(return_value=5)
    type(mock_rak811.return_value).dr = p
    result = runner.invoke(cli, ['dr'])
    p.assert_called_once_with()
    assert result.output == '5\n'
Пример #37
0
def test_set_dr(runner, mock_rak811):
    p = PropertyMock()
    type(mock_rak811.return_value).dr = p
    result = runner.invoke(cli, ['-v', 'dr', '5'])
    p.assert_called_once_with(5)
    assert result.output == 'Data rate set to 5.\n'
Пример #38
0
class TestGeometry(LocationTestCase):
    """
    Test case class for base Geometry tests.

    This class tests the `Geometry` interface. It can be subclassed in order
    to test the subclasses of `Geometry`. The test methods are then inherited,
    so some may need to be overridden to test different behavior.
    """

    def setUp(self):
        super(TestGeometry, self).setUp()

        # Geometry object to use in the tests.
        self.geometry = Geometry()

        # Delta values for approximate equality checks.
        # The default values handle float inaccuracies that may be caused by 
        # conversions in the geometry class.
        self.dist_delta = sys.float_info.epsilon * 10
        self.coord_delta = self.dist_delta
        self.angle_delta = sys.float_info.epsilon * 10

        # Create a mock version of a `Locations` object. The location frames 
        # have property mocks that can be configured to return a specific 
        # location value.
        self.locations_mock = Mock(spec_set=Locations)
        self.relative_mock = PropertyMock()
        self.global_mock = PropertyMock()
        self.local_mock = PropertyMock()

        type(self.locations_mock).global_relative_frame = self.relative_mock
        type(self.locations_mock).global_frame = self.global_mock
        type(self.locations_mock).local_frame = self.local_mock

        # Location objects that can be used by type checking tests, where the 
        # coordinate values do not matter at all.
        self.local_location = LocationLocal(1.0, 2.0, 3.0)
        self.global_location = LocationGlobal(4.0, 5.0, 6.0)
        self.relative_location = LocationGlobalRelative(7.0, 8.0, 9.0)

    def _make_global_location(self, x, y, z=0.0):
        """
        Create a `Location` object that is suitable as a global location.

        The returned type depends on the geometry being tested.
        """

        return LocationLocal(x, y, -z)

    def _make_relative_location(self, x, y, z=0.0):
        """
        Create a `Location` object that is suitable as a relative location.

        The returned type depends on the geometry being tested.
        """

        return LocationLocal(x, y, -z)

    def test_set_home_location(self):
        self.assertEqual(self.geometry.home_location,
                         self._make_global_location(0.0, 0.0, 0.0))

        home_loc = self._make_global_location(1.0, 2.0, 3.0)
        self.geometry.set_home_location(home_loc)
        self.assertEqual(self.geometry.home_location, home_loc)

    def test_set_home_location_type(self):
        # Base geometry does not support relative or global locations.
        with self.assertRaises(TypeError):
            self.geometry.set_home_location(self.relative_location)

        with self.assertRaises(TypeError):
            self.geometry.set_home_location(self.global_location)

    def test_equalize(self):
        # Local locations are kept intact.
        loc1 = LocationLocal(1.0, 2.0, 3.0)
        loc2 = LocationLocal(4.5, 6.7, -8.9)
        new_loc1, new_loc2 = self.geometry.equalize(loc1, loc2)
        self.assertEqual(loc1, new_loc1)
        self.assertEqual(loc2, new_loc2)

        # Base geometry does not support relative or global locations.
        with self.assertRaises(TypeError):
            self.geometry.equalize(self.local_location, self.relative_location)
        with self.assertRaises(TypeError):
            self.geometry.equalize(self.relative_location, self.global_location)
        with self.assertRaises(TypeError):
            self.geometry.equalize(self.global_location, self.local_location)

    def test_equals(self):
        loc = LocationLocal(1.0, 2.0, -3.0)
        self.assertTrue(self.geometry.equals(loc, loc))
        # Integer coordinates are still equal to floats.
        self.assertTrue(self.geometry.equals(loc, LocationLocal(1.0, 2, -3.0)))
        self.assertFalse(self.geometry.equals(loc, LocationLocal(1, 2, -3.14)))

    def test_make_location(self):
        # Base geometry creates local locations with inverted down component.
        loc = LocationLocal(1.0, 2.0, -3.0)
        self.assertEqual(self.geometry.make_location(1.0, 2.0, 3.0), loc)

    def test_get_coordinates(self):
        # Check that retrieving coordinates from `Location` objects works.
        # The supported location types of the geometry are tested.
        loc1 = LocationLocal(1.0, 2.0, -3.0)
        self.assertEqual(self.geometry.get_coordinates(loc1), (1.0, 2.0, 3.0))

        loc2 = self._make_relative_location(4.0, 5.0, 6.0)
        self.assertEqual(self.geometry.get_coordinates(loc2), (4.0, 5.0, 6.0))

        loc3 = self._make_global_location(7.0, 8.0, 9.0)
        self.assertEqual(self.geometry.get_coordinates(loc3), (7.0, 8.0, 9.0))

        # A `Location` object must be provided.
        with self.assertRaises(TypeError):
            self.geometry.get_coordinates(None)

    def test_bearing_to_angle(self):
        bearing = -45.0 * math.pi/180
        self.assertEqual(self.geometry.bearing_to_angle(bearing),
                         135.0 * math.pi/180)

    def test_angle_to_bearing(self):
        angle = 180.0 * math.pi/180
        self.assertEqual(self.geometry.angle_to_bearing(angle),
                         270.0 * math.pi/180)

    def test_get_location_local(self):
        local_location = LocationLocal(7.6, 5.4, -3.2)
        self.assertEqual(self.geometry.get_location_local(local_location),
                         local_location)

        self.local_mock.configure_mock(return_value=local_location)
        self.assertEqual(self.geometry.get_location_local(self.locations_mock),
                         local_location)
        self.local_mock.assert_called_once_with()

    def test_get_location_local_other(self):
        # Base geometry does not support relative or global locations.
        with self.assertRaises(TypeError):
            self.geometry.get_location_local(self.global_location)
        with self.assertRaises(TypeError):
            self.geometry.get_location_local(self.relative_location)

    def test_get_location_frame(self):
        local_location = LocationLocal(7.6, 5.4, -3.2)
        self.local_mock.configure_mock(return_value=local_location)
        self.assertEqual(self.geometry.get_location_frame(self.locations_mock),
                         local_location)
        self.local_mock.assert_called_once_with()

    def test_get_location_frame_other(self):
        # A `Locations` object must be given.
        with self.assertRaises(TypeError):
            self.geometry.get_location_frame(self.local_location)
        with self.assertRaises(TypeError):
            self.geometry.get_location_frame(self.global_location)
        with self.assertRaises(TypeError):
            self.geometry.get_location_frame(self.relative_location)

    def test_get_location_meters(self):
        loc = LocationLocal(5.4, 3.2, -1.0)
        loc2 = LocationLocal(5.4, 3.2, -11.0)
        self.assertEqual(self.geometry.get_location_meters(loc, 0, 0, 0), loc)
        self.assertEqual(self.geometry.get_location_meters(loc, 0, 0, 10), loc2)

    def test_get_distance_meters(self):
        loc = LocationLocal(5.4, 3.2, -1.0)
        # 3 * 3 + 4 * 4 = 9 + 16 = 25 which is 5 squared.
        loc2 = self.geometry.get_location_meters(loc, 3.0, 4.0)
        self.assertAlmostEqual(self.geometry.get_distance_meters(loc, loc2),
                               5.0, delta=self.dist_delta)

    def test_norm(self):
        # 3 * 3 + 4 * 4 = 9 + 16 = 25 which is 5 squared.
        self.assertEqual(self.geometry.norm(3.0, 4.0), 5.0)
        # (-12)**2 + 5**2 = 144 + 25 which is 13 squared.
        self.assertEqual(self.geometry.norm(0.0, -12.0, 5.0), 13.0)

    def test_diff_location_meters(self):
        loc = LocationLocal(5.4, 3.2, -1.0)
        # 3 * 3 + 4 * 4 = 9 + 16 = 25 which is 5 squared.
        loc2 = self.geometry.get_location_meters(loc, 3.0, 4.0, 5.0)
        dlat, dlon, dalt = self.geometry.diff_location_meters(loc, loc2)
        self.assertAlmostEqual(dlat, 3.0, delta=self.dist_delta)
        self.assertAlmostEqual(dlon, 4.0, delta=self.dist_delta)
        self.assertAlmostEqual(dalt, 5.0, delta=self.dist_delta)

    def test_get_location_range(self):
        home = self._make_relative_location(0.0, 0.0, 0.0)
        cases = [
            {
                "start": (0.0, 0.0),
                "end": (4.0, 0.0),
                "count": 4,
                "range": [(1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)]
            },
            {
                "start": (5.0, 1.0),
                "end": (5.0, 3.0),
                "count": 2,
                "range": [(5.0, 2.0), (5.0, 3.0)]
            },
            {
                "start": (6.0, 6.0, 0.0),
                "end": (3.0, 0.0, 9.0),
                "count": 3,
                "range": [(5.0, 4.0, 3.0), (4.0, 2.0, 6.0), (3.0, 0.0, 9.0)]
            },
            {
                "start": (3.0, 4.0),
                "end": (3.0, 4.0),
                "count": 5,
                "range": [(3.0, 4.0)]*5
            },
            {
                "start": (4.0, 5.0),
                "end": (6.0, 7.0),
                "count": 1,
                "range": [(6.0, 7.0)]
            }
        ]
        for case in cases:
            start = self.geometry.get_location_meters(home, *case["start"])
            end = self.geometry.get_location_meters(home, *case["end"])
            actual = self.geometry.get_location_range(start, end,
                                                      count=case["count"])
            self.assertEqual(len(actual), len(case["range"]))
            for actual_loc, p in zip(actual, case["range"]):
                expected_loc = self.geometry.get_location_meters(home, *p)
                self.assertEqual(actual_loc,
                                 self.geometry.get_location_local(expected_loc))

    def test_get_location_angle(self):
        loc = LocationLocal(5.0, 3.0, -1.0)
        loc2 = self.geometry.get_location_meters(loc, 10, math.sqrt(200),
                                                 math.sqrt(200))
        cl = self.geometry.get_location_angle(loc, 20, 45.0 * math.pi/180,
                                              45.0 * math.pi/180)
        self.assertAlmostEqual(cl.north, loc2.north, delta=self.coord_delta)
        self.assertAlmostEqual(cl.east, loc2.east, delta=self.coord_delta)
        self.assertAlmostEqual(cl.down, loc2.down, delta=self.coord_delta)

        other_loc = self.geometry.get_location_angle(loc, 10.0, math.pi/4)
        angle = self.geometry.get_angle(loc, other_loc)
        self.assertAlmostEqual(angle, math.pi/4, delta=self.angle_delta)

    def test_get_angle(self):
        loc = LocationLocal(5.4, 3.2, -1.0)
        loc2 = self.geometry.get_location_meters(loc, 10.0, 10.0, 0.0)
        self.assertAlmostEqual(self.geometry.get_angle(loc, loc2),
                               45.0 * math.pi/180, delta=self.angle_delta)

    def test_diff_angle(self):
        self.assertEqual(self.geometry.diff_angle(math.pi, 3*math.pi), 0.0)
        self.assertEqual(abs(self.geometry.diff_angle(-math.pi/2, math.pi/2)),
                         math.pi)

    def test_check_angle(self):
        right = math.pi/2
        self.assertTrue(self.geometry.check_angle(math.pi, 3*math.pi, 0.0))
        self.assertFalse(self.geometry.check_angle(-right, right, math.pi/4))
        self.assertTrue(self.geometry.check_angle(2.0 * math.pi/180,
                                                  -2.0 * math.pi/180,
                                                  5.0 * math.pi/180))

    def test_get_direction(self):
        self.assertEqual(self.geometry.get_direction(0.0, math.pi/2), -1)
        self.assertEqual(self.geometry.get_direction(-math.pi/2, math.pi), 1)

    def test_get_neighbor_offsets(self):
        offsets = self.geometry.get_neighbor_offsets()
        self.assertEqual(offsets.shape, (8, 2))

        # pylint: disable=bad-continuation,bad-whitespace
        self.assertTrue(np.array_equal(offsets, [ (1, -1),  (1, 0),  (1, 1),
                                                  (0, -1),           (0, 1),
                                                 (-1, -1), (-1, 0), (-1, 1)]))

    def test_get_neighbor_directions(self):
        angles = self.geometry.get_neighbor_directions()
        self.assertEqual(angles.shape, (8,))
        eighth = math.pi/4

        # pylint: disable=bad-continuation,bad-whitespace
        self.assertTrue(np.array_equal(angles, [7*eighth,   0.0,   1*eighth,
                                                6*eighth,          2*eighth,
                                                5*eighth, math.pi, 3*eighth]))

    def test_ray_intersects_segment(self):
        cases = [
            [(1, 0), (2, 1), (0, 1), True], # Vertical edge
            [(1, 1), (2, 1), (0, 1), True], # Precisely on vertical edge
            [(1, 1), (1, 4), (4, 1), True], # Non-straight edge
            [(2, 0), (3, 1), (5.5, 3.25), False], # Too far north
            [(3, 20), (3, 2), (5, 7.6), False], # Too far east
            [(2, 3.5), (1, 1), (4, 4), False], # Right from edge
            [(2, 4), (1, 1), (4, 4), False] # Right from edge
        ]
        for case in cases:
            P = self._make_relative_location(*case[0])
            start = self._make_relative_location(*case[1])
            end = self._make_relative_location(*case[2])
            expected = case[3]
            with patch('sys.stdout'):
                actual = self.geometry.ray_intersects_segment(P, start, end,
                                                              verbose=True)
                msg = "Ray from {0} must{neg} intersect start={1}, end={2}"
                msg = msg.format(*case, neg="" if expected else " not")
                self.assertEqual(actual, expected, msg=msg)

    def test_point_inside_polygon(self):
        # http://rosettacode.org/wiki/Ray-casting_algorithm#Python
        polys = {
            "square": [(0, 0), (10, 0), (10, 10), (0, 10)],
            "square_hole": [
                (0, 0), (10, 0), (10, 10), (0, 10), (0, 0),
                (2.5, 2.5), (7.5, 2.5), (7.5, 7.5), (2.5, 7.5)
            ],
            "exagon": [(3, 0), (7, 0), (10, 5), (7, 10), (3, 10), (0, 5)]
        }
        locs = [(5, 8), (-10, 5), (10, 10)]
        results = {
            "square": [True, False, False],
            "square_hole": [True, False, False],
            "exagon": [True, False, False]
        }

        for name, poly in polys.iteritems():
            points = [self._make_relative_location(*p) for p in poly]
            for loc, expected in zip(locs, results[name]):
                location = self._make_relative_location(*loc)
                actual = self.geometry.point_inside_polygon(location, points)
                msg = "Point {} must{} be inside polygon {}"
                msg = msg.format(loc, "" if expected else " not", name)
                self.assertEqual(actual, expected, msg=msg)

        poly = polys["square"]
        points = [self._make_relative_location(*p) for p in poly]
        location = self._make_relative_location(1, 2, 3)
        with patch('sys.stdout'):
            inside = self.geometry.point_inside_polygon(location, points,
                                                        alt=True, verbose=True)
            self.assertFalse(inside)

    def test_get_edge_distance(self):
        start_location = self._make_relative_location(0.0, 0.0, 0.0)
        cases = [
            [(1, 0), (2, 1), (0, 1), 1.0], # Vertical edge
            [(1, 0), (2, 0), (2, 2), sys.float_info.max], # Horizontal edge
            [(1, 1), (2, 1), (0, 1), 0.0], # Precisely on vertical edge
            [(1, 1), (1, 4), (4, 1), 3.0], # Non-straight edge
            [(1, 1), (4, 1), (1, 4), 3.0], # Non-straight edge (swapped)
            [(1, 1), (2, 4), (4, 2), sys.float_info.max] # Non-extended line
        ]
        for case in cases:
            loc = self.geometry.get_location_meters(start_location, *case[0])
            start = self.geometry.get_location_meters(start_location, *case[1])
            end = self.geometry.get_location_meters(start_location, *case[2])
            expected = case[3]

            actual = self.geometry.get_edge_distance((start, end), loc)
            self.assertAlmostEqual(actual, expected, delta=self.dist_delta)

        # Miss the edge
        loc = self.geometry.get_location_meters(start_location, 1, 0.66, 0)
        start = self.geometry.get_location_meters(start_location, 2, 1, 0)
        end = self.geometry.get_location_meters(start_location, 0, 1, 0)
        actual = self.geometry.get_edge_distance((start, end), loc,
                                                 pitch_angle=0.25*math.pi)
        self.assertEqual(actual, sys.float_info.max)

    def test_get_point_edges(self):
        self.assertEqual(self.geometry.get_point_edges([]), [])
        points = [(1, 2, 3), (20.0, 4.3, 2.5), (3.14, 4.443, 1.2)]
        locations = [self._make_relative_location(*p) for p in points]
        edges = self.geometry.get_point_edges(locations)
        self.assertEqual(edges[0], (locations[0], locations[1]))
        self.assertEqual(edges[1], (locations[1], locations[2]))
        self.assertEqual(edges[2], (locations[2], locations[0]))

    def test_get_projected_location(self):
        location = LocationLocal(1.0, 2.0, -3.0)
        self.assertEqual(self.geometry.get_projected_location(location, 0),
                         LocationLocal(2.0, 3.0, 0.0))
        self.assertEqual(self.geometry.get_projected_location(location, 1),
                         LocationLocal(1.0, 3.0, 0.0))
        self.assertEqual(self.geometry.get_projected_location(location, 2),
                         location)

    @covers([
        "get_plane_intersection", "get_plane_vector", "point_inside_plane"
    ])
    def test_get_plane_distance(self):
        home = self._make_relative_location(0.0, 0.0, 0.0)
        cases = [
            # Upward polygon
            {
                "points": [(1, 2, 3), (1, 4, 3), (1, 4, 9), (1, 2, 9)],
                "location1": (0, 3, 6),
                "location2": (0.1, 3, 6),
                "distance": 1.0,
                "loc_point": (1, 3, 6)
            },
            # Missing the polygon
            {
                "points": [(1, 2, 3), (1, 4, 3), (1, 4, 9), (1, 2, 9)],
                "location1": (0, 5, 6),
                "location2": (0.1, 5, 6),
                "distance": sys.float_info.max,
                "loc_point": None
            },
            # Line segment in the other direction
            {
                "points": [(1, 2, 3), (1, 4, 3), (1, 4, 9), (1, 2, 9)],
                "location1": (0, 3, 6),
                "location2": (-0.1, 3, 6),
                "distance": sys.float_info.max,
                "loc_point": None
            },
            # Not intersecting with plane
            {
                "points": [(1, 2, 3), (1, 4, 3), (1, 4, 9), (1, 2, 9)],
                "location1": (0, 3, 6),
                "location2": (0, 3.1, 6),
                "distance": sys.float_info.max,
                "loc_point": None
            },
            # Incomplete face
            {
                "points": [(1, 2, 3), (1, 4, 3)],
                "location1": (0, 3, 6),
                "location2": (0.1, 3, 6),
                "distance": sys.float_info.max,
                "loc_point": None
            }
        ]
        for case in cases:
            points = case["points"]
            face = [self.geometry.get_location_meters(home, *p) for p in points]
            loc1 = self.geometry.get_location_meters(home, *case["location1"])
            loc2 = self.geometry.get_location_meters(home, *case["location2"])
            with patch('sys.stdout'):
                dist, point = self.geometry.get_plane_distance(face,
                                                               loc1, loc2,
                                                               verbose=True)

            self.assertAlmostEqual(dist, case["distance"],
                                   delta=self.dist_delta)
            if case["loc_point"] is None:
                self.assertIsNone(point)
            else:
                actual = self.geometry.get_location_local(point)
                location = self.geometry.get_location_meters(home,
                                                             *case["loc_point"])
                expected = self.geometry.get_location_local(location)
                self.assertAlmostEqual(actual.north, expected.north,
                                       delta=self.coord_delta)
                self.assertAlmostEqual(actual.east, expected.east,
                                       delta=self.coord_delta)
                self.assertAlmostEqual(actual.down, expected.down,
                                       delta=self.coord_delta)