Beispiel #1
0
def test_splunk_saved_searches(splunk_client):
    """Check saved searches."""
    splunk_client.connect = cli_connect
    sp_driver = SplunkDriver()

    # trying to get these before connecting should throw
    with pytest.raises(MsticpyNotConnectedError) as mp_ex:
        sp_driver._get_saved_searches()
        check.is_false(sp_driver.connected)
        check.is_none(sp_driver._saved_searches)
    check.is_in("not connected to Splunk.", mp_ex.value.args)

    sp_driver.connect(host="localhost", username="******",
                      password="******")  # nosec
    check.is_true(sp_driver.connected)

    check.is_instance(sp_driver._saved_searches, pd.DataFrame)
    for _, search in sp_driver._saved_searches.iterrows():
        check.is_true(search["name"].startswith("query"))
        check.equal(search["query"], "get stuff from somewhere")

    queries, name = sp_driver.service_queries
    check.equal(name, "SavedSearches")
    check.is_instance(queries, dict)
    for name, query in queries.items():
        check.is_true(name.startswith("query"))
        check.equal(query, "search get stuff from somewhere")
Beispiel #2
0
def test_splunk_saved_searches(splunk_client):
    """Check saved searches."""
    splunk_client.connect = cli_connect
    sp_driver = SplunkDriver()

    # trying to get these before connecting should throw
    with pytest.raises(MsticpyNotConnectedError) as mp_ex:
        sp_driver._get_saved_searches()
        check.is_false(sp_driver.connected)
        check.is_none(sp_driver._saved_searches)
    check.is_in("not connected to Splunk.", mp_ex.value.args)

    # [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Test code")]
    sp_driver.connect(host="localhost", username="******", password=_FAKE_STRING)  # nosec
    check.is_true(sp_driver.connected)

    check.is_instance(sp_driver._saved_searches, pd.DataFrame)
    for _, search in sp_driver._saved_searches.iterrows():
        check.is_true(search["name"].startswith("query"))
        check.equal(search["query"], "get stuff from somewhere")

    queries, name = sp_driver.service_queries
    check.equal(name, "SavedSearches")
    check.is_instance(queries, dict)
    for name, query in queries.items():
        check.is_true(name.startswith("query"))
        check.equal(query, "search get stuff from somewhere")
Beispiel #3
0
def test_notebooklet_create(monkeypatch):
    """Test method."""
    # Should run because required providers are loaded
    monkeypatch.setattr(data_providers, "GeoLiteLookup", GeoIPLiteMock)
    data_providers.init(query_provider="LocalData",
                        providers=["tilookup", "geolitelookup"])
    for _, nblt in nblts.iter_classes():
        new_nblt = nblt()
        check.is_instance(new_nblt, Notebooklet)
        check.is_none(new_nblt.result)

    # Should throw a warning because of unrecognized provider
    data_providers.init(query_provider="LocalData")
    with pytest.raises(MsticnbDataProviderError) as err:
        for _, nblt in nblts.iter_classes():
            curr_provs = nblt.metadata.req_providers
            bad_provs = [*curr_provs, "bad_provider"]
            try:
                nblt.metadata.req_providers = bad_provs
                new_nblt = nblt()
                check.is_instance(new_nblt, Notebooklet)
                check.is_none(new_nblt.result)
            finally:
                nblt.metadata.req_providers = curr_provs
    check.is_in("bad_provider", err.value.args[0])
    test_nb = TstNBSummary()
    check.is_not_none(test_nb.get_provider("LocalData"))
    with pytest.raises(MsticnbDataProviderError):
        test_nb.get_provider("otherprovider")
