diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py index da4891e1..c5457ed8 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/datafileupdate_console.py @@ -206,11 +206,12 @@ # example. CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-datafileupdate_console.py&utm_term=licence-key" DEFAULT_DATA_FILENAME = os.path.expanduser("~") + os.path.sep + ENTERPRISE_DATAFILE_NAME -# The product asked of the 51Degrees distributor when no other is given, -# which is the Enterprise data file. A license key for another product needs -# that product given as the third command line argument, such as V4TAC for -# the TAC data file. -DATA_UPDATE_PRODUCT_TYPE = "V4Enterprise" +# The product asked of the 51Degrees distributor when none is given as the +# third command line argument. It is None, so no product is named and the +# distributor serves the product the license key holds. A license key that +# holds several products needs the one wanted to be given, such as +# V4Enterprise for the Enterprise data file or V4TAC for the TAC data file. +DATA_UPDATE_PRODUCT_TYPE = None # Where to go next, printed when the example ends. FIND_OUT_MORE = [ @@ -419,8 +420,10 @@ def run(self, data_file, license_key, interactive, logger, output, product = Non # Watch the data file on disk and refresh the engine # as soon as that file is updated. file_system_watcher=True, - # The product the license key holds, which the 51Degrees - # distributor is asked for. + # The product the 51Degrees distributor is asked for, which + # is named only when this example is given one. With none + # given no product is named, and the distributor serves the + # product the license key holds. data_update_product_type = product if product else DATA_UPDATE_PRODUCT_TYPE, ).add_logger(logger).build() @@ -474,8 +477,8 @@ def main(argv): # file that is included in the repository. license_key = argv[0] if len(argv) > 0 else None data_file = argv[1] if len(argv) > 1 else None - # The product the license key holds, when it is not the Enterprise - # data file. + # The product to ask for, which a license key that holds several + # products needs. With none given, no product is named. product = argv[2] if len(argv) > 2 else None # Configure a logger to output to the console. diff --git a/device-detection/fiftyone_devicedetection_examples/tests/test_datafileupdate_product.py b/device-detection/fiftyone_devicedetection_examples/tests/test_datafileupdate_product.py new file mode 100644 index 00000000..343c3080 --- /dev/null +++ b/device-detection/fiftyone_devicedetection_examples/tests/test_datafileupdate_product.py @@ -0,0 +1,99 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +# The data file update example names a product to the 51Degrees distributor +# only when it is given one. With none given it names none, so a license key +# that holds one product is served that product. No pipeline is built and +# nothing is downloaded, so these tests need no license key and no data +# file. + +import os +import tempfile +import unittest +from unittest import mock + +from fiftyone_devicedetection_examples.example_utils import ExampleUtils +from fiftyone_devicedetection_examples.onpremise import datafileupdate_console +from fiftyone_pipeline_core.logger import Logger + +# Stands in for a license key. No request is made with it. +KEY = "ABCDEFGHIJKL" + + +class Stop(Exception): + """Ends the example where it would build the pipeline that updates the + data file.""" + + +def settings_given(*product): + """Runs the example to the point where it builds the pipeline that + updates the data file, and returns the settings it gave the pipeline + builder. The data file is one that does not exist, in a directory that + does, so the example builds no other pipeline first.""" + builder = mock.Mock(side_effect=Stop()) + with tempfile.TemporaryDirectory() as directory: + location = os.path.join(directory, "not-there.hash") + with mock.patch.object( + datafileupdate_console, "DeviceDetectionPipelineBuilder", + builder), mock.patch.object( + ExampleUtils, "find_file", return_value=location): + try: + datafileupdate_console.DataFileUpdateConsole().run( + location, KEY, False, Logger(min_level="error"), + lambda text: None, *product) + except Stop: + pass + if builder.call_count != 1: + raise AssertionError( + "The example built " + str(builder.call_count) + " pipelines") + return builder.call_args[1] + + +class DataFileUpdateProductTests(unittest.TestCase): + + def test_a_product_given_is_the_product_asked_for(self): + settings = settings_given("V4TAC") + self.assertEqual("V4TAC", settings["data_update_product_type"]) + self.assertEqual(KEY, settings["licence_keys"]) + + def test_no_product_is_asked_for_when_none_is_given(self): + for name, product in ( + ("no argument", ()), ("none", (None,)), ("empty", ("",))): + with self.subTest(name): + self.assertIsNone( + settings_given(*product).get("data_update_product_type")) + + def test_the_third_argument_is_the_product(self): + for name, argv, product in ( + ("given", [KEY, "a.hash", "V4TAC"], "V4TAC"), + ("not given", [KEY, "a.hash"], None)): + with self.subTest(name): + with mock.patch.object( + datafileupdate_console.DataFileUpdateConsole, + "run") as run, mock.patch.object( + ExampleUtils, "print_find_out_more"): + datafileupdate_console.main(argv) + self.assertEqual(product, run.call_args[0][-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_datafile.py b/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_datafile.py index c12f36e7..b80974d2 100644 --- a/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_datafile.py +++ b/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_datafile.py @@ -58,10 +58,14 @@ def get_url_formatter(self): if not self._data_update_use_url_formatter: return self.update_url_params["base_url"] + # A product is named only when one is configured, and then every + # request carries it. With none configured the URL has no Product + # parameter at all, so a license key that holds one product is + # served that product. query_params = { "Type": self.update_url_params["type"], "licenseKeys": self.update_url_params.get("license_keys"), - "Product": self.update_url_params.get("product") + "Product": self.update_url_params.get("product") or None } # Remove keys with None values diff --git a/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py b/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py index 1ddf8983..4608e3a2 100644 --- a/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py +++ b/device-detection/fiftyone_devicedetection_onpremise/src/fiftyone_devicedetection_onpremise/devicedetection_onpremise.py @@ -153,6 +153,8 @@ def __init__( @param use_predictive_graph: True if the predictive optimized graph should be used for processing @param data_update_use_url_formatter: This must be set to false to prevent the API from appending the query string parameters that are required when calling the 51Degrees Distributor service. @type data_update_use_url_formatter: bool + @param data_update_product_type: The product to ask the 51Degrees Distributor for, such as V4TAC. When one is given, every request for a data file names it. When none is given, no request names a product unless the Distributor asks which of several is wanted, and the product of the data file in use is then named. + @type data_update_product_type: string """ diff --git a/device-detection/fiftyone_devicedetection_onpremise/tests/test_data_update_product.py b/device-detection/fiftyone_devicedetection_onpremise/tests/test_data_update_product.py index ed18c496..e55813a8 100644 --- a/device-detection/fiftyone_devicedetection_onpremise/tests/test_data_update_product.py +++ b/device-detection/fiftyone_devicedetection_onpremise/tests/test_data_update_product.py @@ -68,5 +68,40 @@ def test_no_product_is_named_before_a_data_file_is_loaded(self): data_file(flow_element).get_data_update_product()) +def formatted(product): + """The update URL the URL formatter writes for a data file that is + configured with the product.""" + return DeviceDetectionDataFile( + flow_element=SimpleNamespace(), identifier="HashV41", + path="not-read.hash", data_update_use_url_formatter=True, + update_url_params={ + "base_url": "https://example.com/update", + "type": "HashV41", + "license_keys": "ABCDEFGHIJKL", + "product": product}).get_update_url() + + +# A product is named in the update URL only when one is configured. Every +# request is made to that URL, so with a product configured every request +# names it, the first included, and with none configured the first request +# has no Product parameter at all. +class ConfiguredProductTests(unittest.TestCase): + + def test_a_configured_product_is_named_in_the_update_url(self): + self.assertEqual( + "https://example.com/update?Type=HashV41&" + "licenseKeys=ABCDEFGHIJKL&Product=V4TAC", + formatted("V4TAC")) + + def test_no_product_is_named_when_none_is_configured(self): + for name, product in (("none", None), ("empty", "")): + with self.subTest(name): + url = formatted(product) + self.assertEqual( + "https://example.com/update?Type=HashV41&" + "licenseKeys=ABCDEFGHIJKL", url) + self.assertNotIn("product", url.lower()) + + if __name__ == "__main__": unittest.main() diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/readme.md b/ip-intelligence/fiftyone_ipintelligence_examples/readme.md index 4f6e8cc6..4d04039b 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/readme.md +++ b/ip-intelligence/fiftyone_ipintelligence_examples/readme.md @@ -85,7 +85,7 @@ python -m fiftyone_ipintelligence_examples.onpremise.countries_console [data-fil python -m fiftyone_ipintelligence_examples.onpremise.offlineprocessing [data-file [evidence-file]] python -m fiftyone_ipintelligence_examples.onpremise.performance_console [-d data-file] [-e evidence-file] python -m fiftyone_ipintelligence_examples.onpremise.compare_console [-d data-file] [-t truth-file] -python -m fiftyone_ipintelligence_examples.onpremise.datafileupdate_console [license-key [data-file]] +python -m fiftyone_ipintelligence_examples.onpremise.datafileupdate_console [license-key [data-file [product]]] python -m fiftyone_ipintelligence_examples.onpremise.mixed_console [hash-file [ipi-file]] python -m fiftyone_ipintelligence_examples.onpremise.gettingstarted_web ``` diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py index 76bb0180..abbe7dfe 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/onpremise/datafileupdate_console.py @@ -93,10 +93,12 @@ # example. CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_ipintelligence_examples-src-fiftyone_ipintelligence_examples-onpremise-datafileupdate_console.py&utm_term=licence-key" -# The product type passed to the 51Degrees distributor. This identifies the -# IP intelligence Enterprise product and may need to be adjusted to match -# the product your license entitles you to. -DATA_UPDATE_PRODUCT_TYPE = "IPIV4Enterprise" +# The product asked of the 51Degrees distributor when none is given as the +# third command line argument. It is None, so no product is named and the +# distributor serves the product the license key holds. A license key that +# holds several products needs the one wanted to be given, such as +# IPIV4Enterprise for the Enterprise data file. +DATA_UPDATE_PRODUCT_TYPE = None DEFAULT_DATA_FILENAME = os.path.join( os.path.expanduser("~"), ENTERPRISE_DATAFILE_NAME) @@ -212,7 +214,7 @@ def update_programmatically(self, data_file, output): finally: shutil.rmtree(directory, ignore_errors=True) - def run(self, data_file, license_key, interactive, logger, output): + def run(self, data_file, license_key, interactive, logger, output, product = None): logger.log("info", "Starting example") # Try to find a license key in the environment if not supplied. @@ -282,7 +284,11 @@ def run(self, data_file, license_key, interactive, logger, output): auto_update = True, # Reload automatically when the data file on disk changes. file_system_watcher = True, - data_update_product_type = DATA_UPDATE_PRODUCT_TYPE, + # The product the 51Degrees distributor is asked for, which is + # named only when this example is given one. With none given no + # product is named, and the distributor serves the product the + # license key holds. + data_update_product_type = product if product else DATA_UPDATE_PRODUCT_TYPE, # Usage sharing is off for this example. In production turn it on, # because the requests shared improve the data every user gets. usage_sharing = False).add_logger(logger).build() @@ -330,11 +336,14 @@ def run(self, data_file, license_key, interactive, logger, output): def main(argv): license_key = argv[0] if len(argv) > 0 else None data_file = argv[1] if len(argv) > 1 else None + # The product to ask for, which a license key that holds several + # products needs. With none given, no product is named. + product = argv[2] if len(argv) > 2 else None # Configure a logger to output to the console. logger = Logger(min_level="info") - DataFileUpdateConsole().run(data_file, license_key, True, logger, print) + DataFileUpdateConsole().run(data_file, license_key, True, logger, print, product) # Printed however the example ended, whether it updated the data file, # had no licence key, or was stopped before the download. diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_datafileupdate_product.py b/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_datafileupdate_product.py new file mode 100644 index 00000000..093feda3 --- /dev/null +++ b/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_datafileupdate_product.py @@ -0,0 +1,100 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +# The data file update example names a product to the 51Degrees distributor +# only when it is given one. With none given it names none, so a license key +# that holds one product is served that product. No pipeline is built and +# nothing is downloaded, so these tests need no license key and no data +# file. + +import os +import tempfile +import unittest +from unittest import mock + +from fiftyone_ipintelligence_examples.example_utils import ExampleUtils +from fiftyone_ipintelligence_examples.onpremise import datafileupdate_console +from fiftyone_pipeline_core.logger import Logger + +# Stands in for a license key. No request is made with it. +KEY = "ABCDEFGHIJKL" + + +class Stop(Exception): + """Ends the example where it would build the pipeline that updates the + data file.""" + + +def settings_given(*product): + """Runs the example to the point where it builds the pipeline that + updates the data file, and returns the settings it gave the pipeline + builder. The data file is one that does not exist, in a directory that + does, so the example copies no file first.""" + builder = mock.Mock(side_effect=Stop()) + with tempfile.TemporaryDirectory() as directory: + location = os.path.join(directory, "not-there.ipi") + with mock.patch.object( + datafileupdate_console, "IpIntelligencePipelineBuilder", + builder): + try: + datafileupdate_console.DataFileUpdateConsole().run( + location, KEY, False, Logger(min_level="error"), + lambda text: None, *product) + except Stop: + pass + if builder.call_count != 1: + raise AssertionError( + "The example built " + str(builder.call_count) + " pipelines") + return builder.call_args[1] + + +class DataFileUpdateProductTests(unittest.TestCase): + + def test_a_product_given_is_the_product_asked_for(self): + settings = settings_given("IPIV4Enterprise") + self.assertEqual( + "IPIV4Enterprise", settings["data_update_product_type"]) + self.assertEqual(KEY, settings["licence_keys"]) + + def test_no_product_is_asked_for_when_none_is_given(self): + for name, product in ( + ("no argument", ()), ("none", (None,)), ("empty", ("",))): + with self.subTest(name): + self.assertIsNone( + settings_given(*product).get("data_update_product_type")) + + def test_the_third_argument_is_the_product(self): + for name, argv, product in ( + ("given", [KEY, "a.ipi", "IPIV4Enterprise"], + "IPIV4Enterprise"), + ("not given", [KEY, "a.ipi"], None)): + with self.subTest(name): + with mock.patch.object( + datafileupdate_console.DataFileUpdateConsole, + "run") as run, mock.patch.object( + ExampleUtils, "print_find_out_more"): + datafileupdate_console.main(argv) + self.assertEqual(product, run.call_args[0][-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_datafile.py b/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_datafile.py index 72318026..8ef1ede2 100644 --- a/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_datafile.py +++ b/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_datafile.py @@ -53,10 +53,14 @@ def get_url_formatter(self): if not self._data_update_use_url_formatter: return self.update_url_params["base_url"] + # A product is named only when one is configured, and then every + # request carries it. With none configured the URL has no Product + # parameter at all, so a license key that holds one product is + # served that product. query_params = { "Type": self.update_url_params["type"], "licenseKeys": self.update_url_params.get("license_keys"), - "Product": self.update_url_params.get("product") + "Product": self.update_url_params.get("product") or None } # Remove keys with None values diff --git a/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py b/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py index 425ed21e..d41f604c 100644 --- a/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py +++ b/ip-intelligence/fiftyone_ipintelligence_onpremise/src/fiftyone_ipintelligence_onpremise/ipintelligence_onpremise.py @@ -123,6 +123,8 @@ def __init__( @param data_update_url: base url for the datafile update service @param data_update_use_url_formatter: This must be set to false to prevent the API from appending the query string parameters that are required when calling the 51Degrees Distributor service. @type data_update_use_url_formatter: bool + @param data_update_product_type: The product to ask the 51Degrees Distributor for, such as IPIV4Enterprise. When one is given, every request for a data file names it. When none is given, no request names a product unless the Distributor asks which of several is wanted, and the product of the data file in use is then named. + @type data_update_product_type: string """ diff --git a/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_data_update_product.py b/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_data_update_product.py index 2f7f415c..1f2dcf3c 100644 --- a/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_data_update_product.py +++ b/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_data_update_product.py @@ -67,5 +67,40 @@ def test_no_product_is_named_before_a_data_file_is_loaded(self): data_file(flow_element).get_data_update_product()) +def formatted(product): + """The update URL the URL formatter writes for a data file that is + configured with the product.""" + return IpIntelligenceDataFile( + flow_element=SimpleNamespace(), identifier="IPIV41", + path="not-read.ipi", data_update_use_url_formatter=True, + update_url_params={ + "base_url": "https://example.com/update", + "type": "IPIV41", + "license_keys": "ABCDEFGHIJKL", + "product": product}).get_update_url() + + +# A product is named in the update URL only when one is configured. Every +# request is made to that URL, so with a product configured every request +# names it, the first included, and with none configured the first request +# has no Product parameter at all. +class ConfiguredProductTests(unittest.TestCase): + + def test_a_configured_product_is_named_in_the_update_url(self): + self.assertEqual( + "https://example.com/update?Type=IPIV41&" + "licenseKeys=ABCDEFGHIJKL&Product=IPIV4Enterprise", + formatted("IPIV4Enterprise")) + + def test_no_product_is_named_when_none_is_configured(self): + for name, product in (("none", None), ("empty", "")): + with self.subTest(name): + url = formatted(product) + self.assertEqual( + "https://example.com/update?Type=IPIV41&" + "licenseKeys=ABCDEFGHIJKL", url) + self.assertNotIn("product", url.lower()) + + if __name__ == "__main__": unittest.main() diff --git a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py index 80c3c4e1..2ad0c757 100644 --- a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py +++ b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile.py @@ -130,7 +130,8 @@ def get_data_update_product(self): the data update service names it. A license key can hold several products, and the data update service then asks which one is wanted by answering with the products it offers. The data file update - service picks the one this function returns. + service then makes its request again with the one this function + returns named in it. @returns string: Name of the product, or None when the data file names none, which is the default """ diff --git a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py index c07d241e..2a1cf4f3 100644 --- a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py +++ b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/datafile_update_service.py @@ -31,7 +31,7 @@ import random import threading import time -from urllib.parse import parse_qsl, urljoin, urlsplit +from urllib.parse import parse_qsl, quote, urlsplit, urlunsplit import warnings import zlib import requests @@ -296,21 +296,30 @@ def _update_data_file(self, data_file): # A request that names no product, made with a license key that # holds several, is answered with status 300 and a URI for each - # product. The check carries on at the URI of the product the data - # file in use is of. A key that holds one product never gets this - # answer, so its check is the one request it always was. - if response.status_code == 300: + # product, as the License Keys with several products section of the + # data updates specification says. Only the name of the product is + # read from the answer. The request is then made again, to the same + # URL with that product named and with the same headers, so it + # still goes to the data update URL the data file gives. The answer + # to it is handled as the answer to a first request is, so another + # 300 is not followed and ends the check as any other status does. + # A key that holds one product never gets this answer, so its check + # is the one request it always was. + # When a product is configured, the data update URL names it, so + # every request carries it, the first included. Such a request is + # never made again. An answer of status 300 to it ends the check as + # any other status does, as it does for a second request. + if response.status_code == 300 and not self._names_product(url): offered = self._offered_products(response) if offered: - product, uri = self._offered_product( + product = self._offered_product( data_file, offered, shown_url, engine) - url = urljoin(url, uri) - shown_url = mask_licence_keys_in_text(url) self._log( "info", - "The license key holds several products. Checking for " - "update to product '" + product + "' from '" + + "Requesting product '" + product + "' from '" + shown_url + "' for Engine '" + engine + "'") + url = self._with_product(url, product) + shown_url = mask_licence_keys_in_text(url) response = self._request(url, headers, shown_url, engine) if response.status_code == 304: @@ -448,17 +457,18 @@ def _request(self, url, headers, shown_url, engine): @staticmethod def _offered_products(response): - # The products an answer of status 300 offers, each with its URI, - # in the order given. The answer lists the URIs as AvailableUris, - # and each URI names its product in its Product parameter. Empty - # when the answer lists none, as from a source that is not the - # Distributor. + # The names of the products an answer of status 300 offers, in the + # order given. The answer is JSON that lists a URI for each product + # as AvailableUris, and each URI names its product in its Product + # parameter. A URI that names no product is ignored. Nothing else + # is read from a URI. None when the answer is not JSON with that + # list, as from a source that is not the Distributor. try: uris = json.loads(response.content).get("AvailableUris") except (AttributeError, TypeError, ValueError): - return [] + return None if not isinstance(uris, list): - return [] + return None offered = [] for uri in uris: if not isinstance(uri, str): @@ -469,32 +479,48 @@ def _offered_products(response): continue for name, value in parameters: if name.lower() == "product" and value: - offered.append((value, uri)) + offered.append(value) break return offered def _offered_product(self, data_file, offered, shown_url, engine): - # The product, with its URI, that the data file in use is of. When - # none of the products offered is that one, or the data file names - # no product, the check fails with an error that names the products - # offered. The URIs hold the license key, so the error names the - # products alone. + # The name, as the answer wrote it, of the product offered that the + # data file in use is of, whatever the case of either. When none of + # the products offered is that one, or the data file names no + # product, the check fails with the message and status of that row + # of the errors table, which names the product needed, empty when + # there is none, and the products offered. wanted = self._data_update_product(data_file) if wanted is not None: - for product, uri in offered: + for product in offered: if product.lower() == wanted.lower(): - return product, uri - names = ", ".join("'" + product + "'" for product, uri in offered) - message = ("Data update service at '" + shown_url + - "' offers the products " + names + " for engine '" + - engine + "', ") - if wanted is None: - message += ("which has not named the product of its data file. " - "Set the product to request to one of them.") - else: - message += ("and the data file in use is of the product '" + - wanted + "', which is not one of them.") - raise DataUpdateException(message, UpdateStatus.AUTO_UPDATE_HTTPS_ERR) + return product + raise DataUpdateException( + "Product '" + (wanted or "") + "' is not offered by data update " + "service at '" + shown_url + "' for engine '" + engine + + "'. Products offered: '" + ",".join(offered) + "'", + UpdateStatus.AUTO_UPDATE_HTTPS_ERR) + + @staticmethod + def _names_product(url): + # Whether the URL already names a product in its query, as the data + # update URL does when a product is configured. The name of the + # parameter is matched whatever its case. + try: + parameters = parse_qsl( + urlsplit(url).query, keep_blank_values=True) + except ValueError: + return False + return any(name.lower() == "product" for name, value in parameters) + + @staticmethod + def _with_product(url, product): + # The URL with the product named in its query, after the parameters + # it already has, which are left as they are. + parts = urlsplit(url) + named = "Product=" + quote(product, safe="") + query = parts.query + "&" + named if parts.query else named + return urlunsplit(parts._replace(query=query)) @staticmethod def _data_update_product(data_file): diff --git a/pipeline/fiftyone_pipeline_engines/tests/test_datafile_update_http.py b/pipeline/fiftyone_pipeline_engines/tests/test_datafile_update_http.py index 5894f75f..1cb99d18 100644 --- a/pipeline/fiftyone_pipeline_engines/tests/test_datafile_update_http.py +++ b/pipeline/fiftyone_pipeline_engines/tests/test_datafile_update_http.py @@ -164,11 +164,17 @@ def setUp(self): self.pending = [] def get(self, reply): - """Replaces the HTTP request and keeps the headers it was sent.""" + """Replaces the HTTP request and keeps the headers it was sent, and + the URL each request was made to. A list of replies answers one + request each, in order, and no more requests than it holds.""" self.sent = [] + self.requested = [] def fake_get(url, headers=None, **kwargs): self.sent.append(headers) + self.requested.append(url) + if isinstance(reply, list): + return reply[len(self.sent) - 1] if isinstance(reply, Exception): raise reply return reply @@ -1364,46 +1370,116 @@ def testTheNextCheckIsScheduledAndStillAppliesAGoodFile(self): "There are multiple products associated with this license key. Please " "use the URI returned in the Location header.") +# The path of the update URL of the fake Distributor, and the path of the +# URIs it offers, which no request is to be made to. +UPDATE_PATH = "/api/v2/download" +OFFERED_PATH = "/offered" + +# The path of the URL the fake Distributor gives in the Location header of +# an answer of status 300, when it is set to send one, and the data it +# serves there, which is that of the first product it offers. No request is +# to be made there either. +LOCATION_PATH = "/located" +FIRST_PRODUCT_DATA = b"first product data" + +# The If-Modified-Since header of a request for the stand-in data files, +# which is their publication date. +SINCE = "Tue, 03 Nov 2026 10:30:00 GMT" + def offer(url, products=HELD_PRODUCTS): - """The body of the answer of status 300 that offers each product at the - URL asked for, as the Distributor writes it.""" + """The body of the answer of status 300 that offers each product, as the + Distributor writes it. Each URI is on the host of the URL asked for but + at another path, and has no key and no Download parameter, so it is not + the request the data file update service is to make.""" + parts = urlsplit(url) + there = parts.scheme + "://" + parts.netloc + OFFERED_PATH return json.dumps({ "AvailableUris": [ - url + "&LicenceKeys=&Product=" + product for product in products], + there + "?LicenceKeys=&Type=HashV41&Product=" + product + for product in products], "Error": SEVERAL_PRODUCTS}).encode("utf-8") -def products_offered(url, ending): - """The error for a check that could not choose one of the products - offered at the URL, which is written here with its key masked.""" - return ("Data update service at '" + url + "' offers the products " - "'IPIV4Enterprise', 'V4TAC' for engine 'FakeEngine', " + ending) +def not_offered(product, url, offered="IPIV4Enterprise,V4TAC"): + """The error for a check whose product is not one of those offered at + the URL of the first request, which is written here with its key + masked.""" + return ("Product '" + product + "' is not offered by data update " + "service at '" + url + "' for engine 'FakeEngine'. Products " + "offered: '" + offered + "'") + + +def requesting(product, url): + """The entry logged before the request that names the product, which + gives the URL of the first request, written here with its key masked.""" + return ("info", + "Requesting product '" + product + "' from '" + url + + "' for Engine 'FakeEngine'") class FakeDistributorHandler(http.server.BaseHTTPRequestHandler): """Answers as the Distributor does for a license key that holds two - products. A request that names no product is answered 300 with the URI - of each product, one for V4TAC is answered 200 with the data, and one - for any other product is answered 403. The server keeps the path of - each request.""" + products. A request that names no product is answered 300 with a URI + for each product. A request that names a product after one that named + none has to be that request again, at the same path with the same + parameters and the same If-Modified-Since header, with the Product + parameter added after them, or it is answered 400. A request that + names a product when none before it named none is one made with a + product configured, and has to name one product. A request that names + a product is answered 200 with the data for V4TAC and 403 for any + other product, or 300 again when the server is set to offer the + products every time. A request to any other path, as one to a URI + offered would be, is answered 404. The server keeps the path and the + If-Modified-Since header of each request.""" def do_GET(self): - self.server.paths.append(self.path) - product = dict(parse_qsl(urlsplit(self.path).query)).get("Product") - if product is None: - here = ("http://127.0.0.1:" + - str(self.server.server_address[1]) + self.path) - self.answer(300, offer(here)) - elif product == "V4TAC": + since = self.headers.get("If-Modified-Since") + self.server.requests.append((self.path, since)) + parts = urlsplit(self.path) + parameters = parse_qsl(parts.query, keep_blank_values=True) + products = [value for name, value in parameters if name == "Product"] + here = ("http://127.0.0.1:" + str(self.server.server_address[1]) + + self.path) + if parts.path == LOCATION_PATH: + # Only a client that follows the Location header of an answer + # of status 300 asks here, and it is served the first product. + self.answer(200, FIRST_PRODUCT_DATA) + elif parts.path != UPDATE_PATH: + self.answer(404, b"") + elif not products: + self.server.first = (parameters, since) + self.answer(300, offer(here), self.location()) + elif len(products) != 1: + self.answer(400, b"") + elif self.server.first is not None and ( + parameters[-1][0] != "Product" or + self.server.first != (parameters[:-1], since)): + self.answer(400, b"") + elif self.server.several_again: + self.answer(300, offer(here), self.location()) + elif products[0] == "V4TAC": self.answer(200, TAC_DATA) else: self.answer(403, json.dumps({ "Error": "The license key provided does not contain the " "requested product."}).encode("utf-8")) - def answer(self, status, body): + def location(self): + """The Location header of an answer of status 300, when the server + is set to send one, as the Distributor does. It gives a URL for the + first product offered, which is not the product of the data file + the tests use.""" + if not self.server.location: + return None + return ("http://127.0.0.1:" + str(self.server.server_address[1]) + + LOCATION_PATH + "?LicenceKeys=&Type=HashV41&Product=" + + HELD_PRODUCTS[0]) + + def answer(self, status, body, location=None): self.send_response(status) + if location is not None: + self.send_header("Location", location) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -1425,33 +1501,53 @@ def get_data_update_product(self): # A license key can hold several products. A request that names none is -# then answered with status 300 and the URI of each product, and the check -# carries on at the URI of the product the data file in use is of. When none -# of them is that product the error names the products offered. No message -# holds the license key in full. +# then answered with status 300 and a URI for each product, as the License +# Keys with several products section of the data updates specification +# says. Only the name of the product is read from the answer. The first +# request is made again, to the same URL with the product of the data file +# in use named and with the same If-Modified-Since header, and no request +# is made to a URI offered. Another answer of status 300 is not followed. +# When none of the products offered is that of the data file the error +# names the product and the products offered. The two requests are one +# check, which is reported once. No message holds the license key in full. class SeveralProductsTests(UpdateServiceTestCase): def serve(self): """Starts a fake Distributor and returns it.""" server = http.server.ThreadingHTTPServer( ("127.0.0.1", 0), FakeDistributorHandler) - server.paths = [] + server.requests = [] + server.first = None + server.several_again = False + server.location = False thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() self.addCleanup(server.server_close) self.addCleanup(server.shutdown) return server + # The parameters of the update URL of the fake Distributor, which name + # the license key and the type and no product. + QUERY = "LicenseKeys=" + KEY + "&Type=HashV41&Download=True" + def update_url(self, server): - """The update URL of the fake Distributor, which names the license - key and the type and no product.""" + """The update URL of the fake Distributor.""" return ("http://127.0.0.1:" + str(server.server_address[1]) + - "/api/v2/download?LicenseKeys=" + KEY + "&Type=HashV41") + UPDATE_PATH + "?" + self.QUERY) def assertNoKey(self, text): self.assertNotIn(KEY[:8], text) - def testTheProductOfTheDataFileInUseIsDownloaded(self): + def several(self, product, *later): + """Sets a data file of the product to be checked at the URL that + carries a license key. The first request is answered 300 with the + products offered, and each request after it with the next of the + later replies.""" + self.data_file = ProductDataFile(product) + self.data_file.url = KEYED_URL + self.get([response(300, offer(KEYED_URL))] + list(later)) + + def testTheFirstRequestIsMadeAgainWithTheProductNamed(self): server = self.serve() self.data_file = ProductDataFile("V4TAC") self.data_file.url = self.update_url(server) @@ -1459,81 +1555,170 @@ def testTheProductOfTheDataFileInUseIsDownloaded(self): self.assertTrue(self.service.update_data_file(self.data_file)) self.assertEqual([TAC_DATA], self.data_file.refreshed) + # The two requests are one check, which is reported once. self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) # The first request is the one made for a key that holds one - # product, and the second names the product. - self.assertEqual(2, len(server.paths), server.paths) - first = dict(parse_qsl(urlsplit(server.paths[0]).query)) - second = dict(parse_qsl(urlsplit(server.paths[1]).query)) - self.assertEqual({"LicenseKeys": KEY, "Type": "HashV41"}, first) + # product. The second is the same request, to the update URL and + # with the same If-Modified-Since header, with the product added. self.assertEqual( - {"LicenseKeys": KEY, "Type": "HashV41", "Product": "V4TAC"}, - second) + [(UPDATE_PATH + "?" + self.QUERY, SINCE), + (UPDATE_PATH + "?" + self.QUERY + "&Product=V4TAC", SINCE)], + server.requests) - def testTheSecondRequestIsLoggedWithTheKeyMasked(self): + def testNoRequestIsMadeToAUriOffered(self): server = self.serve() self.data_file = ProductDataFile("V4TAC") self.data_file.url = self.update_url(server) self.service.update_data_file(self.data_file) - self.assertTrue(self.pipeline.logs) + self.assertEqual(2, len(server.requests), server.requests) + for path, since in server.requests: + self.assertEqual(UPDATE_PATH, urlsplit(path).path) + + def testTheLocationHeaderOfAnAnswerOfStatus300IsNotFollowed(self): + # The Distributor gives the first URI it offers in a Location + # header. A client that followed it would never see the answer of + # status 300, and would be served the first product offered, which + # is not the product of the data file in use. + server = self.serve() + server.location = True + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = self.update_url(server) + + self.assertTrue(self.service.update_data_file(self.data_file)) + + self.assertEqual([TAC_DATA], self.data_file.refreshed) + self.assertEqual( + [(UPDATE_PATH + "?" + self.QUERY, SINCE), + (UPDATE_PATH + "?" + self.QUERY + "&Product=V4TAC", SINCE)], + server.requests) + self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) + + def testTheLocationHeaderOfASecondAnswerOfStatus300IsNotFollowed(self): + server = self.serve() + server.location = True + server.several_again = True + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = self.update_url(server) + + self.assertCheckFails( + UpdateStatus.AUTO_UPDATE_HTTPS_ERR, + "HTTP status code '300' from data update service at '" + + mask_licence_keys_in_text(self.data_file.url) + + "&Product=V4TAC' for engine 'FakeEngine'") + + self.assertEqual(2, len(server.requests), server.requests) + for path, since in server.requests: + self.assertEqual(UPDATE_PATH, urlsplit(path).path) + self.assertEqual([], self.data_file.refreshed) + + def testAnotherAnswerOfStatus300IsNotFollowed(self): + server = self.serve() + server.several_again = True + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = self.update_url(server) + + # The answer to the second request ends the check, as an answer of + # any other status does. + self.assertCheckFails( + UpdateStatus.AUTO_UPDATE_HTTPS_ERR, + "HTTP status code '300' from data update service at '" + + mask_licence_keys_in_text(self.data_file.url) + + "&Product=V4TAC' for engine 'FakeEngine'") + + self.assertEqual( + [(UPDATE_PATH + "?" + self.QUERY, SINCE), + (UPDATE_PATH + "?" + self.QUERY + "&Product=V4TAC", SINCE)], + server.requests) + self.assertEqual([UpdateStatus.AUTO_UPDATE_HTTPS_ERR], self.statuses) + self.assertEqual([], self.data_file.refreshed) + + def testEachActionIsLoggedWithTheKeyMasked(self): + self.several("V4TAC", response(200)) + + self.service.update_data_file(self.data_file) + for level, message in self.pipeline.logs: self.assertNoKey(message) - followed = mask_licence_keys_in_text( - self.data_file.url + "&LicenceKeys=&Product=V4TAC") - self.assertNoKey(followed) - self.assertIn( + self.assertEqual([ + ("info", "Checking for update"), ("info", - "The license key holds several products. Checking for update " - "to product 'V4TAC' from '" + followed + "' for Engine " + "Checking for update from '" + MASKED_URL + "' for Engine " "'FakeEngine'"), - self.pipeline.logs) - self.assertIn( + requesting("V4TAC", MASKED_URL), ("info", - "Downloaded new data from '" + followed + "' for Engine " - "'FakeEngine'"), - self.pipeline.logs) + "Downloaded new data from '" + MASKED_URL + "&Product=V4TAC' " + "for Engine 'FakeEngine'"), + ("info", + "Attempting to refresh Engine 'FakeEngine' with new data"), + ], self.pipeline.logs) def testTheProductIsMatchedWhateverItsCase(self): - server = self.serve() - self.data_file = ProductDataFile("v4tac") - self.data_file.url = self.update_url(server) + self.several("v4tac", response(200)) self.assertTrue(self.service.update_data_file(self.data_file)) - self.assertEqual([TAC_DATA], self.data_file.refreshed) + # The product is named as the answer wrote it. + self.assertEqual( + [KEYED_URL, KEYED_URL + "&Product=V4TAC"], self.requested) + self.assertIn(requesting("V4TAC", MASKED_URL), self.pipeline.logs) + self.assertEqual([b"new"], self.data_file.refreshed) def testIfModifiedSinceIsSentWithBothRequests(self): + self.several("V4TAC", response(304)) + + self.assertFalse(self.service.update_data_file(self.data_file)) + + self.assertEqual( + [KEYED_URL, KEYED_URL + "&Product=V4TAC"], self.requested) + self.assertEqual( + [SINCE, SINCE], + [headers["If-Modified-Since"] for headers in self.sent]) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_NOT_NEEDED], self.statuses) + + def testNeitherRequestHasIfModifiedSinceWhenDisabled(self): + self.several("V4TAC", response(304)) + self.data_file.verify_if_modified_since = False + + self.service.update_data_file(self.data_file) + + self.assertEqual(2, len(self.sent)) + for headers in self.sent: + self.assertNotIn("If-Modified-Since", headers) + + def testAUriThatNamesNoProductIsIgnored(self): self.data_file = ProductDataFile("V4TAC") - self.data_file.url = KEYED_URL - self.get(response(300, offer(KEYED_URL))) + self.get([ + response(300, json.dumps({"AvailableUris": [ + URL + "?Type=HashV41", + 7, + URL + "?Type=HashV41&Product=V4TAC"]}).encode("utf-8")), + response(200)]) + + self.assertTrue(self.service.update_data_file(self.data_file)) + + self.assertEqual([URL, URL + "?Product=V4TAC"], self.requested) + + def testAnAnswerOfStatus403ToTheSecondRequestIsAccessDenied(self): + self.several("V4TAC", response(403)) - # The stand-in answers 300 both times, so the second answer ends - # the check, as an answer of any other status does. self.assertCheckFails( - UpdateStatus.AUTO_UPDATE_HTTPS_ERR, - "HTTP status code '300' from data update service at '" + - MASKED_URL + "&LicenceKeys=&Product=V4TAC' for engine " - "'FakeEngine'") + UpdateStatus.AUTO_UPDATE_ERR_403_FORBIDDEN, + "Access denied to data update service at '" + MASKED_URL + + "&Product=V4TAC' for engine 'FakeEngine'") self.assertEqual(2, len(self.sent)) - for headers in self.sent: - self.assertEqual( - "Tue, 03 Nov 2026 10:30:00 GMT", - headers["If-Modified-Since"]) + self.assertEqual( + [UpdateStatus.AUTO_UPDATE_ERR_403_FORBIDDEN], self.statuses) - def testAProductTheKeyDoesNotHoldNamesTheProductsOffered(self): - self.data_file = ProductDataFile("V4Enterprise") - self.data_file.url = KEYED_URL - self.get(response(300, offer(KEYED_URL))) + def testAProductThatIsNotOfferedNamesTheProductsOffered(self): + self.several("V4Enterprise") error = self.assertCheckFails( UpdateStatus.AUTO_UPDATE_HTTPS_ERR, - products_offered( - MASKED_URL, - "and the data file in use is of the product 'V4Enterprise', " - "which is not one of them.")) + not_offered("V4Enterprise", MASKED_URL)) self.assertNoKey("".join(traceback.format_exception( type(error), error, error.__traceback__))) @@ -1541,9 +1726,21 @@ def testAProductTheKeyDoesNotHoldNamesTheProductsOffered(self): self.assertEqual([UpdateStatus.AUTO_UPDATE_HTTPS_ERR], self.statuses) self.assertEqual([], self.data_file.refreshed) + def testTheErrorIsWrittenExactly(self): + # Written out in full, so a change to any character fails. + self.several("V4Enterprise") + + self.assertCheckFails( + UpdateStatus.AUTO_UPDATE_HTTPS_ERR, + "Product 'V4Enterprise' is not offered by data update service " + "at 'https://example.com/update?licenseKeys=********IJKL&" + "Type=HashV41' for engine 'FakeEngine'. Products offered: " + "'IPIV4Enterprise,V4TAC'") + def testADataFileThatNamesNoProductNamesTheProductsOffered(self): # A data file that has no way to name its product, and one whose - # engine has loaded no data file yet. + # engine has loaded no data file yet. The product in the error is + # then empty. for name, data_file in ( ("no name", HttpDataFile()), ("none loaded", ProductDataFile(None))): @@ -1555,40 +1752,37 @@ def testADataFileThatNamesNoProductNamesTheProductsOffered(self): self.assertCheckFails( UpdateStatus.AUTO_UPDATE_HTTPS_ERR, - products_offered( - MASKED_URL, - "which has not named the product of its data file. " - "Set the product to request to one of them.")) + not_offered("", MASKED_URL)) self.assertEqual(1, len(self.sent)) self.assertEqual( [UpdateStatus.AUTO_UPDATE_HTTPS_ERR], self.statuses) def testAPolledCheckLogsTheProductsOfferedWithTheKeyMasked(self): - self.data_file = ProductDataFile("V4Enterprise") - self.data_file.url = KEYED_URL - self.get(response(300, offer(KEYED_URL))) + self.several("V4Enterprise") self.poll() for level, message in self.pipeline.logs: self.assertNoKey(message) - self.assertIn( - ("error", - CHECK_ERROR + products_offered( - MASKED_URL, - "and the data file in use is of the product " - "'V4Enterprise', which is not one of them.")), - self.pipeline.logs) + self.assertEqual( + [CHECK_ERROR + not_offered("V4Enterprise", MASKED_URL)], + [message for level, message in self.pipeline.logs + if level == "error"]) self.assertEqual([UpdateStatus.AUTO_UPDATE_HTTPS_ERR], self.statuses) def testAnAnswerThatOffersNoProductIsReportedByItsStatus(self): - # An answer of status 300 that lists no URIs, as from a source that - # is not the Distributor, ends the check as any other status does. + # An answer of status 300 that is not JSON with a list of URIs, or + # whose list names no product, as from a source that is not the + # Distributor, ends the check as any other status does. self.data_file = ProductDataFile("V4TAC") for name, content in ( ("not JSON", b"new"), + ("not an object", json.dumps([1]).encode("utf-8")), ("no list", json.dumps({"Error": "no"}).encode("utf-8")), + ("not a list", json.dumps( + {"AvailableUris": URL + "?Product=V4TAC"} + ).encode("utf-8")), ("empty list", json.dumps({"AvailableUris": []}).encode("utf-8")), ("no product", json.dumps( @@ -1611,6 +1805,115 @@ def testAKeyThatHoldsOneProductIsAskedOnce(self): self.assertEqual(1, len(self.sent)) self.assertEqual([b"new"], self.data_file.refreshed) + # A product is named in the update URL only when one is configured. + # Every request is made to that URL, so with a product configured every + # request names it, the first included, and no request is made again. + # With none configured the first request has no Product parameter. + + def testWithNoProductConfiguredTheFirstRequestNamesNoProduct(self): + server = self.serve() + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = self.update_url(server) + + self.service.update_data_file(self.data_file) + + path, since = server.requests[0] + self.assertEqual(UPDATE_PATH + "?" + self.QUERY, path) + # No parameter of the first request is Product, empty or not. + self.assertEqual( + [], [name for name, value in parse_qsl( + urlsplit(path).query, keep_blank_values=True) + if name.lower() == "product"]) + + def testAConfiguredProductIsNamedInTheFirstRequest(self): + server = self.serve() + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = self.update_url(server) + "&Product=V4TAC" + + self.assertTrue(self.service.update_data_file(self.data_file)) + + # The one request names the product, so the products are not + # offered and nothing is asked a second time. + self.assertEqual( + [(UPDATE_PATH + "?" + self.QUERY + "&Product=V4TAC", SINCE)], + server.requests) + self.assertEqual([TAC_DATA], self.data_file.refreshed) + self.assertEqual([UpdateStatus.AUTO_UPDATE_SUCCESS], self.statuses) + self.assertNotIn( + "Requesting product", + "".join(message for level, message in self.pipeline.logs)) + + def testAConfiguredProductIsNamedInEveryRequest(self): + server = self.serve() + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = self.update_url(server) + "&Product=V4TAC" + + self.service.update_data_file(self.data_file) + self.service.update_data_file(self.data_file) + + self.assertEqual( + [(UPDATE_PATH + "?" + self.QUERY + "&Product=V4TAC", SINCE)] * 2, + server.requests) + + def testAConfiguredProductIsNamedWhateverTheDataFileInUse(self): + # The product configured is the one asked for, and the product of + # the data file in use is not read. + server = self.serve() + self.data_file = ProductDataFile("V4Enterprise") + self.data_file.url = self.update_url(server) + "&Product=V4TAC" + + self.assertTrue(self.service.update_data_file(self.data_file)) + + self.assertEqual( + [(UPDATE_PATH + "?" + self.QUERY + "&Product=V4TAC", SINCE)], + server.requests) + + def testAnAnswerOfStatus300ToAConfiguredProductIsNotFollowed(self): + server = self.serve() + server.several_again = True + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = self.update_url(server) + "&Product=V4TAC" + + # The request already names a product, so it is not made again and + # the answer ends the check as an answer of any other status does. + self.assertCheckFails( + UpdateStatus.AUTO_UPDATE_HTTPS_ERR, + "HTTP status code '300' from data update service at '" + + mask_licence_keys_in_text(self.data_file.url) + + "' for engine 'FakeEngine'") + + self.assertEqual( + [(UPDATE_PATH + "?" + self.QUERY + "&Product=V4TAC", SINCE)], + server.requests) + self.assertEqual([UpdateStatus.AUTO_UPDATE_HTTPS_ERR], self.statuses) + self.assertEqual([], self.data_file.refreshed) + + def testAConfiguredProductTheKeyDoesNotHoldIsAccessDenied(self): + server = self.serve() + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = ( + self.update_url(server) + "&Product=V4Enterprise") + + self.assertCheckFails( + UpdateStatus.AUTO_UPDATE_ERR_403_FORBIDDEN, + "Access denied to data update service at '" + + mask_licence_keys_in_text(self.data_file.url) + + "' for engine 'FakeEngine'") + + self.assertEqual(1, len(server.requests), server.requests) + + def testTheNameOfTheProductParameterIsReadWhateverItsCase(self): + self.data_file = ProductDataFile("V4TAC") + self.data_file.url = KEYED_URL + "&product=V4TAC" + self.get(response(300, offer(KEYED_URL))) + + self.assertCheckFails( + UpdateStatus.AUTO_UPDATE_HTTPS_ERR, + "HTTP status code '300' from data update service at '" + + MASKED_URL + "&product=V4TAC' for engine 'FakeEngine'") + + self.assertEqual(1, len(self.sent)) + if __name__ == "__main__": unittest.main()