def test_api_check_failed(self, monkeypatch):
        # force API failure
        class MockSession:
            def get(self, *args, **kwargs):
                raise Exception("The API is broken")

        monkeypatch.setattr(requests, "Session", MockSession)

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(True)
        app.set_cisco_eox_api_queries("yxcz")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        expected_status_message = "<p style=\"text-align: left;\">The following queries were executed:<br>" \
                                  "<ul style=\"text-align: left;\"><li class=\"text-danger\"><code>yxcz</code> " \
                                  "(failed, cannot contact API endpoint at " \
                                  "https://api.cisco.com/supporttools/eox/rest/5/EOXByProductID/1/yxcz)</li></ul></p>"

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_status_message
        assert NotificationMessage.objects.count(
        ) == 1, "Task should create a Notification Message"
        nm = NotificationMessage.objects.first()
        assert nm.type == NotificationMessage.MESSAGE_ERROR, "Should be an error message, because all queries failed"
    def test_manual_task_with_multiple_blacklist_entries(self, monkeypatch):
        self.mock_api_call(monkeypatch)

        # try to execute it, while no auto-sync is enabled
        app = AppSettings()
        app.set_periodic_sync_enabled(False)
        app.set_cisco_eox_api_queries("WS-C2960-*")
        app.set_product_blacklist_regex("WS-C2950G-48-EI-WS;WS-C2950G-24-EI")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay(
            ignore_periodic_sync_flag=True)
        expected_result = [
            '<p style="text-align: left;">The following queries were executed:<br>'
            '<ul style="text-align: left;"><li><code>WS-C2960-*</code> (<b>affects 3 products</b>, '
            'success)</li></ul>'
        ]

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        for er in expected_result:
            assert er in task.info.get("status_message")
        assert NotificationMessage.objects.count(
        ) == 1, "Task should create a Notification Message"
        assert Product.objects.count(
        ) == 1, "Only a single product is imported"
        nm = NotificationMessage.objects.first()
        assert nm.type == NotificationMessage.MESSAGE_SUCCESS, "Incomplete configuration, should throw a warning "
    def test_execute_task_to_synchronize_cisco_eox_states_with_failed_api_query(
            self, monkeypatch):
        def raise_ciscoapicallfailed():
            raise CiscoApiCallFailed("Cisco API call failed message")

        monkeypatch.setattr(utils, "check_cisco_eox_api_access",
                            lambda x, y, z: True)
        monkeypatch.setattr(
            cisco_eox_api_crawler,
            "get_raw_api_data",
            lambda api_query=None, year=None: raise_ciscoapicallfailed())

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(True)
        app.set_cisco_eox_api_queries("yxcz")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        expected_status_message = "<p style=\"text-align: left;\">The following queries were executed:<br>" \
                                  "<ul style=\"text-align: left;\"><li class=\"text-danger\">" \
                                  "<code>yxcz</code> (failed, Cisco API call failed message)</li></ul></p>"

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_status_message
        assert NotificationMessage.objects.count(
        ) == 1, "Task should create a Notification Message"
        nm = NotificationMessage.objects.first()
        assert nm.type == NotificationMessage.MESSAGE_ERROR, "Should be an error message, because all queries failed"
def use_test_api_configuration():
    app = AppSettings()
    with open(CREDENTIALS_FILE) as f:
        content = json.loads(f.read())
    app.set_cisco_api_enabled(True)
    app.set_product_blacklist_regex("")
    app.set_cisco_eox_api_queries("")
    app.set_auto_create_new_products(True)
    app.set_periodic_sync_enabled(False)
    app.set_cisco_api_client_id(content.get("client_id", "dummy_id"))
    app.set_cisco_api_client_id(content.get("client_secret", "dummy_secret"))
def use_test_api_configuration():
    app = AppSettings()
    with open(CREDENTIALS_FILE) as f:
        content = json.loads(f.read())
    app.set_cisco_api_enabled(True)
    app.set_product_blacklist_regex("")
    app.set_cisco_eox_api_queries("")
    app.set_auto_create_new_products(True)
    app.set_periodic_sync_enabled(False)
    app.set_cisco_api_client_id(content.get("client_id", "dummy_id"))
    app.set_cisco_api_client_id(content.get("client_secret", "dummy_secret"))