Beispiel #4
0
def test_notebooklet_options(monkeypatch):
    """Test option logic for notebooklet."""
    monkeypatch.setattr(data_providers, "GeoLiteLookup", GeoIPLiteMock)
    data_providers.init(query_provider="LocalData",
                        providers=["tilookup", "geolitelookup"])
    nb_test = TstNBSummary()

    # default options
    nb_res = nb_test.run()
    check.is_not_none(nb_res.default_property)
    check.is_none(nb_res.optional_property)

    # add optional option
    nb_res = nb_test.run(options=["+optional_opt"])
    check.is_not_none(nb_res.default_property)
    check.is_not_none(nb_res.optional_property)

    # remove default option
    nb_res = nb_test.run(options=["-default_opt"])
    check.is_none(nb_res.default_property)
    check.is_none(nb_res.optional_property)

    # specific options
    nb_res = nb_test.run(options=["heartbest", "azure_net"])
    check.is_none(nb_res.default_property)
    check.is_none(nb_res.optional_property)

    # invalid option
    f_stream = StringIO()
    with redirect_stdout(f_stream):
        nb_test.run(options=["invalid_opt"])
    output = str(f_stream.getvalue())
    check.is_in("Invalid options ['invalid_opt']", output)
Beispiel #5
0
def test_extract_header_nowcs():
    header = fits.Header.fromstring(_base_header, sep='\n')
    h, wcs = extract_header_wcs(header)
    check.is_none(wcs)
    check.is_instance(h, fits.Header)
    check.equal(h, header)
    check.is_false(h is header)
Beispiel #6
0
def test_ip_summary_notebooklet_internal(monkeypatch):
    """Test basic run of notebooklet."""
    test_data = str(Path(TEST_DATA_PATH).absolute())
    monkeypatch.setattr(data_providers, "GeoLiteLookup", GeoIPLiteMock)
    monkeypatch.setattr(data_providers, "TILookup", TILookupMock)
    data_providers.init(
        query_provider="LocalData",
        LocalData_data_paths=[test_data],
        LocalData_query_paths=[test_data],
        providers=["tilookup", "geolitelookup"],
    )

    test_nb = nblts.azsent.network.IpAddressSummary()
    tspan = TimeSpan(period="1D")

    test_nb.query_provider.schema.update({tab: {} for tab in DEF_PROV_TABLES})
    result = test_nb.run(value="40.76.43.124", timespan=tspan)
    check.is_not_none(result.ip_entity)
    check.equal(result.ip_type, "Public")
    check.equal(result.ip_origin, "Internal")
    check.is_not_none(result.whois)
    check.is_instance(result.related_alerts, pd.DataFrame)
    check.is_instance(result.heartbeat, pd.DataFrame)
    check.is_instance(result.az_network_if, pd.DataFrame)
    check.is_none(result.passive_dns)
    check.is_none(result.ti_results)
Beispiel #7
0
    def test_on_step_end(self, mocker):
        """ should update episode_metrics for the current agent and
            steps_cycle_metrics for all agents on_step_end. """
        mocker.patch(self.logging_callback_path +
                     '._update_metrics_all_agents')
        mocker.patch(self.logging_callback_path + '._update_metrics')

        logging_callback = LoggingCallback()
        logging_callback.n_agents = 1
        logging_callback.on_step_end(step=7)

        args, kwargs = logging_callback._update_metrics.call_args
        check.equal(args[1], 'episode')
        check.is_false(kwargs.get('reset'))
        check.is_none(kwargs.get('agent_id'))

        args, kwargs = logging_callback._update_metrics_all_agents.call_args
        check.equal(args[1], 'steps_cycle')
        check.is_false(kwargs.get('reset'))

        # Multi agents
        logging_callback = LoggingCallback()
        logging_callback.n_agents = 5
        logging_callback.on_step_end(step=7, logs={'agent_id': 3})

        args, kwargs = logging_callback._update_metrics.call_args
        check.equal(args[1], 'episode')
        check.is_false(kwargs.get('reset'))
        check.equal(kwargs.get('agent_id'), 3)

        args, kwargs = logging_callback._update_metrics_all_agents.call_args
        check.equal(args[1], 'steps_cycle')
        check.is_false(kwargs.get('reset'))
Beispiel #8
0
def test_params(data, expected):
    check.equal(data.get_age(), expected["age"])
    check.equal(data.get_goals(), expected["goals"])
    check.equal(data.get_cards(), expected["cards"])
    check.equal(data.get_position(), expected["position"])
    check.equal(data.get_name(), expected["name"])
    check.is_none(data.get_club())
    check.equal(data.get_field_number(), expected["field_number"])
Beispiel #9
0
def test_clear(qtbot, page):
    widget = QWidget()
    qtbot.addWidget(widget)

    page.central_layout.addWidget(widget)
    page.clear()
    
    check.is_none(widget.parent())
    check.equal(page.central_layout.count(), 0)
Beispiel #10
0
def test_initial_values_for_user():
    p = Player("Ronaldinho", "attacker", 23)
    check.equal(p.get_age(), 23)
    check.equal(p.get_goals(), 0)
    check.equal(p.get_cards(), 0)
    check.equal(p.get_position(), "attacker")
    check.equal(p.get_name(), "Ronaldinho")
    check.is_none(p.get_club())
    check.equal(p.get_field_number(), 0)
Beispiel #11
0
def test_extract_invalid_wcs_header():
    # It should no raise, just return empty wcs
    # No header change too
    header = fits.Header.fromstring(_base_header + _invalid_wcs, sep='\n')
    h, wcs = extract_header_wcs(header)
    check.is_none(wcs)
    check.is_instance(h, fits.Header)
    check.equal(h, header)
    check.is_false(h is header)
def test_checkboxLegend_line():
    """Test legend with lines"""
    line, = plt.plot([1, 2], [1, 2], color='r', lw=2)
    legend = plt.legend([line], ["line"],
                        handler_map={line: VisibilityHandler()})
    line_handle = legend.get_legend_handler(legend.get_legend_handler_map(),
                                            line)
    line_handler = line_handle.handler
    checked = line_handle.is_checked()
    check.is_none(line_handler)
    check.equal(checked, True)
def test_checkboxLegend_patch():
    """Test legend with patches"""
    rect = mpatches.Rectangle((0, 0), 0.5, 0.5, label="rect")
    ax = plt.gca()
    ax.add_patch(rect)
    legend = plt.legend([rect], ["rect"],
                        handler_map={rect: VisibilityHandler()})
    rect_handle = legend.get_legend_handler(legend.get_legend_handler_map(),
                                            rect)
    rect_handler = rect_handle.handler
    checked = rect_handle.is_checked()
    check.is_none(rect_handler)
    check.equal(checked, True)
def test_checkboxLegend_text():
    """Test legend with text"""
    ax = plt.gca()
    line, = plt.plot([1, 2], [1, 2], color='r', lw=2)
    text = plt.text(1, 1.5, "text on plot")
    legend = plt.legend([text], ["text"],
                        handler_map={text: VisibilityHandler(handler=None)})
    text_handle = legend.get_legend_handler(legend.get_legend_handler_map(),
                                            text)
    text_handler = text_handle.handler
    checked = text_handle.is_checked()
    check.is_none(text_handler)
    check.equal(checked, True)
Beispiel #15
0
def test_classify_img():
    image_dir = '/sampleImage/'
    # Changes to tests:
    # we changed the images classified due to the limitations of our ML model
    # since the model is only trained on 1000 object categories
    # we will create a helper function in the next iteration
    # to test for semantic simularity and get better search results
    image_names = [
        'banana',
        'basketball',
        'carton',
        'cucumber',
        'fountain',
        'golden_retriever',
        'goldfish',
        'passenger_car',
        'pop_bottle',
        'seashore',
        'space_shuttle',
        'sports_car',
        'suit',
        'tabby',
        'volcano'
    ]
    # Changes to tests:
    # wrong_names is a rotation of original image_names
    # as it is unlikely that basketball
    # will be in the classification dict for banana and so on
    wrong_names = image_names[1:] + image_names[:1]
    img_ext = '.jpg'

    # instead of simply using os.getcwd(), we use full_path so that pytest will
    # find the images regardless of where you run pytest
    # (like in test/ as opposed to main dir)

    full_path = os.path.realpath(__file__)
    test_folder = os.path.dirname(full_path)

    w = Worker()
    check.is_none(w.classify_img(None))

    for idx, name in enumerate(image_names):
        img = Image.open(test_folder + image_dir + name + img_ext)
        # should all be true
        # (that 'banana' is in classification dict for 'banana.jpg' and so on)
        check.is_in(name, w.classify_img(img))

        # now let's try assertions that should definitely be wrong
        # (that 'volcano' is in the classification dict for 'banana.jpg')
        check.is_not_in(wrong_names[idx], w.classify_img(img))