def use_test_api_configuration():
    app = AppSettings()
    app.set_cisco_api_enabled(True)
    app.set_product_blacklist_regex("")
    app.set_cisco_eox_api_queries("")
    app.set_auto_create_new_products(True)
    app.set_periodic_sync_enabled(False)
    app.set_cisco_api_client_id(
        os.getenv("TEST_CISCO_API_CLIENT_ID", "dummy_id"))
    app.set_cisco_api_client_secret(
        os.getenv("TEST_CISCO_API_CLIENT_SECRET", "dummy_secret"))
    def test_periodic_sync_enabled(self):
        # create new AppSettings object and create defaults
        settings = AppSettings()

        assert settings.is_periodic_sync_enabled() is False

        settings.set_periodic_sync_enabled(True)
        assert settings.is_periodic_sync_enabled() is True

        settings.set_periodic_sync_enabled(False)
        assert settings.is_periodic_sync_enabled() is False
    def test_periodic_sync_enabled(self):
        # create new AppSettings object and create defaults
        settings = AppSettings()

        assert settings.is_periodic_sync_enabled() is False

        settings.set_periodic_sync_enabled(True)
        assert settings.is_periodic_sync_enabled() is True

        settings.set_periodic_sync_enabled(False)
        assert settings.is_periodic_sync_enabled() is False
def mock_cisco_eox_api_access_broken(monkeypatch):
    app = AppSettings()
    app.set_cisco_api_enabled(True)
    app.set_cisco_api_client_id("client_id")
    app.set_cisco_api_client_id("client_secret")
    app.set_periodic_sync_enabled(True)
    app.set_cisco_eox_api_queries("")
    app.set_product_blacklist_regex("")
    app.set_auto_create_new_products(True)

    monkeypatch.setattr(utils, "check_cisco_eox_api_access",
                        lambda client_id, client_secret, drop_credentials=False: False)
예제 #10
0
def mock_cisco_eox_api_access_broken(monkeypatch):
    app = AppSettings()
    app.set_cisco_api_enabled(True)
    app.set_cisco_api_client_id("client_id")
    app.set_cisco_api_client_id("client_secret")
    app.set_periodic_sync_enabled(True)
    app.set_cisco_eox_api_queries("")
    app.set_product_blacklist_regex("")
    app.set_auto_create_new_products(True)

    monkeypatch.setattr(utils, "check_cisco_eox_api_access",
                        lambda client_id, client_secret, drop_credentials=False: False)
예제 #11
0
    def test_manual_task(self, monkeypatch):
        self.mock_api_call(monkeypatch)

        # try to execute it, while no auto-sync is enabled
        app = AppSettings()
        app.set_periodic_sync_enabled(False)
        app.set_cisco_eox_api_queries("WS-C2960-*")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay(ignore_periodic_sync_flag=True)
        expected_result = '<div style="text-align:left;"><h3>Query: WS-C2960-*</h3>The following products are ' \
                          'affected by this update:</p><ul><li>create the Product <code>WS-C2950G-48-EI-WS</code> ' \
                          'in the database</li><li>create the Product <code>WS-C2950T-48-SI-WS</code> in the ' \
                          'database</li><li>create the Product <code>WS-C2950G-24-EI</code> in the database</li>' \
                          '</ul></div>'

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_result
        assert NotificationMessage.objects.count() == 1, "Task should create a Notification Message"
        assert Product.objects.count() == 3, "Three products are part of the update"

        # test no changes required
        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay(ignore_periodic_sync_flag=True)
        expected_result = '<div style="text-align:left;"><h3>Query: WS-C2960-*</h3>No changes required.</div>'

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_result
        assert NotificationMessage.objects.count() == 2, "Task should create a Notification Message"
        assert Product.objects.count() == 3, "Three products are part of the update"

        # test update required
        p = Product.objects.get(product_id="WS-C2950G-24-EI")
        p.eox_update_time_stamp = datetime.date(1999, 1, 1)
        p.save()

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay(ignore_periodic_sync_flag=True)
        expected_result = '<div style="text-align:left;"><h3>Query: WS-C2960-*</h3>The following products are ' \
                          'affected by this update:</p><ul><li>update the Product data for <code>WS-C2950G-24-EI' \
                          '</code></li></ul></div>'

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_result
        assert NotificationMessage.objects.count() == 3, "Task should create a Notification Message"
        assert Product.objects.count() == 3, "Three products are part of the update"