Beispiel #16
0
    def test_on_run_begin(self, mocker):
        """ should set n_agents on_run_begin. """
        class DummyPlayground():
            """DummyPlaygrounf"""
            def __init__(self, n_agents):
                self.agents = [None] * n_agents

        n_agents = 5
        mocker.patch(self.logging_callback_path + '', return_value=n_agents)
        logging_callback = LoggingCallback()
        logging_callback.playground = DummyPlayground(n_agents)
        check.is_none(logging_callback.n_agents)
        logging_callback.on_run_begin()
        check.equal(logging_callback.n_agents, n_agents)
def test_constructor():

    # Currently, when the GUI object is created, we are only allowing
    # the default values to be used.

    # test default constructor with no parameters
    test_gui = GUI()
    check.equal(test_gui.video_path, '')
    check.equal(test_gui.settings, {
        'conf': .5,
        'poll': 5,
        'anti': 5,
        'runtime': 1,
        'search': []
    })
    check.is_none(test_gui.job)
Beispiel #18
0
def compare_tables(table, ref):
    for row_num in range(table.num_rows):
        for col_num in range(table.num_cols):
            if ref[row_num][col_num] is None:
                check.is_none(
                    table.cell(row_num, col_num).formula,
                    f"!existsy@[{row_num},{col_num}]",
                )
            else:
                check.is_not_none(
                    table.cell(row_num, col_num).formula,
                    f"exists@[{row_num},{col_num}]",
                )
                check.equal(
                    table.cell(row_num, col_num).formula,
                    ref[row_num][col_num],
                    f"formula@[{row_num},{col_num}]",
                )
Beispiel #19
0
def test_splunk_fired_alerts(splunk_client):
    """Check fired alerts."""
    splunk_client.connect = cli_connect
    sp_driver = SplunkDriver()

    # trying to get these before connecting should throw
    with pytest.raises(MsticpyNotConnectedError) as mp_ex:
        sp_driver._get_fired_alerts()
        check.is_false(sp_driver.connected)
        check.is_none(sp_driver._fired_alerts)
    check.is_in("not connected to Splunk.", mp_ex.value.args)
    sp_driver.connect(host="localhost", username="******",
                      password="******")  # nosec
    check.is_true(sp_driver.connected)

    check.is_instance(sp_driver._fired_alerts, pd.DataFrame)
    for _, alert in sp_driver._fired_alerts.iterrows():
        check.is_true(alert["name"].startswith("alert"))
        check.equal(alert["count"], 10)
Beispiel #20
0
def test_splunk_fired_alerts(splunk_client):
    """Check fired alerts."""
    splunk_client.connect = cli_connect
    sp_driver = SplunkDriver()

    # trying to get these before connecting should throw
    with pytest.raises(MsticpyNotConnectedError) as mp_ex:
        sp_driver._get_fired_alerts()
        check.is_false(sp_driver.connected)
        check.is_none(sp_driver._fired_alerts)
    check.is_in("not connected to Splunk.", mp_ex.value.args)

    # [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Test code")]
    sp_driver.connect(host="localhost", username="******", password=_FAKE_STRING)  # nosec
    check.is_true(sp_driver.connected)

    check.is_instance(sp_driver._fired_alerts, pd.DataFrame)
    for _, alert in sp_driver._fired_alerts.iterrows():
        check.is_true(alert["name"].startswith("alert"))
        check.equal(alert["count"], 10)
def test_checkboxLegend_multiple():
    """Test with multiple handlers"""
    ax = plt.gca()
    line, = plt.plot([1, 2], [1, 2], color='r', lw=2)
    text = plt.text(1, 1.5, "text on plot")
    rect = mpatches.Rectangle((1.5, 1.4), 0.5, 0.5, label="rect")
    rect.set_visible(0)
    ax.add_patch(rect)
    legend = plt.legend(
        [text, line, rect], ["text", "line", "rect"],
        handler_map={
            text: VisibilityHandler(),
            line: VisibilityHandler(),
            rect: VisibilityHandler()
        })
    line_handle = legend.get_legend_handler(legend.get_legend_handler_map(),
                                            line)
    line_handler = line_handle.handler
    rect_handle = legend.get_legend_handler(legend.get_legend_handler_map(),
                                            rect)
    rect_handler = rect_handle.handler
    line_checked = line_handle.is_checked()
    rect_checked = rect_handle.is_checked()
    text_handle = legend.get_legend_handler(legend.get_legend_handler_map(),
                                            text)
    text_handler = text_handle.handler
    text_checked = text_handle.is_checked()
    check.is_none(line_handler)
    check.is_none(rect_handler)
    check.is_none(text_handler)
    check.equal(line_checked, True)
    check.equal(rect_checked, False)
    check.equal(text_checked, True)
Beispiel #22
0
def test_tee(test_df, monkeypatch):
    """Test mp_pivot.tee_exec accessor."""
    ipython = _IPython()

    def _m_get_ipython():
        """Path get_ipython."""
        return ipython

    monkeypatch.setattr(pivot_pd_accessor, "get_ipython", _m_get_ipython)

    # with pytest.warns(UserWarning):
    # Try with variable that already exists
    test_df.mp_pivot.tee(var_name="test_var")
    check.is_none(ipython.ns_table["user_local"]["test_var"])

    test_df.mp_pivot.tee(var_name="test_var", clobber=True)
    print(ipython.ns_table["user_local"]["test_var"])
    print(type(ipython.ns_table["user_local"]["test_var"]))

    check.is_instance(ipython.ns_table["user_local"]["test_var"], pd.DataFrame)
    check.is_true(
        test_df.compare(ipython.ns_table["user_local"]["test_var"]).empty)
Beispiel #23
0
def test_combobox_activated(qtbot):

    record = []

    def set_record(_, b):
        record.append(b)

    delegate = ComboBoxDelegate(None, ["a", "b", "c"])
    delegate.setModelData = set_record

    dummy = QMainWindow()
    cb = delegate.createEditor(dummy, None, None)
    qtbot.addWidget(cb)

    app = QApplication.instance()
    app.setActiveWindow(dummy)
    cb.setFocus()

    cb.activated.emit(12)

    check.is_none(app.focusWidget())
    check_allclose(record, [12])