예제 #12
0
    def test_periodic_task_without_queries(self, monkeypatch):
        self.mock_api_call(monkeypatch)

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(True)
        app.set_cisco_eox_api_queries("")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == "No Cisco EoX API queries configured."
        assert NotificationMessage.objects.count() == 1, "Task should create a Notification Message"
예제 #13
0
def test_trigger_manual_cisco_eox_synchronization():
    app_config = AppSettings()

    app_config.set_cisco_api_enabled(True)
    app_config.set_periodic_sync_enabled(True)

    # schedule Cisco EoX API update
    url = reverse('cisco_api:start_cisco_eox_api_sync_now')
    client = Client()
    client.login(username="******", password="******")
    resp = client.get(url)

    assert resp.status_code == 302

    # verify that task ID is saved in the cache (set by the schedule call)
    task_id = cache.get("CISCO_EOX_API_SYN_IN_PROGRESS", "")
    assert task_id != ""
def test_trigger_manual_cisco_eox_synchronization():
    app_config = AppSettings()

    app_config.set_cisco_api_enabled(True)
    app_config.set_periodic_sync_enabled(True)

    # schedule Cisco EoX API update
    url = reverse('cisco_api:start_cisco_eox_api_sync_now')
    client = Client()
    client.login(username="******", password="******")
    resp = client.get(url)

    assert resp.status_code == 302

    # verify that task ID is saved in the cache (set by the schedule call)
    task_id = cache.get("CISCO_EOX_API_SYN_IN_PROGRESS", "")
    assert task_id != ""
    def test_manual_task(self, monkeypatch):
        self.mock_api_call(monkeypatch)

        # try to execute it, while no auto-sync is enabled
        app = AppSettings()
        app.set_periodic_sync_enabled(False)
        app.set_cisco_eox_api_queries("WS-C2960-*")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay(
            ignore_periodic_sync_flag=True)
        expected_result = '<p style="text-align: left;">The following queries were executed:<br>' \
                          '<ul style="text-align: left;"><li><code>WS-C2960-*</code> (<b>affects 3 products</b>, ' \
                          'success)</li></ul></p>'

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_result
        assert NotificationMessage.objects.count(
        ) == 1, "Task should create a Notification Message"
        assert Product.objects.count(
        ) == 3, "Three products are part of the update"

        # test update required
        p = Product.objects.get(product_id="WS-C2950G-24-EI")
        p.eox_update_time_stamp = datetime.date(1999, 1, 1)
        p.save()

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay(
            ignore_periodic_sync_flag=True)
        expected_result = '<p style="text-align: left;">The following queries were executed:<br>' \
                          '<ul style="text-align: left;"><li><code>WS-C2960-*</code> (<b>affects 3 products</b>, ' \
                          'success)</li></ul></p>'

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_result
        assert NotificationMessage.objects.count(
        ) == 2, "Task should create a Notification Message"
        assert Product.objects.count(
        ) == 3, "Three products are part of the update"
예제 #16
0
    def test_api_call_error(self, monkeypatch):
        # force API failure
        def mock_response():
            raise CiscoApiCallFailed("The API is broken")

        monkeypatch.setattr(api_crawler, "update_cisco_eox_database", lambda query: mock_response())

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(True)
        app.set_cisco_eox_api_queries("yxcz")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message", None) is None
        assert task.info.get("error_message") == "Cisco EoX API call failed (The API is broken)"
        assert NotificationMessage.objects.count() == 1, "Task should create a Notification Message"