Beispiel #24
0
def test_account_summary_notebooklet(monkeypatch):
    """Test basic run of notebooklet."""
    test_data = str(Path(TEST_DATA_PATH).absolute())
    monkeypatch.setattr(data_providers, "GeoLiteLookup", GeoIPLiteMock)
    data_providers.init(
        "LocalData",
        providers=["-tilookup"],
        LocalData_data_paths=[test_data],
        LocalData_query_paths=[test_data],
    )

    test_nb = nblts.azsent.account.AccountSummary()
    tspan = TimeSpan(period="1D")

    result = test_nb.run(value="accountname", timespan=tspan)
    check.is_not_none(result.account_selector)
    acct_select = test_nb.browse_accounts()
    check.is_instance(acct_select, nbwidgets.SelectItem)

    select_opts = result.account_selector._item_dict
    disp_account = result.account_selector.item_action
    for acct_item in select_opts.values():
        # Programatically select the item list control
        select_item = [
            key for key, value in select_opts.items() if value == acct_item
        ]
        if select_item:
            result.account_selector._wgt_select.value = select_item[0]
        disp_account(acct_item)
        check.is_instance(result.account_activity, pd.DataFrame)
        check.is_instance(result.related_alerts, pd.DataFrame)
        check.is_instance(result.related_bookmarks, pd.DataFrame)
        check.is_instance(result.alert_timeline, LayoutDOM)
        check.is_instance(result.account_entity, entities.Account)

        alert_select = test_nb.browse_alerts()
        check.is_instance(alert_select, nbwidgets.SelectAlert)
        bm_select = test_nb.browse_bookmarks()
        assert isinstance(bm_select, nbwidgets.SelectItem)

        test_nb.get_additional_data()

        check.is_instance(result.account_timeline_by_ip, LayoutDOM)
        if "Windows" in acct_item or "Linux" in acct_item:
            check.is_instance(result.host_logons, pd.DataFrame)
            check.is_instance(result.host_logon_summary, pd.DataFrame)
            check.is_none(result.azure_activity)
            check.is_none(result.azure_activity_summary)
            check.is_none(result.azure_timeline_by_provider)
            check.is_none(result.azure_timeline_by_operation)
            vwr = result.view_events(
                attrib="host_logons",
                summary_cols=["Computer", "LogonResult", "LogonType"],
            )
        else:
            check.is_none(result.host_logons)
            check.is_none(result.host_logon_summary)
            check.is_instance(result.azure_activity, pd.DataFrame)
            check.is_instance(result.azure_activity_summary, pd.DataFrame)
            check.is_instance(result.azure_timeline_by_provider, LayoutDOM)
            check.is_instance(result.azure_timeline_by_operation, LayoutDOM)
            vwr = result.view_events(
                attrib="azure_activity",
                summary_cols=["Source", "Operation", "IPAddress"],
            )
        check.is_instance(vwr, nbwidgets.SelectItem)

        result.display_alert_timeline()
        result.browse_accounts()
        result.browse_alerts()
        result.browse_bookmarks()
        result.az_activity_timeline_by_provider()
        result.az_activity_timeline_by_ip()
        result.az_activity_timeline_by_operation()
        result.host_logon_timeline()
        check.is_not_none(result.get_geoip_map())
Beispiel #25
0
def test_is_none():
    a = None
    check.is_none(a)
Beispiel #26
0
 def test_init(self):
     """ should instanciate correctly. """
     callbacks = CallbackList(self.callbacks)
     check.equal(callbacks.params, {})
     check.is_none(callbacks.playground)
def test_render():
    # The theory behind test_render is that the unit tests
    # will test whether render() can put underlying changes
    # of the GUI onto the screen correctly.
    # I will be creating a GUI object, rendering it, leaving it on the screen,
    # then killing it. Then, I will change the underlying paramters
    # then re-render another window.

    # In reality, render() cannot be called or else it messes with the
    # travis build. We will have to figure out a better solution
    # in iteration 2.

    # Another side note is that by the point of rendering the window,
    # all the inputs will be valid. This is because the GUI technically
    # limits the users to edit the settings within a valid range. However,
    # invalid inputs will also be included in testing.
    #
    # The majority of invalid input testing will be in set_settings and get_settings.

    # Good inputs (changes in the paratmeters that are valid) are included
    # to test that the GUI does NOT throw an error message when a valid input
    # is given.

    # If an input is invalid, then the GUI will render the default settings in the GUI.

    # Please note that you cannot touch any of the sliders or values in the GUI between test cases.
    # You must either click "Kill this Window" or click the red X to move to the next test case.

    # First, create a test GUI and make sure the default values are correct when generated.
    test_gui = GUI()
    check.equal(test_gui.video_path, '')
    check.equal(test_gui.settings, {
        'conf': .5,
        'poll': 5,
        'anti': 5,
        'runtime': 1,
        'search': []
    })
    check.is_none(test_gui.job)

    # change the video path and settings to some valid input that a user would use
    test_gui.video_path = './test/sampleVideo/SampleVideo_1280x720_1mb.mp4'
    test_gui.set_settings(
        {
            'conf': .5,
            'poll': 3,
            'anti': 1,
            'runtime': 10,
            'search': ['child']
        }, test_gui.video_path)

    # assert that these changes have gone through
    check.equal(test_gui.video_path,
                './test/sampleVideo/SampleVideo_1280x720_1mb.mp4')
    check.equal(
        test_gui.get_settings(), {
            'settings': {
                'conf': .5,
                'poll': 3,
                'anti': 1,
                'runtime': 10,
                'search': ['child']
            },
            'video': './test/sampleVideo/SampleVideo_1280x720_1mb.mp4'
        })
    check.is_none(test_gui.job)

    #test_gui.render()

    # change the video_path, settings, and job to another valid input that a user would use
    test_gui.video_path = './test/sampleVideo/SampleVideo_1280x720_1mb.mp4'
    test_gui.set_settings(
        {
            'conf': 0.2,
            'poll': 1,
            'anti': 1,
            'runtime': 10,
            'search': ["child, kid, ball"]
        }, test_gui.video_path)
    # create a test job object to use as the test_gui.job parameter
    #test_job1 = Job(test_gui.get_settings())
    #test_gui.job = test_job1
    # assert that these changes have gone through
    check.equal(test_gui.video_path,
                './test/sampleVideo/SampleVideo_1280x720_1mb.mp4')
    check.equal(
        test_gui.settings, {
            'conf': 0.2,
            'poll': 1,
            'anti': 1,
            'runtime': 10,
            'search': ["child, kid, ball"]
        })
    #check.equal(test_gui.job, test_job1)

    #test_gui.render()

    # change the video path to a very very long video path.
    test_gui.video_path = './test/sampleVideo/SampleVideo_1280x720_1mb.mp4'
    test_gui.set_settings(test_gui.settings, test_gui.video_path)
    # make sure the other two parameters have not changed, but video path has changed
    check.equal(test_gui.video_path,
                './test/sampleVideo/SampleVideo_1280x720_1mb.mp4')
    check.equal(
        test_gui.settings, {
            'conf': 0.2,
            'poll': 1,
            'anti': 1,
            'runtime': 10,
            'search': ["child, kid, ball"]
        })
    #check.equal(test_gui.job, test_job1)

    #test_gui.render()

    # change the video path to an empty one
    test_gui.video_path = ''
    test_gui.set_settings(test_gui.settings, test_gui.video_path)
    # make sure the correct parameters have changed, and the others have remained the same
    check.equal(test_gui.video_path, '')
    check.equal(
        test_gui.settings, {
            'conf': 0.2,
            'poll': 1,
            'anti': 1,
            'runtime': 10,
            'search': ["child, kid, ball"]
        })
    #check.equal(test_gui.job, test_job1)

    #test_gui.render()

    # change video path to an invalid value or type
    # the point of this test to make sure that the GUI realizes the invalid input
    # and instead displays the default values.
    # Because these types of errors will be caught by the logic unit tests,
    # most of this testing is done in test_set_settings.

    # Below is an invalid input as the video path is a number, not a string
    test_gui.set_settings(
        {
            'conf': 0.2,
            'poll': 1,
            'anti': 1,
            'runtime': 10,
            'search': ["child, kid, ball"]
        }, 2)

    # make sure that the parameters have been reset to the default value.
    check.equal(test_gui.video_path, '')
    check.equal(test_gui.settings, {
        'conf': .5,
        'poll': 5,
        'anti': 5,
        'runtime': 1,
        'search': []
    })
    #check.equal(test_gui.job, test_job1)

    #test_gui.render()

    # Here, we will start testing more levels of the settings parameter in specific.
    # Valid inputs for settings should not throw a GUI error message and
    # instead display the correct image for the GUI.
    # Incorrect inputs for settings should be reset to the default settings and
    # GUI should display the defaults.

    # create a clean new GUI object
    test_gui2 = GUI()

    # change the video_path to a normal one, make sure GUI displays the new settings
    test_gui2.video_path = './test/sampleVideo/SampleVideo_1280x720_1mb.mp4'
    test_gui2.settings = {
        'conf': .75,
        'poll': 571,
        'anti': 462,
        'runtime': 10,
        'search': ["comptuter"]
    }
    test_gui2.set_settings(test_gui2.settings, test_gui2.video_path)
    # make sure that these parameters have been appropriately changed
    check.equal(test_gui2.video_path,
                './test/sampleVideo/SampleVideo_1280x720_1mb.mp4')
    check.equal(
        test_gui2.settings, {
            'conf': .75,
            'poll': 571,
            'anti': 462,
            'runtime': 10,
            'search': ["comptuter"]
        })
    check.is_none(test_gui2.job)

    #test_gui2.render()

    # change the settings used so there are some invalid values (negative settings)
    test_gui2.settings = {
        'conf': -10,
        'poll': -1,
        'anti': -5,
        'runtime': 10,
        'search': ["uhhhh"]
    }
    test_gui2.set_settings(test_gui2.settings, test_gui2.video_path)
    # assert that these changes do not go through and the default settings are implemented
    check.equal(test_gui2.video_path, '')
    check.equal(test_gui2.settings, {
        'conf': .5,
        'poll': 5,
        'anti': 5,
        'runtime': 1,
        'search': []
    })
    check.is_none(test_gui2.job)

    #test_gui2.render()

    # change the settings to the wrong type
    test_gui2.settings = {
        'conf': 'hello',
        'poll': 'nice',
        'anti': 'should not work',
        'runtime': 'woof',
        'search': ["seach term"]
    }
    test_gui2.set_settings(test_gui2.settings, test_gui2.video_path)
    # assert that these changes do not go through and the default settings are rendered
    check.equal(test_gui2.video_path, '')
    check.equal(test_gui2.settings, {
        'conf': .5,
        'poll': 5,
        'anti': 5,
        'runtime': 1,
        'search': []
    })
    check.is_none(test_gui2.job)

    #test_gui2.render()

    # Here, we will be changing the parameters for the job object.
    # All of the following job objects should be valid and should run.

    # create a new GUI object
    test_gui3 = GUI()

    # change the video_path to something other an empty
    test_gui3.video_path = './test/sampleVideo/SampleVideo_1280x720_1mb.mp4'
    # make the settings something valid for set_settings
    test_gui3.settings = {
        'conf': .73,
        'poll': 93,
        'anti': 146,
        'runtime': 10,
        'search': ['boy']
    }
    test_gui3.set_settings(test_gui3.settings, test_gui3.video_path)

    # make sure that the job is empty, and the new settings have been achieved.
    check.equal(test_gui3.video_path,
                './test/sampleVideo/SampleVideo_1280x720_1mb.mp4')
    check.equal(test_gui3.settings, {
        'conf': .73,
        'poll': 93,
        'anti': 146,
        'runtime': 10,
        'search': ['boy']
    })
    check.is_none(test_gui3.job)

    #test_gui3.render()

    # create a new Job object with the updated settings and path.
    #test_job3 = Job({'settings': test_gui3.settings, 'video': test_gui3.video_path})

    # change the value of the GUI's job
    #test_gui3.job = test_job3
    # make sure job has changed, but all the other settings stay the same
    check.equal(test_gui3.video_path,
                './test/sampleVideo/SampleVideo_1280x720_1mb.mp4')
    check.equal(test_gui3.settings, {
        'conf': .73,
        'poll': 93,
        'anti': 146,
        'runtime': 10,
        'search': ['boy']
    })
    #check.equal(test_gui3.job, test_job3)

    #test_gui3.render()

    # change the job back to None
    test_gui3.job = None
    # make sure Job has returned to None, but the other settings remain.
    check.equal(test_gui3.video_path,
                './test/sampleVideo/SampleVideo_1280x720_1mb.mp4')
    check.equal(test_gui3.settings, {
        'conf': .73,
        'poll': 93,
        'anti': 146,
        'runtime': 10,
        'search': ['boy']
    })
    check.is_none(test_gui3.job)
Beispiel #28
0
def test_unit_property_none(unit):
    # Check None and dimensionless_unscaled
    c = DummyClass(unit)
    check.is_none(c._unit)