예제 #17
0
    def test_api_not_reachable_while_task_synchronization(self, monkeypatch):
        monkeypatch.setattr(utils, "check_cisco_eox_api_access", lambda x, y,z: False)
        expected_detail_msg = "The synchronization with the Cisco EoX API was not started."

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(True)
        app.set_cisco_eox_api_queries("yxcz")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message", None) is None
        assert task.info.get("error_message") == "Cannot access the Cisco API. Please ensure that the server is " \
                                                 "connected to the internet and that the authentication settings are " \
                                                 "valid."
        assert NotificationMessage.objects.count() == 1, "Task should create a Notification Message"
        assert NotificationMessage.objects.all().first().detailed_message == expected_detail_msg
    def test_periodic_task_enabled_state(self, monkeypatch):
        self.mock_api_call(monkeypatch)

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(False)
        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == "task not enabled"

        app.set_periodic_sync_enabled(True)

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") != "task not enabled"
예제 #19
0
    def test_credentials_not_found(self, monkeypatch):
        # force API failure
        def mock_response():
            raise CredentialsNotFoundException("Something is wrong with the credentials handling")

        monkeypatch.setattr(api_crawler, "update_cisco_eox_database", lambda query: mock_response())

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(True)
        app.set_cisco_eox_api_queries("yxcz")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message", None) is None
        assert task.info.get("error_message") == "Invalid credentials for Cisco EoX API or insufficient access " \
                                                 "rights (Something is wrong with the credentials handling)"
        assert NotificationMessage.objects.count() == 1, "Task should create a Notification Message"
    def test_periodic_task_enabled_state(self, monkeypatch):
        self.mock_api_call(monkeypatch)

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(False)
        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == "task not enabled"

        app.set_periodic_sync_enabled(True)

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") != "task not enabled"
예제 #21
0
    def test_manual_task_with_multiple_blacklist_entries(self, monkeypatch):
        self.mock_api_call(monkeypatch)

        # try to execute it, while no auto-sync is enabled
        app = AppSettings()
        app.set_periodic_sync_enabled(False)
        app.set_cisco_eox_api_queries("WS-C2960-*")
        app.set_product_blacklist_regex("WS-C2950G-48-EI-WS;WS-C2950G-24-EI")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay(ignore_periodic_sync_flag=True)
        expected_result = '<div style="text-align:left;"><h3>Query: WS-C2960-*</h3>The following products are ' \
                          'affected by this update:</p><ul><li>Product data for <code>WS-C2950G-48-EI-WS</code> ' \
                          'ignored</li><li>create the Product <code>WS-C2950T-48-SI-WS</code> in the ' \
                          'database</li><li>Product data for <code>WS-C2950G-24-EI</code> ignored</li>' \
                          '</ul></div>'

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message") == expected_result
        assert NotificationMessage.objects.count() == 1, "Task should create a Notification Message"
        assert Product.objects.count() == 1, "Only a single product is imported"
예제 #22
0
    def test_api_check_failed(self, monkeypatch):
        # force API failure
        def mock_response():
            raise Exception("The API is broken")

        monkeypatch.setattr(requests, "get", lambda x, headers: mock_response())

        # test automatic trigger
        app = AppSettings()
        app.set_periodic_sync_enabled(True)
        app.set_cisco_eox_api_queries("yxcz")

        task = tasks.execute_task_to_synchronize_cisco_eox_states.delay()

        assert task is not None
        assert task.status == "SUCCESS", task.traceback
        assert task.state == TaskState.SUCCESS
        assert task.info.get("status_message", None) is None
        assert task.info.get("error_message") == "Cannot access the Cisco API. Please ensure that the server is " \
                                                 "connected to the internet and that the authentication settings are " \
                                                 "valid."
        assert NotificationMessage.objects.count() == 1, "Task should create a Notification Message"
예제 #23
0
def change_configuration(request):
    """
    change configuration of the Product Database
    """
    # read settings from configuration file
    app_config = AppSettings()

    # read settings from database
    hp_content_after, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_AFTER_FAVORITE_ACTIONS
    )
    hp_content_before, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_BEFORE_FAVORITE_ACTIONS
    )

    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        form = SettingsForm(request.POST)
        if form.is_valid():
            # set common settings
            app_config.set_login_only_mode(form.cleaned_data["login_only_mode"])

            hp_content_before.html_content = form.cleaned_data["homepage_text_before"]
            hp_content_before.save()
            hp_content_after.html_content = form.cleaned_data["homepage_text_after"]
            hp_content_after.save()

            # set the Cisco API configuration options
            api_enabled = form.cleaned_data["cisco_api_enabled"]

            if not api_enabled:
                # api is disabled, reset values to default
                app_config.set_cisco_api_enabled(api_enabled)
                app_config.set_cisco_api_client_id("PlsChgMe")
                app_config.set_cisco_api_client_secret("PlsChgMe")
                app_config.set_periodic_sync_enabled(False)
                app_config.set_auto_create_new_products(False)
                app_config.set_cisco_eox_api_queries("")
                app_config.set_product_blacklist_regex("")
                app_config.set_cisco_eox_api_sync_wait_time("5")

            else:
                app_config.set_cisco_api_enabled(api_enabled)

                client_id = form.cleaned_data["cisco_api_client_id"] \
                    if form.cleaned_data["cisco_api_client_id"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_id(client_id)
                client_secret = form.cleaned_data["cisco_api_client_secret"] \
                    if form.cleaned_data["cisco_api_client_secret"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_secret(client_secret)

                app_config.set_internal_product_id_label(form.cleaned_data["internal_product_id_label"])
                app_config.set_periodic_sync_enabled(form.cleaned_data["eox_api_auto_sync_enabled"])
                app_config.set_auto_create_new_products(form.cleaned_data["eox_auto_sync_auto_create_elements"])
                app_config.set_cisco_eox_api_queries(form.cleaned_data["eox_api_queries"])
                app_config.set_product_blacklist_regex(form.cleaned_data["eox_api_blacklist"])
                if form.cleaned_data["eox_api_wait_time"]:
                    app_config.set_cisco_eox_api_sync_wait_time(form.cleaned_data["eox_api_wait_time"])

                if client_id != "PlsChgMe":
                    result = utils.check_cisco_eox_api_access(
                        form.cleaned_data["cisco_api_client_id"],
                        form.cleaned_data["cisco_api_client_secret"]
                    )

                    if result:
                        messages.success(request, "Successfully connected to the Cisco EoX API")

                    else:
                        messages.error(request, "Cannot contact the Cisco EoX API. Please contact your "
                                                "Administrator")

                else:
                    messages.info(
                        request,
                        "Please configure your Cisco API credentials within the Cisco API settings tab."
                    )

            # expire cached settings
            cache.delete("LOGIN_ONLY_MODE_SETTING")

            messages.success(request, "Settings saved successfully")
            return redirect(resolve_url("productdb_config:change_settings"))

        else:
            messages.error(request, "Invalid configuration option detected, please check it below.")

    else:
        form = SettingsForm()
        form.fields['cisco_api_enabled'].initial = app_config.is_cisco_api_enabled()
        form.fields['login_only_mode'].initial = app_config.is_login_only_mode()
        form.fields['internal_product_id_label'].initial = app_config.get_internal_product_id_label()
        form.fields['cisco_api_client_id'].initial = app_config.get_cisco_api_client_id()
        form.fields['cisco_api_client_secret'].initial = app_config.get_cisco_api_client_secret()
        form.fields['eox_api_auto_sync_enabled'].initial = app_config.is_periodic_sync_enabled()
        form.fields['eox_auto_sync_auto_create_elements'].initial = app_config.is_auto_create_new_products()
        form.fields['eox_api_queries'].initial = app_config.get_cisco_eox_api_queries()
        form.fields['eox_api_blacklist'].initial = app_config.get_product_blacklist_regex()
        form.fields['eox_api_wait_time'].initial = app_config.get_cisco_eox_api_sync_wait_time()
        form.fields['homepage_text_before'].initial = hp_content_before.html_content
        form.fields['homepage_text_after'].initial = hp_content_after.html_content

    context = {
        "form": form,
        "is_cisco_api_enabled": app_config.is_cisco_api_enabled(),
        "is_cisco_eox_api_auto_sync_enabled": app_config.is_periodic_sync_enabled()
    }
    return render(request, "config/change_configuration.html", context=context)
    def test_populate_flag_on_cisco_products(self):
        app_config = AppSettings()
        v = Vendor.objects.get(id=1)
        productdb_models.Product.objects.create(product_id="est",
                                                vendor=v,
                                                lc_state_sync=False)
        productdb_models.Product.objects.create(product_id="Test",
                                                vendor=v,
                                                lc_state_sync=False)
        productdb_models.Product.objects.create(product_id="TestA",
                                                vendor=v,
                                                lc_state_sync=False)
        productdb_models.Product.objects.create(product_id="TestB",
                                                vendor=v,
                                                lc_state_sync=False)
        productdb_models.Product.objects.create(product_id="TestC",
                                                vendor=v,
                                                lc_state_sync=False)
        productdb_models.Product.objects.create(product_id="ControlItem",
                                                vendor=v,
                                                lc_state_sync=False)

        # the following item is part of every query, but is never synced because of the wrong vendor
        productdb_models.Product.objects.create(product_id="Other ControlItem",
                                                lc_state_sync=False)

        app_config.set_cisco_eox_api_queries("")
        app_config.set_periodic_sync_enabled(True)

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()

        assert result.status == "SUCCESS"
        assert Product.objects.filter(
            lc_state_sync=True).count() == 0, "No queries configured"

        app_config.set_cisco_eox_api_queries("Test\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)

        assert result.status == "SUCCESS"
        assert list(
            filterquery.order_by("id").values_list("product_id",
                                                   flat=True)) == ["Test"]

        app_config.set_cisco_eox_api_queries("Test*\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "Test",
            "TestA",
            "TestB",
            "TestC",
        ]

        assert result.status == "SUCCESS"
        assert list(
            filterquery.order_by("id").values_list(
                "product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*estB\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "TestB",
        ]

        assert result.status == "SUCCESS"
        assert list(
            filterquery.order_by("id").values_list(
                "product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*estB\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "TestB",
        ]

        assert result.status == "SUCCESS"
        assert list(
            filterquery.order_by("id").values_list(
                "product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*es*\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "est",
            "Test",
            "TestA",
            "TestB",
            "TestC",
        ]

        assert result.status == "SUCCESS"
        assert list(
            filterquery.order_by("id").values_list(
                "product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*es*\nOther ControlItem")
        app_config.set_periodic_sync_enabled(False)

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)

        assert result.status == "SUCCESS"
        assert filterquery.count(
        ) == 0, "Periodic sync disabled, no value should be true"
예제 #25
0
def change_configuration(request):
    """
    change configuration of the Product Database
    """
    # read settings from configuration file
    app_config = AppSettings()

    # read settings from database
    hp_content_after, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_AFTER_FAVORITE_ACTIONS
    )
    hp_content_before, _ = TextBlock.objects.get_or_create(
        name=TextBlock.TB_HOMEPAGE_TEXT_BEFORE_FAVORITE_ACTIONS
    )

    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        form = SettingsForm(request.POST)
        if form.is_valid():
            # set common settings
            app_config.set_login_only_mode(form.cleaned_data["login_only_mode"])

            hp_content_before.html_content = form.cleaned_data["homepage_text_before"]
            hp_content_before.save()
            hp_content_after.html_content = form.cleaned_data["homepage_text_after"]
            hp_content_after.save()

            # set the Cisco API configuration options
            api_enabled = form.cleaned_data["cisco_api_enabled"]

            if not api_enabled:
                # api is disabled, reset values to default
                app_config.set_cisco_api_enabled(api_enabled)
                app_config.set_cisco_api_client_id("PlsChgMe")
                app_config.set_cisco_api_client_secret("PlsChgMe")
                app_config.set_periodic_sync_enabled(False)
                app_config.set_auto_create_new_products(False)
                app_config.set_cisco_eox_api_queries("")
                app_config.set_product_blacklist_regex("")
                app_config.set_cisco_eox_api_sync_wait_time("5")

            else:
                app_config.set_cisco_api_enabled(api_enabled)

                client_id = form.cleaned_data["cisco_api_client_id"] \
                    if form.cleaned_data["cisco_api_client_id"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_id(client_id)
                client_secret = form.cleaned_data["cisco_api_client_secret"] \
                    if form.cleaned_data["cisco_api_client_secret"] != "" else "PlsChgMe"
                app_config.set_cisco_api_client_secret(client_secret)

                if client_id != "PlsChgMe":
                    result = utils.check_cisco_eox_api_access(
                        form.cleaned_data["cisco_api_client_id"],
                        form.cleaned_data["cisco_api_client_secret"]
                    )

                    if result:
                        messages.success(request, "Successfully connected to the Cisco EoX API")

                    else:
                        messages.error(request, "Cannot contact the Cisco EoX API. Please contact your "
                                                "Administrator")

                else:
                    messages.info(
                        request,
                        "Please configure your Cisco API credentials within the Cisco API settings tab."
                    )

                app_config.set_periodic_sync_enabled(form.cleaned_data["eox_api_auto_sync_enabled"])
                app_config.set_internal_product_id_label(form.cleaned_data["internal_product_id_label"])
                app_config.set_auto_create_new_products(form.cleaned_data["eox_auto_sync_auto_create_elements"])
                app_config.set_cisco_eox_api_queries(form.cleaned_data["eox_api_queries"])
                app_config.set_product_blacklist_regex(form.cleaned_data["eox_api_blacklist"])
                if form.cleaned_data["eox_api_wait_time"]:
                    app_config.set_cisco_eox_api_sync_wait_time(form.cleaned_data["eox_api_wait_time"])

            # expire cached settings
            cache.delete("LOGIN_ONLY_MODE_SETTING")

            messages.success(request, "Settings saved successfully")
            return redirect(resolve_url("productdb_config:change_settings"))

        else:
            messages.error(request, "Invalid configuration option detected, please check it below.")

    else:
        form = SettingsForm()
        form.fields['cisco_api_enabled'].initial = app_config.is_cisco_api_enabled()
        form.fields['login_only_mode'].initial = app_config.is_login_only_mode()
        form.fields['internal_product_id_label'].initial = app_config.get_internal_product_id_label()
        form.fields['cisco_api_client_id'].initial = app_config.get_cisco_api_client_id()
        form.fields['cisco_api_client_secret'].initial = app_config.get_cisco_api_client_secret()
        form.fields['eox_api_auto_sync_enabled'].initial = app_config.is_periodic_sync_enabled()
        form.fields['eox_auto_sync_auto_create_elements'].initial = app_config.is_auto_create_new_products()
        form.fields['eox_api_queries'].initial = app_config.get_cisco_eox_api_queries()
        form.fields['eox_api_blacklist'].initial = app_config.get_product_blacklist_regex()
        form.fields['eox_api_wait_time'].initial = app_config.get_cisco_eox_api_sync_wait_time()
        form.fields['homepage_text_before'].initial = hp_content_before.html_content
        form.fields['homepage_text_after'].initial = hp_content_after.html_content

    context = {
        "form": form,
        "is_cisco_api_enabled": app_config.is_cisco_api_enabled(),
        "is_cisco_eox_api_auto_sync_enabled": app_config.is_periodic_sync_enabled()
    }
    return render(request, "config/change_configuration.html", context=context)
    def test_populate_flag_on_cisco_products(self):
        app_config = AppSettings()
        v = Vendor.objects.get(id=1)
        mixer.blend("productdb.Product", product_id="est", vendor=v, lc_state_sync=False)
        mixer.blend("productdb.Product", product_id="Test", vendor=v, lc_state_sync=False)
        mixer.blend("productdb.Product", product_id="TestA", vendor=v, lc_state_sync=False)
        mixer.blend("productdb.Product", product_id="TestB", vendor=v, lc_state_sync=False)
        mixer.blend("productdb.Product", product_id="TestC", vendor=v, lc_state_sync=False)
        mixer.blend("productdb.Product", product_id="ControlItem", vendor=v, lc_state_sync=False)

        # the following item is part of every query, but is never synced because of the wrong vendor
        mixer.blend("productdb.Product", product_id="Other ControlItem", lc_state_sync=False)

        app_config.set_cisco_eox_api_queries("")
        app_config.set_periodic_sync_enabled(True)

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()

        assert result.status == "SUCCESS"
        assert Product.objects.filter(lc_state_sync=True).count() == 0, "No queries configured"

        app_config.set_cisco_eox_api_queries("Test\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)

        assert result.status == "SUCCESS"
        assert list(filterquery.order_by("id").values_list("product_id", flat=True)) == ["Test"]

        app_config.set_cisco_eox_api_queries("Test*\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "Test",
            "TestA",
            "TestB",
            "TestC",
        ]

        assert result.status == "SUCCESS"
        assert list(filterquery.order_by("id").values_list("product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*estB\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "TestB",
        ]

        assert result.status == "SUCCESS"
        assert list(filterquery.order_by("id").values_list("product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*estB\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "TestB",
        ]

        assert result.status == "SUCCESS"
        assert list(filterquery.order_by("id").values_list("product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*es*\nOther ControlItem")

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)
        expected_result_list = [
            "est",
            "Test",
            "TestA",
            "TestB",
            "TestC",
        ]

        assert result.status == "SUCCESS"
        assert list(filterquery.order_by("id").values_list("product_id", flat=True)) == expected_result_list

        app_config.set_cisco_eox_api_queries("*es*\nOther ControlItem")
        app_config.set_periodic_sync_enabled(False)

        result = tasks.cisco_eox_populate_product_lc_state_sync_field.delay()
        filterquery = Product.objects.filter(lc_state_sync=True)

        assert result.status == "SUCCESS"
        assert filterquery.count() == 0, "Periodic sync disabled, no value should be true"