diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/configurator_console.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/configurator_console.py index 0ef8d9b8..3145b513 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/configurator_console.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/configurator_console.py @@ -25,6 +25,16 @@ from fiftyone_devicedetection_cloud.devicedetection_cloud_pipelinebuilder import DeviceDetectionCloudPipelineBuilder from fiftyone_devicedetection_examples.example_utils import ExampleUtils +# Where to ask about a paid resource key, for the properties a free key +# does not return. +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-cloud-configurator_console.py&utm_term=paid-resource-key" + +# The properties that only a paid resource key returns, as the name the +# note gives and the property name. +PAID_PROPERTIES = [ + ("HardwareVendor", "hardwarevendor"), + ("HardwareName", "hardwarename")] + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("Device detection", @@ -91,6 +101,17 @@ def run(self, resource_key, logger, output): output("device.ismobile: " + f"{ExampleUtils.get_human_readable(device, 'ismobile')}") + # The same for the properties only a paid resource key returns, + # saying once what to do about any the key cannot return. + missing = [] + for label, property_name in PAID_PROPERTIES: + output(f"device.{property_name}: " + + f"{ExampleUtils.get_human_readable(device, property_name)}") + if ExampleUtils.needs_paid_key(device, property_name): + missing.append(label) + if missing: + output(ExampleUtils.get_paid_key_note(missing, CONTACT_US)) + ExampleUtils.print_find_out_more(FIND_OUT_MORE, output) def main(argv): @@ -111,8 +132,8 @@ def main(argv): "cloud service is accessed using a 'ResourceKey'. " + "For more detail see " + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-configurator_console.py&utm_term=resource-key-required. " + - "A resource key with the properties required by this " + - "example can be created for free at " + + "A resource key with the free properties this " + + "example uses can be created for free at " + "https://51degrees.com/configure/1QWJwHxl?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-configurator_console.py&utm_term=resource-key-required. " + "Once complete, populate the environment variable " + "mentioned at the start of this message with the key.") diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/failuretomatch.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/failuretomatch.py index ae926b41..fcc24391 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/failuretomatch.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/failuretomatch.py @@ -33,6 +33,10 @@ # it has no key. from fiftyone_devicedetection_examples.example_utils import ExampleUtils +# Where to ask about a paid resource key, for the properties a free key +# does not return. +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-cloud-failuretomatch.py&utm_term=paid-resource-key" + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("Device detection", @@ -51,7 +55,7 @@ print(ExampleUtils.get_missing_resource_key_message()) # The address stays on one line, because the campaign lint reads a # line at a time and a split address looks to it like a missing tag. - print(" To include the properties used in this example, go to " + print(" To include the free properties this example uses, go to " "https://51degrees.com/configure/bxXqZhLT?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-failuretomatch.py&utm_term=resource-key-required") else: @@ -86,6 +90,14 @@ # Output why the value isn't meaningful print(flowdata1.device.ismobile.no_value_message()) + # The hardware vendor is only returned by a paid resource key, so it is + # read through the helper, which says why a value is missing rather + # than stopping the example. + print("Who made the device?: ") + print(ExampleUtils.get_human_readable(flowdata1.device, "hardwarevendor")) + if ExampleUtils.needs_paid_key(flowdata1.device, "hardwarevendor"): + print(ExampleUtils.get_paid_key_note(["HardwareVendor"], CONTACT_US)) + # Now we do the same with a new User-Agent, this time a corrupted one badUA = "--" diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.json b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.json index 2caf8d14..89fb3d01 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.json +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.json @@ -6,8 +6,8 @@ "elementPath": "fiftyone_pipeline_cloudrequestengine.cloudrequestengine", "elementParameters": { "settings": { - // Obtain a resource key with the properties required to run this - // example for free: https://51degrees.com/configure/1QWJwHxl?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_console.json&utm_term=settings + // Obtain a resource key with the free properties this + // example uses: https://51degrees.com/configure/1QWJwHxl?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_console.json&utm_term=settings "resource_key": "!!ENTER_YOUR_RESOURCE_KEY_HERE!!", "cloud_request_origin": "51Degrees.example.com" } diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.py index 7d525358..868b0c9a 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.py @@ -45,6 +45,10 @@ from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder from fiftyone_devicedetection_examples.example_utils import ExampleUtils +# Where to ask about a paid resource key, for the properties a free key +# does not return. +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-cloud-gettingstarted_console.py&utm_term=paid-resource-key" + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("Device detection", @@ -67,9 +71,15 @@ def run(self, config, logger, output): # Create the pipeline using the service provider and the configured options. pipeline = PipelineBuilder().add_logger(logger).build_from_configuration(config) - # carry out some sample detections + # carry out some sample detections, noting the properties that the + # resource key cannot return + missing = [] for values in self.EvidenceValues: - self.analyseEvidence(values, pipeline, output) + missing += self.analyseEvidence(values, pipeline, output) + + # Say once what to do about them. + if missing: + output(ExampleUtils.get_paid_key_note(missing, CONTACT_US)) ExampleUtils.print_find_out_more(FIND_OUT_MORE, output) @@ -117,7 +127,18 @@ def analyseEvidence(self, evidence, pipeline, output): self.outputValue("Platform Version", device.platformversion, message) self.outputValue("Browser Name", device.browsername, message) self.outputValue("Browser Version", device.browserversion, message) + + # These properties are only returned by a paid resource key, so they + # are read through the helper, which says why a value is missing + # rather than stopping the example. + missing = [] + for label, property_name in self.PaidProperties: + message.append(f"\t{label}: " + f"{ExampleUtils.get_human_readable(device, property_name)}\n") + if ExampleUtils.needs_paid_key(device, property_name): + missing.append(label) output("".join(message)) + return missing def outputValue(self, name, value, message): # Individual result values have a wrapper called @@ -132,6 +153,12 @@ def outputValue(self, name, value, message): else f"\t{name}: {value.no_value_message()}\n") + # The properties that only a paid resource key returns, as label and + # property name. + PaidProperties = [ + ("Hardware Vendor", "hardwarevendor"), + ("Hardware Name", "hardwarename")] + # This collection contains the various input values that will # be passed to the device detection algorithm. EvidenceValues = [ @@ -189,7 +216,7 @@ def main(argv): "service is accessed using a 'ResourceKey'. For more information " + "see " + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_console.py&utm_term=resource-key-required. " + - "A resource key with the properties required by this example can be " + + "A resource key with the free properties this example uses can be " + "created for free at https://51degrees.com/configure/1QWJwHxl?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_console.py&utm_term=resource-key-required. " + "Once complete, populate the config file or environment variable " + "mentioned at the start of this message with the key.") diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/app.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/app.py index 1ab69bcc..69261224 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/app.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/app.py @@ -92,6 +92,29 @@ import os import sys +# Where to ask about a paid resource key, for the properties a free key +# does not return. +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-cloud-gettingstarted_web-app.py&utm_term=paid-resource-key" + +# The properties on the page that only a paid resource key returns, as +# label and property name. +PAID_PROPERTIES = [ + ("Hardware Vendor", "hardwarevendor"), + ("Hardware Name", "hardwarename"), + ("Device Type", "devicetype"), +] + + +def get_paid_key_note_html(device): + """! + The paid key note for the page, naming the paid properties the key + cannot return, or an empty string when it returns them all. + """ + missing = [label for label, name in PAID_PROPERTIES + if ExampleUtils.needs_paid_key(device, name)] + return ExampleUtils.get_paid_key_note_html(missing, CONTACT_US) + + # Where to go next, printed when the example ends. The page ends with the # same links, in templates/index.html. FIND_OUT_MORE = [ @@ -203,6 +226,7 @@ def server(): 'index.html', data=flowdata, utils=ExampleUtils, + paid_key_note=get_paid_key_note_html(flowdata.device), response=response)) return response @@ -225,8 +249,8 @@ def main(argv): "cloud service is accessed using a 'ResourceKey'. " + "For more detail see " + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_web-app.py&utm_term=resource-key-required. " + - "A resource key with the properties required by this " + - "example can be created for free at " + + "A resource key with the free properties this example uses " + + "can be created for free at " + "https://51degrees.com/configure/g3gMZdPY?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-gettingstarted_web-app.py&utm_term=resource-key-required. " + "Once complete, populated the environment variable " + "mentioned at the start of this message with the key.") diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/templates/index.html b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/templates/index.html index 0d055c53..01a06f76 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/templates/index.html +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/templates/index.html @@ -136,6 +136,9 @@
diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/app.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/app.py index 15a3b1c1..1709f411 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/app.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/app.py @@ -60,6 +60,29 @@ from fiftyone_pipeline_core.logger import Logger from fiftyone_pipeline_core.web import webevidence, set_response_header +# Where to ask about a paid resource key, for the properties a free key +# does not return. +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-cloud-useragentclienthints_web-app.py&utm_term=paid-resource-key" + +# The properties on the page that only a paid resource key returns, as +# label and property name. +PAID_PROPERTIES = [ + ("Hardware Vendor", "hardwarevendor"), + ("Hardware Name", "hardwarename"), + ("Device Type", "devicetype"), +] + + +def get_paid_key_note_html(device): + """! + The paid key note for the page, naming the paid properties the key + cannot return, or an empty string when it returns them all. + """ + missing = [label for label, name in PAID_PROPERTIES + if ExampleUtils.needs_paid_key(device, name)] + return ExampleUtils.get_paid_key_note_html(missing, CONTACT_US) + + # Where to go next, printed when the example ends. The page ends with the # same links, in templates/index.html. FIND_OUT_MORE = [ @@ -138,6 +161,7 @@ def server(): 'index.html', data=flowdata, utils=ExampleUtils, + paid_key_note=get_paid_key_note_html(flowdata.device), response=response)) return response @@ -161,8 +185,8 @@ def main(argv): "cloud service is accessed using a 'ResourceKey'. " + "For more detail see " + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-useragentclienthints_web-app.py&utm_term=resource-key-required. " + - "A resource key with the properties required by this " + - "example can be created for free at " + + "A resource key with the free properties this example uses " + + "can be created for free at " + "https://51degrees.com/configure/?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-cloud-useragentclienthints_web-app.py&utm_term=resource-key-required. " + "Once complete, populated the environment variable " + "mentioned at the start of this message with the key.") diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/templates/index.html b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/templates/index.html index 1b84bc94..76024cdd 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/templates/index.html +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/templates/index.html @@ -98,6 +98,9 @@
" + + ExampleUtils.get_paid_key_note_html(["Country"], CONTACT_US) + + "
") + + @app.route("/") def index(): @@ -107,7 +124,9 @@ def index():Add ?client-ip=x.x.x.x to the url to lookup a different address.
{ExampleUtils.get_find_out_more_html(FIND_OUT_MORE)} """ @@ -129,7 +148,7 @@ def main(resource_key = None): "service is accessed using a 'ResourceKey'. For more " "information see " "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-gettingstarted_web-app.py&utm_term=resource-key-required. " - "A resource key with the properties required by this example " + "A resource key with the free properties this example uses " "can be created for free at " "https://51degrees.com/configure/?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-gettingstarted_web-app.py&utm_term=resource-key-required. " "Once complete, populate the environment variable mentioned at " diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/mixed_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/mixed_console.py index 9b9a1813..b6a2bb7f 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/mixed_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/mixed_console.py @@ -85,6 +85,22 @@ "Longitude", ] +# The properties above that only a paid resource key returns. The free +# Lite data files have none of them. A free property that is missing shows +# its reason and gets no note. +PAID_PROPERTIES = [ + "HardwareVendor", + "DeviceType", + "Country", + "CountryCode", + "Latitude", + "Longitude", +] + +# Where to ask about a paid resource key, for the properties a free key +# does not return. +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-cloud-mixed_console.py&utm_term=paid-resource-key" + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("Device detection", @@ -131,8 +147,13 @@ def run(self, resource_key, logger, output, cloud_endpoint = None): .add_logger(logger) \ .build() + # Note the properties that the resource key cannot return, and say + # once what to do about them. + missing = [] for evidence in COMBINED_EVIDENCE: - self.analyse_evidence(evidence, pipeline, output) + missing += self.analyse_evidence(evidence, pipeline, output) + if missing: + output(ExampleUtils.get_paid_key_note(missing, CONTACT_US)) def analyse_evidence(self, evidence, pipeline, output): @@ -149,15 +170,23 @@ def analyse_evidence(self, evidence, pipeline, output): data.process() message = [] + missing = [] message.append("Device Detection Results:\n") for name in DEVICE_PROPERTIES: self.outputValue(data.device, name, message) + if name in PAID_PROPERTIES and \ + ExampleUtils.needs_paid_key(data.device, name.lower()): + missing.append(name) message.append("\nIP Intelligence Results:\n") for name in IP_PROPERTIES: self.outputValue(data.ip, name, message) + if name in PAID_PROPERTIES and \ + ExampleUtils.needs_paid_key(data.ip, name.lower()): + missing.append(name) output("".join(message)) + return missing def outputValue(self, aspect_data, name, message): # `get_value` returns None when the property is not present in the diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py index 0c81760e..1c5429d4 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py @@ -129,6 +129,63 @@ def get_value(ip_data, property): except Exception: return None + # The cloud service gives a property the resource key is not entitled + # to with no value and a reason that contains this. + PAID_FEATURE = "paid feature" + + @staticmethod + def needs_paid_key(data, property_name): + + """! + True when the resource key in use cannot return the property. The + results leave out a property the key does not include, or give it + no value with a reason that says it is a paid feature. + """ + + value = ExampleUtils.get_value(data, property_name) + if value is None: + return True + if value.has_value(): + return False + reason = value.no_value_message() or "" + return ExampleUtils.PAID_FEATURE in reason.lower() + + @staticmethod + def get_paid_key_note(missing, contact_us): + + """! + What to do about the properties the resource key in use cannot + return, written once after an example has shown them. It reads + right for a free key and for a paid key set up without them. + missing names the properties as the example shows them, and the + link is tagged with the example's file, so that an enquiry can be + traced to the example. + """ + + names = list(dict.fromkeys(missing)) + if len(names) == 1: + start = (f"This property needs a paid Resource Key: {names[0]}. " + "If yours is paid, add it") + else: + start = ("These properties need a paid Resource Key: " + f"{', '.join(names)}. If yours is paid, add them") + return (f"{start} on the configuration page. If it is free, contact " + f"us about a paid one at {contact_us}") + + @staticmethod + def get_paid_key_note_html(missing, contact_us): + """! + The paid key note as HTML for a page, with the contact link as a + link, or an empty string when nothing is missing. + """ + + if not missing: + return "" + link = html.escape(contact_us) + return html.escape( + ExampleUtils.get_paid_key_note(missing, contact_us)).replace( + link, f'{link}') + @staticmethod def get_data_file_path(): """! diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_cloud_paid_key_note.py b/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_cloud_paid_key_note.py new file mode 100644 index 00000000..7f8a6549 --- /dev/null +++ b/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_cloud_paid_key_note.py @@ -0,0 +1,339 @@ +# ********************************************************************* +# 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. +# ********************************************************************* + +"""! +Runs the cloud examples that ask for properties only a paid resource key +returns against a stand-in for the cloud service. With a key that cannot +return them, as a free key or a paid key set up without them, each example +must give the paid key note once, ending with its own tagged contact link, +and end normally. With a key that returns them, it must give no note. The +stand-in answers as the cloud service does, so these tests need no key and +no network. +""" + +import html +import http.server +import json +import os +import re +import threading +import unittest +from contextlib import contextmanager +from pathlib import Path +from unittest import mock + +from fiftyone_pipeline_core.logger import Logger + +from fiftyone_ipintelligence_examples.example_utils import ExampleUtils +from fiftyone_ipintelligence_examples.cloud import countries_console +from fiftyone_ipintelligence_examples.cloud import getallproperties_console +from fiftyone_ipintelligence_examples.cloud import gettingstarted_console +from fiftyone_ipintelligence_examples.cloud import mixed_console +from fiftyone_ipintelligence_examples.cloud.gettingstarted_web import ( + app as web) + +# The properties a free resource key returns, by product, as the cloud +# service names them, each with its type and the value the stand-in gives. +FREE = { + "ip": { + "RegisteredName": ("String", "Example Networks"), + "RegisteredOwner": ("String", "Example Owner"), + "RegisteredCountry": ("String", "GB"), + }, + "device": { + "IsMobile": ("Boolean", True), + "PlatformName": ("String", "iOS"), + "PlatformVersion": ("String", "14.6"), + "BrowserName": ("String", "Mobile Safari"), + "BrowserVersion": ("String", "14.0"), + "DeviceType": ("String", "SmartPhone"), + }, +} + +# The properties only a paid resource key returns, by product. +PAID = { + "ip": { + "IpRangeStart": ("IpAddress", "1.3.32.0"), + "IpRangeEnd": ("IpAddress", "1.3.32.255"), + "Country": ("String", "China"), + "CountryCode": ("String", "CN"), + "CountryCode3": ("String", "CHN"), + "Region": ("String", "Asia"), + "State": ("String", "Guangdong"), + "Town": ("String", "Guangzhou"), + "Latitude": ("Double", 23.1), + "Longitude": ("Double", 113.3), + "Areas": ("String", "POINT(113.3 23.1)"), + "AccuracyRadiusMin": ("Int32", 1000), + "TimeZoneOffset": ("Int32", 480), + }, + "device": { + "HardwareVendor": ("String", "Apple"), + }, + "countrynamestranslated": { + "CountryNamesGeographicalTranslated": ( + "WeightedString", [{"value": "Chine", "rawweighting": 65535}]), + "CountryCodesGeographicalAll": ("Array", ["CN", "FR"]), + "CountryNamesGeographicalAllTranslated": ( + "Array", ["Chine", "France"]), + "SortingCultureUsed": ("String", "fr-FR"), + }, +} + +# Every evidence key the examples give. +EVIDENCE_KEYS = [ + "query.client-ip", "query.client-ip-51d", "server.client-ip", + "header.user-agent", "header.accept-language"] + +# Any resource key, as the stand-in does not check it. +RESOURCE_KEY = "stand-in-key" + +# A contact link as the UTM convention asks: exactly five parameters in +# this order, the last two being lowercase slugs, the term at most 60 +# characters. +CONTACT_LINK = re.compile( + r"https://51degrees\.com/contact-us\?utm_source=code&utm_medium=example" + r"&utm_campaign=51degrees-python&utm_content=([a-z0-9][a-z0-9._-]*)" + r"&utm_term=([a-z0-9][a-z0-9._-]{0,59})") + +# The start of each example's utm_content, which ends with its file's path +# below the cloud folder. +CONTENT = ("fiftyone_ipintelligence_examples-src-" + "fiftyone_ipintelligence_examples-cloud-") + + +def merge(*keys): + """The properties of several keys put together, by product.""" + products = {} + for key in keys: + for product, properties in key.items(): + products.setdefault(product, {}).update(properties) + return products + + +class StandInHandler(http.server.BaseHTTPRequestHandler): + """Answers the accessible properties, evidence keys and results requests + as the cloud service does for a key that carries the server's + products, and anything else with 404.""" + + def do_GET(self): + self.reply() + + def do_POST(self): + # The body is read before answering, so the client is not cut off + # while it is still sending. + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + self.reply() + + def reply(self): + products = self.server.products + path = self.path.split("?", 1)[0].lower() + if path.endswith("/accessibleproperties"): + self.answer(200, {"Products": { + product: { + "DataTier": "CloudV4Free", + "Properties": [ + {"Name": name, "Type": kind, "Category": ""} + for name, (kind, _) in properties.items()]} + for product, properties in products.items()}}) + elif path.endswith("/evidencekeys"): + self.answer(200, EVIDENCE_KEYS) + elif path.endswith(".json"): + results = { + product: {name.lower(): value + for name, (_, value) in properties.items()} + for product, properties in products.items()} + results["javascriptProperties"] = [] + self.answer(200, results) + else: + self.answer(404, {"errors": ["Not found."]}) + + def answer(self, status, body): + content = json.dumps(body).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + + def log_message(self, format, *args): + pass + + +@contextmanager +def stand_in_cloud(products): + """A stand-in for the cloud service, on a free port of this machine, for + a key that carries products, with the cloud endpoint and the resource + key in the environment.""" + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), StandInHandler) + server.products = products + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with mock.patch.dict(os.environ): + os.environ.pop(ExampleUtils.LICENSE_KEY_ENV_VAR, None) + os.environ[ExampleUtils.CLOUD_RESOURCE_KEY_ENV_VAR] = RESOURCE_KEY + os.environ[ExampleUtils.CLOUD_ENDPOINT_ENV_VAR] = ( + f"http://127.0.0.1:{server.server_address[1]}/api/v4/") + yield server + finally: + server.shutdown() + server.server_close() + + +def run_console(example): + """Runs a console example's class and returns what it wrote.""" + printed = [] + example().run(RESOURCE_KEY, Logger(min_level="error"), printed.append) + return "\n".join(printed) + + +def run_web(): + """Builds the web example's pipeline and returns its page.""" + pipeline = web.build_pipeline(RESOURCE_KEY) + try: + page = web.app.test_client().get("/?client-ip=1.3.32.31") + return page.get_data(as_text=True) + finally: + pipeline.close() + + +def web_note(missing, contact_us): + """The note as the web example's page shows it, with the link as a + link.""" + link = html.escape(contact_us) + return html.escape( + ExampleUtils.get_paid_key_note(missing, contact_us)).replace( + link, f'{link}') + + +# Each example, how it is run, the properties its note names, and how the +# note is shown. +EXAMPLES = [ + (gettingstarted_console, + lambda: run_console(gettingstarted_console.GettingStartedConsole), + [name for name in gettingstarted_console.OUTPUT_PROPERTIES + if name not in FREE["ip"]], + ExampleUtils.get_paid_key_note), + (mixed_console, + lambda: run_console(mixed_console.MixedConsole), + ["HardwareVendor", "Country", "CountryCode", "Latitude", "Longitude"], + ExampleUtils.get_paid_key_note), + (getallproperties_console, + lambda: run_console(getallproperties_console.GetAllPropertiesConsole), + ["Country", "Town"], + ExampleUtils.get_paid_key_note), + (countries_console, + lambda: run_console(countries_console.CountriesConsole), + countries_console.TRANSLATED_PROPERTIES, + ExampleUtils.get_paid_key_note), + (web, run_web, ["Country"], web_note), +] + + +def file_slug(module): + """The example's file below the cloud folder, as utm_content ends.""" + path = Path(module.__file__) + parts = path.parts[path.parts.index("cloud") + 1:] + return "-".join(parts) + + +class PaidKeyNoteTests(unittest.TestCase): + + def test_each_contact_link_is_tagged_with_its_file(self): + for module, _, _, _ in EXAMPLES: + with self.subTest(module.__name__): + match = CONTACT_LINK.fullmatch(module.CONTACT_US) + self.assertIsNotNone(match, module.CONTACT_US) + self.assertEqual(CONTENT + file_slug(module), match.group(1)) + self.assertEqual("paid-resource-key", match.group(2)) + + def test_a_key_without_the_paid_properties_gets_the_note_once(self): + for module, run, missing, shown in EXAMPLES: + with self.subTest(module.__name__), stand_in_cloud(FREE): + output = run() + note = shown(missing, module.CONTACT_US) + self.assertEqual(1, output.count(note), output) + self.assertNotIn("Traceback", output) + + def test_a_key_with_the_paid_properties_gets_no_note(self): + for module, run, _, _ in EXAMPLES: + with self.subTest(module.__name__), \ + stand_in_cloud(merge(FREE, PAID)): + output = run() + self.assertNotIn("paid Resource Key", output) + self.assertNotIn("Traceback", output) + + +def without(key, product, name): + """The properties of key without one of them.""" + products = {section: dict(properties) + for section, properties in key.items()} + del products[product][name] + return products + + +class FreePropertyMissingTests(unittest.TestCase): + """A key set up without a free property must not be told that the + property needs a paid key.""" + + def test_a_missing_free_property_is_not_named_in_the_note(self): + key = without(FREE, "ip", "RegisteredName") + for module, run, missing, shown in EXAMPLES[:2]: + with self.subTest(module.__name__), stand_in_cloud(key): + output = run() + self.assertEqual( + 1, output.count(shown(missing, module.CONTACT_US)), + output) + note = output[output.index("paid Resource Key"):] + self.assertNotIn("RegisteredName", note) + + def test_a_key_missing_only_a_free_property_gets_no_note(self): + key = without(merge(FREE, PAID), "ip", "RegisteredName") + for module, run, _, _ in EXAMPLES[:2]: + with self.subTest(module.__name__), stand_in_cloud(key): + output = run() + self.assertNotIn("paid Resource Key", output) + self.assertIn("RegisteredName", output) + + +class PaidKeyHelperTests(unittest.TestCase): + + def test_names_one_property_as_it(self): + self.assertEqual( + "This property needs a paid Resource Key: Country. If yours is " + "paid, add it on the configuration page. If it is free, contact " + "us about a paid one at https://example.test/", + ExampleUtils.get_paid_key_note( + ["Country"], "https://example.test/")) + + def test_names_several_properties_once_each_as_them(self): + self.assertEqual( + "These properties need a paid Resource Key: Country, Town. If " + "yours is paid, add them on the configuration page. If it is " + "free, contact us about a paid one at https://example.test/", + ExampleUtils.get_paid_key_note( + ["Country", "Town", "Country"], "https://example.test/")) + + +if __name__ == "__main__": + unittest.main() diff --git a/location/examples/cloud/example_utils.py b/location/examples/cloud/example_utils.py new file mode 100644 index 00000000..2e513b52 --- /dev/null +++ b/location/examples/cloud/example_utils.py @@ -0,0 +1,72 @@ +# ********************************************************************* +# 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. +# ********************************************************************* + +"""Helpers the location cloud examples share.""" + +import html + +# The cloud service gives a property the resource key is not entitled to +# with no value and a reason that contains this. +PAID_FEATURE = "paid feature" + + +def needs_paid_key(data, property_name): + """True when the resource key in use cannot return the property. The + results leave out a property the key does not include, or give it no + value with a reason that says it is a paid feature.""" + try: + value = data.get(property_name) + except Exception: # pylint: disable=broad-exception-caught + return True + if value is None: + return True + if value.has_value(): + return False + reason = value.no_value_message() or "" + return PAID_FEATURE in reason.lower() + + +def get_paid_key_note(missing, contact_us): + """What to do about the properties the resource key in use cannot + return, written once after an example has shown them. It reads right + for a free key and for a paid key set up without them. missing names the + properties as the example shows them, and the link is tagged with the + example's file, so that an enquiry can be traced to the example.""" + names = list(dict.fromkeys(missing)) + if len(names) == 1: + start = (f"This property needs a paid Resource Key: {names[0]}. " + "If yours is paid, add it") + else: + start = ("These properties need a paid Resource Key: " + f"{', '.join(names)}. If yours is paid, add them") + return (f"{start} on the configuration page. If it is free, contact us " + f"about a paid one at {contact_us}") + + +def get_paid_key_note_html(missing, contact_us): + """The paid key note as HTML for a page, with the contact link as a + link, or an empty string when nothing is missing.""" + if not missing: + return "" + link = html.escape(contact_us) + return html.escape(get_paid_key_note(missing, contact_us)).replace( + link, f'{link}') diff --git a/location/examples/cloud/gettingstarted.py b/location/examples/cloud/gettingstarted.py index 54366221..c0d7ef39 100644 --- a/location/examples/cloud/gettingstarted.py +++ b/location/examples/cloud/gettingstarted.py @@ -40,6 +40,20 @@ # and paste it into the code, replacing !!YOUR_RESOURCE_KEY!! below. # Alternatively, add a _51DEGREES_RESOURCE_KEY environment variable. import os +import sys +from pathlib import Path + +try: + # Imported as part of a package, as the tests do. + from .example_utils import get_paid_key_note, needs_paid_key +except ImportError: + # Run as a script, so the helper is read from the folder beside it. + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from example_utils import get_paid_key_note, needs_paid_key # pylint: disable=import-error + +# Where to ask about a paid resource key, for the properties a free key +# does not return. +CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-gettingstarted.py&utm_term=paid-resource-key" # Where to go next, printed when the example ends. FIND_OUT_MORE = [ @@ -64,7 +78,7 @@ https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-gettingstarted.py&utm_term=resource-key-required and set the _51DEGREES_RESOURCE_KEY environment variable to it, or paste it into the code in place of !!YOUR_RESOURCE_KEY!!. - To get a resource key with the properties used in this example go to https://51degrees.com/configure/GCrtGh1L?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-gettingstarted.py&utm_term=resource-key-required + To get a resource key set up for this example go to https://51degrees.com/configure/GCrtGh1L?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-gettingstarted.py&utm_term=resource-key-required """) else: @@ -88,7 +102,10 @@ flow_data.process() print("What country is at coordinates:" + longitude + ", " + latitude + "?") - if flow_data.location.country.has_value(): + if needs_paid_key(flow_data.location, "country"): + # The resource key in use cannot return the country. + print(get_paid_key_note(["Country"], CONTACT_US)) + elif flow_data.location.country.has_value(): print(flow_data.location.country.value()) else: print(flow_data.location.country.no_value_message()) diff --git a/location/examples/cloud/web.py b/location/examples/cloud/web.py index 6529e518..f4d4920f 100644 --- a/location/examples/cloud/web.py +++ b/location/examples/cloud/web.py @@ -49,6 +49,20 @@ # Alternatively, add a _51DEGREES_RESOURCE_KEY environment variable. import html import os +import sys +from pathlib import Path + +try: + # Imported as part of a package, as Flask does. + from .example_utils import get_paid_key_note_html, needs_paid_key +except ImportError: + # Run as a script, so the helper is read from the folder beside it. + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from example_utils import get_paid_key_note_html, needs_paid_key # pylint: disable=import-error + +# Where to ask about a paid resource key, for the properties a free key +# does not return. +CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-web.py&utm_term=paid-resource-key" # Where to go next, shown at the end of the page, and printed when there is # no resource key. @@ -73,6 +87,16 @@ def print_find_out_more(): print(f"\t{label}: {url}") +def paid_key_note_html(location): + """A paragraph saying what to do about the country, which the resource + key in use cannot return, with the contact link as a link, or nothing + when the key returns it.""" + if not needs_paid_key(location, "country"): + return "" + return ("" + + get_paid_key_note_html(["Country"], CONTACT_US) + "
") + + def find_out_more_html(): """The Find out more section for the end of the page. A repository is shown by its address, and any other link by its label.""" @@ -97,7 +121,7 @@ def find_out_more_html(): https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-web.py&utm_term=resource-key-required and set the _51DEGREES_RESOURCE_KEY environment variable to it, or paste it into the code in place of !!YOUR_RESOURCE_KEY!!. - To get a resource key with the properties used in this example go to https://51degrees.com/configure/GCrtGh1L?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-web.py&utm_term=resource-key-required + To get a resource key set up for this example go to https://51degrees.com/configure/GCrtGh1L?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=examples-cloud-web.py&utm_term=resource-key-required """) print_find_out_more() else: @@ -160,6 +184,9 @@ def server(): # The JavaScript created by the pipeline javascript = flowData.javascriptbuilder.javascript + # What to do when the resource key cannot return the country. + paid_key_note = paid_key_note_html(flowData.location) + # Generate the HTML output = "" @@ -197,6 +224,8 @@ def server(): """ + output += paid_key_note + # Where to go next. output += find_out_more_html() diff --git a/location/tests/test_paid_key_note.py b/location/tests/test_paid_key_note.py new file mode 100644 index 00000000..fb4ac9f4 --- /dev/null +++ b/location/tests/test_paid_key_note.py @@ -0,0 +1,204 @@ +# ********************************************************************* +# 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. +# ********************************************************************* + +""" +Runs the cloud examples against a stand-in for the cloud service. With a +key that cannot return the country, the getting started example must print +the paid key note once, ending with its own tagged contact link, and the +web example must show it on its page, with the link as a link. With a key +that returns the country, neither gives the note. The stand-in answers as +the cloud service does, so these tests need no key and no network. +""" + +import html +import http.server +import importlib.util +import io +import json +import os +import re +import runpy +import threading +import unittest +from contextlib import contextmanager, redirect_stdout +from pathlib import Path +from unittest import mock + +EXAMPLES = Path(__file__).resolve().parent.parent / "examples" / "cloud" + +# The location properties of a key without the country, each with the +# value the stand-in gives it. +WITHOUT_COUNTRY = {"Town": "Reading", "State": "England"} + +# The location properties of a key with the country. +WITH_COUNTRY = {**WITHOUT_COUNTRY, "Country": "United Kingdom"} + +# Some of the evidence keys the cloud service accepts. +EVIDENCE_KEYS = ["query.51D_Pos_latitude", "query.51D_Pos_longitude"] + +# Any resource key, as the stand-in does not check it. +RESOURCE_KEY = "stand-in-key" + +# A contact link as the UTM convention asks: exactly five parameters in +# this order. +CONTACT_LINK = re.compile( + r"https://51degrees\.com/contact-us\?utm_source=code&utm_medium=example" + r"&utm_campaign=51degrees-python&utm_content=([a-z0-9][a-z0-9._-]*)" + r"&utm_term=([a-z0-9][a-z0-9._-]{0,59})") + + +class StandInHandler(http.server.BaseHTTPRequestHandler): + """Answers the accessible properties, evidence keys and results requests + as the cloud service does for a key that carries the server's location + properties, and anything else with 404.""" + + def do_GET(self): + self.reply() + + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + self.reply() + + def reply(self): + properties = self.server.properties + path = self.path.split("?", 1)[0].lower() + if path.endswith("/accessibleproperties"): + self.answer(200, {"Products": {"location": { + "DataTier": "CloudV4Free", + "Properties": [ + {"Name": name, "Type": "String", "Category": "Location"} + for name in properties]}}}) + elif path.endswith("/evidencekeys"): + self.answer(200, EVIDENCE_KEYS) + elif path.endswith(".json"): + self.answer(200, { + "location": {name.lower(): value + for name, value in properties.items()}, + "javascriptProperties": []}) + else: + self.answer(404, {"errors": ["Not found."]}) + + def answer(self, status, body): + content = json.dumps(body).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + + def log_message(self, format, *args): + pass + + +@contextmanager +def stand_in_cloud(properties): + """A stand-in for the cloud service, on a free port of this machine, for + a key that carries properties, with the cloud endpoint and the resource + key in the environment.""" + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), StandInHandler) + server.properties = properties + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with mock.patch.dict(os.environ, { + "_51DEGREES_RESOURCE_KEY": RESOURCE_KEY, + "_51DEGREES_CLOUD_ENDPOINT": + f"http://127.0.0.1:{server.server_address[1]}/api/v4/"}): + yield server + finally: + server.shutdown() + server.server_close() + + +def run_getting_started(properties): + """Runs the getting started example as a script and returns what it + printed and its globals.""" + printed = io.StringIO() + with stand_in_cloud(properties), redirect_stdout(printed): + names = runpy.run_path( + str(EXAMPLES / "gettingstarted.py"), run_name="__main__") + return printed.getvalue(), names + + +def web_page(properties): + """Loads the web example as a module and returns its page and the + module.""" + with stand_in_cloud(properties): + spec = importlib.util.spec_from_file_location( + "location_cloud_web_paid_key", EXAMPLES / "web.py") + module = importlib.util.module_from_spec(spec) + with redirect_stdout(io.StringIO()): + spec.loader.exec_module(module) + try: + page = module.app.test_client().get("/").get_data(as_text=True) + finally: + module.pipeline.close() + return page, module + + +class LocationPaidKeyNoteTests(unittest.TestCase): + + def assert_tagged(self, link, file_name): + match = CONTACT_LINK.fullmatch(link) + self.assertIsNotNone(match, link) + self.assertEqual(f"examples-cloud-{file_name}", match.group(1)) + self.assertEqual("paid-resource-key", match.group(2)) + + def test_getting_started_without_the_country_gets_the_note_once(self): + output, names = run_getting_started(WITHOUT_COUNTRY) + self.assert_tagged(names["CONTACT_US"], "gettingstarted.py") + note = names["get_paid_key_note"](["Country"], names["CONTACT_US"]) + self.assertTrue(note.endswith(names["CONTACT_US"])) + self.assertEqual(1, output.count(note), output) + self.assertIn(note + "\n", output) + self.assertIn("Find out more:", output) + + def test_getting_started_with_the_country_gets_no_note(self): + output, _ = run_getting_started(WITH_COUNTRY) + self.assertNotIn("paid Resource Key", output) + self.assertIn("United Kingdom", output) + + def test_web_without_the_country_shows_the_note_once(self): + page, module = web_page(WITHOUT_COUNTRY) + self.assert_tagged(module.CONTACT_US, "web.py") + link = html.escape(module.CONTACT_US) + note = module.get_paid_key_note_html(["Country"], module.CONTACT_US) + self.assertIn(f"{link}", note) + self.assertEqual(1, page.count(note), page) + self.assertIn("Find out more", page) + + def test_web_with_the_country_shows_no_note(self): + page, _ = web_page(WITH_COUNTRY) + self.assertNotIn("paid Resource Key", page) + + def test_the_note_names_several_properties_as_them(self): + _, names = run_getting_started(WITH_COUNTRY) + self.assertEqual( + "These properties need a paid Resource Key: Country, Town. If " + "yours is paid, add them on the configuration page. If it is " + "free, contact us about a paid one at https://example.test/", + names["get_paid_key_note"]( + ["Country", "Town", "Country"], "https://example.test/")) + + +if __name__ == "__main__": + unittest.main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md index ca67efd2..fd27865a 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md @@ -37,9 +37,11 @@ those values, not the Flow Data. The examples call the cloud service with a resource key or a licence key. A resource key carries the list of properties it returns. Create one -carrying device detection and IP intelligence properties for free with the +carrying the free device detection and IP intelligence properties with the [configuration page](https://51degrees.com/configure?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-readme.md&utm_term=resource-key), -and set the `_51DEGREES_RESOURCE_KEY` environment variable to it. A +and set the `_51DEGREES_RESOURCE_KEY` environment variable to it. The +hardware and IP location properties the examples show need a paid resource +key, and the examples say so when the key cannot return them. A resource key limited to particular domains only answers a request whose origin is one of them, so set `_51DEGREES_CLOUD_REQUEST_ORIGIN` to one of its domains. diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py index 91b9c644..1514dbc5 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py @@ -38,10 +38,12 @@ # To run this example you need a resource key or a licence key. # # A resource key carries the list of properties it returns. Create one -# carrying device detection and IP intelligence properties for free at +# carrying the free device detection and IP intelligence properties at # https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=header # and set the _51DEGREES_RESOURCE_KEY environment variable to it, or pass it -# as the first argument. +# as the first argument. The hardware and IP location properties the +# example shows need a paid resource key, and the example says so when the +# key cannot return them. # # A licence key can be used on its own instead, by setting the # _51DEGREES_LICENSE_KEY environment variable to it. A licence key carries @@ -159,6 +161,19 @@ class GettingStartedConsole(): ("Time Zone Offset", "timezoneoffset"), ] + # The properties above that only a paid resource key returns. The free + # Lite data files have none of them. A free property that is missing + # shows its reason and gets no note. + PAID_PROPERTIES = { + "hardwarename", "hardwarevendor", "devicetype", + "country", "countrycode", "region", "state", "town", "latitude", + "longitude", "iprangestart", "iprangeend", "accuracyradiusmin", + "timezoneoffset"} + + # Where to ask about a paid resource key, for the properties a free key + # does not return. + CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=paid-resource-key" + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("Device detection", @@ -195,9 +210,15 @@ def values(cls): def run(self, pipeline, output): - # Carry out some sample detections. + # Carry out some sample detections, noting the properties that the + # key cannot return. + missing = [] for evidence in self.EVIDENCE: - self.analyse_evidence(evidence, pipeline, output) + missing += self.analyse_evidence(evidence, pipeline, output) + + # Say once what to do about them. + if missing: + output(ExampleUtils.get_paid_key_note(missing, self.CONTACT_US)) self.print_find_out_more(output) @@ -235,27 +256,38 @@ def analyse_evidence(self, evidence, pipeline, output): data.process() message = [] - self.append_results( + missing = self.append_results( "Device Detection Results:", ExampleUtils.get_element(data, "device"), self.DEVICE_PROPERTIES, message) message.append("") - self.append_results( + missing += self.append_results( "IP Intelligence Results:", ExampleUtils.get_element(data, "ip"), self.IP_PROPERTIES, message) output("\n".join(message) + "\n") + return missing - @staticmethod - def append_results(heading, element_data, properties, message): + @classmethod + def append_results(cls, heading, element_data, properties, message): + + """! + Add the heading and each property's value to message, and return + the labels of the paid properties that the key cannot return. + """ message.append(heading) message.append("-" * len(heading)) + missing = [] for label, property_name in properties: value = ExampleUtils.get_human_readable(element_data, property_name) message.append(f"\t{label}: {value}") + if property_name in cls.PAID_PROPERTIES and \ + ExampleUtils.needs_paid_key(element_data, property_name): + missing.append(label) + return missing def create_pipeline(logger, resource_key=None, license_key=None, @@ -304,7 +336,7 @@ def main(argv): "service is accessed using a resource key or a licence key. For " "more information see " "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=resource-key-required. " - "A resource key carrying the device detection and IP " + "A resource key carrying the free device detection and IP " "intelligence properties this example uses can be created for " "free at " "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=resource-key-required. " diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py index e96ddb08..cb8575be 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py @@ -36,10 +36,13 @@ # To run this example you need a resource key or a licence key. # # A resource key carries the list of properties it returns. Create one -# carrying device detection and IP intelligence properties for free at +# carrying the free device detection and IP intelligence properties at # https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=header # and set the _51DEGREES_RESOURCE_KEY environment variable to it, or pass it -# as the first argument. +# as the first argument. The hardware and IP location properties and the +# translated country list the page shows need a paid resource key. The page +# names the hardware and location properties the key cannot return, and +# shows no country list without it. # # A licence key can be used on its own instead, by setting the # _51DEGREES_LICENSE_KEY environment variable to it. A licence key carries @@ -151,6 +154,19 @@ COUNTRY_CODES_PROPERTY = "countrycodesgeographicalall" COUNTRY_NAMES_PROPERTY = "countrynamesgeographicalalltranslated" +# The properties above that only a paid resource key returns. The free +# Lite data files have none of them. The page names any the key cannot +# return in the paid key note. +PAID_PROPERTIES = { + "hardwarevendor", "hardwarename", "devicetype", + "iprangestart", "iprangeend", "country", "countrycode", "countrycode3", + "region", "state", "town", "latitude", "longitude", "areas", + "accuracyradiusmin", "timezoneoffset"} + +# Where to ask about a paid resource key, for the properties a free key +# does not return. +CONTACT_US = "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=paid-resource-key" + # Evidence values longer than this are shortened on the page. EVIDENCE_DISPLAY_LENGTH = 100 @@ -363,8 +379,21 @@ def page_model(flowdata): ip_rows.append(ip_row( "Countries (geographical):", options=country_options(countries))) + # Name the paid properties the key cannot return, once, under the + # tables. + missing = [ + label.rstrip(":") + for element_data, properties in ( + (device, DEVICE_PROPERTIES), + (ip, [(label, name) for label, name, _ in IP_PROPERTIES])) + for label, name in properties + if name in PAID_PROPERTIES and + ExampleUtils.needs_paid_key(element_data, name)] + return { "device_message": device_message, + "paid_key_note": ExampleUtils.get_paid_key_note_html( + missing, CONTACT_US), "device_rows": [ (label, ExampleUtils.get_value_or_unknown(device, name)) for label, name in DEVICE_PROPERTIES], @@ -469,7 +498,7 @@ def main(argv): "service is accessed using a resource key or a licence key. For " "more information see " "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=resource-key-required. " - "A resource key carrying the device detection and IP " + "A resource key carrying the free device detection and IP " "intelligence properties this example uses can be created for " "free at " "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=resource-key-required. " diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/templates/index.html b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/templates/index.html index 88648aa2..11c0ddd0 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/templates/index.html +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/templates/index.html @@ -121,6 +121,10 @@Evidence collected from the current request
diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py index 3bfb42ba..7e2f5bf0 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py @@ -25,6 +25,7 @@ environment and for turning property values into text. """ +import html import os import sys @@ -174,6 +175,60 @@ def get_human_readable(element_data, property_name, decimals=None): return f"{ExampleUtils.UNKNOWN} ({reason})" + # The cloud service gives a property the key in use is not entitled to + # with no value and a reason that contains this. + PAID_FEATURE = "paid feature" + + @staticmethod + def needs_paid_key(element_data, property_name): + """! + True when the key in use cannot return the property. The results + leave out a property the key does not include, or give it no value + with a reason that says it is a paid feature. + """ + + value = ExampleUtils.get_value(element_data, property_name) + if value is None: + return True + if value.has_value(): + return False + reason = value.no_value_message() or "" + return ExampleUtils.PAID_FEATURE in reason.lower() + + @staticmethod + def get_paid_key_note(missing, contact_us): + """! + What to do about the properties the key in use cannot return, + written once after an example has shown them. It reads right for a + free key and for a paid key set up without them. missing names the + properties as the example shows them, and the link is tagged with + the example's file, so that an enquiry can be traced to the example. + """ + + names = list(dict.fromkeys(missing)) + if len(names) == 1: + start = (f"This property needs a paid Resource Key: {names[0]}. " + "If yours is paid, add it") + else: + start = ("These properties need a paid Resource Key: " + f"{', '.join(names)}. If yours is paid, add them") + return (f"{start} on the configuration page. If it is free, contact " + f"us about a paid one at {contact_us}") + + @staticmethod + def get_paid_key_note_html(missing, contact_us): + """! + The paid key note as HTML for a page, with the contact link as a + link, or an empty string when nothing is missing. + """ + + if not missing: + return "" + link = html.escape(contact_us) + return html.escape( + ExampleUtils.get_paid_key_note(missing, contact_us)).replace( + link, f'{link}') + @staticmethod def get_value_or_unknown(element_data, property_name, decimals=None): """! diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_paid_key_note.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_paid_key_note.py new file mode 100644 index 00000000..cb1b7e57 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_paid_key_note.py @@ -0,0 +1,249 @@ +# ********************************************************************* +# 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. +# ********************************************************************* + +""" +Runs the mixed cloud console example against a stand-in for the cloud +service. With a key that cannot return the properties only a paid resource +key returns, as a free key or a paid key set up without them, the example +must print the paid key note once, ending with its own tagged contact link, +and end normally. With a key that returns them, it must print no note. The +stand-in answers as the cloud service does, so these tests need no key and +no network. +""" + +import http.server +import io +import json +import os +import re +import threading +import unittest +from contextlib import contextmanager, redirect_stdout +from unittest import mock + +from fiftyone_pipeline_core.logger import Logger + +from fiftyone_pipeline_examples.cloud.mixed import gettingstarted_console +from fiftyone_pipeline_examples.cloud.mixed.gettingstarted_web import ( + app as web) +from fiftyone_pipeline_examples.example_utils import ExampleUtils + +EXAMPLE = gettingstarted_console.GettingStartedConsole + +# The properties a free resource key returns, by section. +FREE = { + "device": ["ismobile", "platformname", "platformversion", "browsername", + "browserversion", "devicetype"], + "ip": ["registeredname", "registeredowner", "registeredcountry"], +} + +# Every property the example shows, by section, which a paid key set up +# with them returns. +EVERY = { + "device": [name for _, name in EXAMPLE.DEVICE_PROPERTIES], + "ip": [name for _, name in EXAMPLE.IP_PROPERTIES], +} + +# The labels of the paid properties a free key cannot return, as the note +# names them. +MISSING = [ + label for label, name in EXAMPLE.DEVICE_PROPERTIES + EXAMPLE.IP_PROPERTIES + if name in EXAMPLE.PAID_PROPERTIES + and name not in FREE["device"] + FREE["ip"]] + +# A key set up without a free property. +WITHOUT_REGISTERED_NAME = { + "device": FREE["device"], + "ip": [name for name in FREE["ip"] if name != "registeredname"]} + +# A key with every property but one free one. +ALL_BUT_REGISTERED_NAME = { + "device": EVERY["device"], + "ip": [name for name in EVERY["ip"] if name != "registeredname"]} + +# Some of the evidence keys the cloud service accepts. +EVIDENCE_KEYS = ["header.user-agent", "query.client-ip"] + +# Any resource key, as the stand-in does not check it. +RESOURCE_KEY = "stand-in-key" + +# The contact link as the UTM convention asks: exactly five parameters +# in this order. +CONTACT_LINK = re.compile( + r"https://51degrees\.com/contact-us\?utm_source=code&utm_medium=example" + r"&utm_campaign=51degrees-python&utm_content=([a-z0-9][a-z0-9._-]*)" + r"&utm_term=([a-z0-9][a-z0-9._-]{0,59})") + + +class StandInHandler(http.server.BaseHTTPRequestHandler): + """Answers the accessible properties, evidence keys and results requests + as the cloud service does for a key that carries the server's + properties, giving each one a value, and anything else with 404.""" + + def do_GET(self): + self.reply() + + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + self.reply() + + def reply(self): + sections = self.server.sections + path = self.path.split("?", 1)[0].lower() + if path.endswith("/accessibleproperties"): + self.answer(200, {"Products": { + section: { + "DataTier": "CloudV4Free", + "Properties": [ + {"Name": name, "Type": "String", "Category": ""} + for name in names]} + for section, names in sections.items()}}) + elif path.endswith("/evidencekeys"): + self.answer(200, EVIDENCE_KEYS) + elif path.endswith(".json"): + results = {section: {name: f"value of {name}" for name in names} + for section, names in sections.items()} + results["javascriptProperties"] = [] + self.answer(200, results) + else: + self.answer(404, {"errors": ["Not found."]}) + + def answer(self, status, body): + content = json.dumps(body).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + + def log_message(self, format, *args): + pass + + +@contextmanager +def stand_in_cloud(sections): + """A stand-in for the cloud service, on a free port of this machine, for + a key that carries the properties in sections.""" + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), StandInHandler) + server.sections = sections + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}/api/v4/" + finally: + server.shutdown() + server.server_close() + + +def run_example(sections): + """Runs the example's main with a resource key and the stand-in as its + cloud service, and returns what it printed.""" + printed = io.StringIO() + with stand_in_cloud(sections) as endpoint, mock.patch.dict(os.environ), \ + redirect_stdout(printed): + for name in (ExampleUtils.LICENSE_KEY_ENV_VAR, + ExampleUtils.CLOUD_REQUEST_ORIGIN_ENV_VAR): + os.environ.pop(name, None) + os.environ[ExampleUtils.RESOURCE_KEY_ENV_VAR] = RESOURCE_KEY + os.environ[ExampleUtils.CLOUD_ENDPOINT_ENV_VAR] = endpoint + gettingstarted_console.main([]) + return printed.getvalue() + + +def web_page(sections): + """Builds the mixed web example's page with the stand-in as its cloud + service, and returns it.""" + with stand_in_cloud(sections) as endpoint: + pipeline = web.create_pipeline( + Logger(min_level="error"), resource_key=RESOURCE_KEY, + cloud_endpoint=endpoint) + try: + page = web.create_app(pipeline).test_client().get( + "/", headers={"User-Agent": "Mozilla/5.0 (iPhone)"}) + return page.get_data(as_text=True) + finally: + pipeline.close() + + +class MixedConsolePaidKeyNoteTests(unittest.TestCase): + + def test_the_contact_link_is_tagged_with_its_file(self): + match = CONTACT_LINK.fullmatch(EXAMPLE.CONTACT_US) + self.assertIsNotNone(match, EXAMPLE.CONTACT_US) + self.assertEqual( + "fiftyone_pipeline_cloudrequestengine-examples-src-" + "fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py", + match.group(1)) + self.assertEqual("paid-resource-key", match.group(2)) + + def test_a_key_without_the_paid_properties_gets_the_note_once(self): + output = run_example(FREE) + note = ExampleUtils.get_paid_key_note(MISSING, EXAMPLE.CONTACT_US) + self.assertEqual(1, output.count(note), output) + self.assertIn(note + "\n", output) + self.assertIn("Find out more:", output) + self.assertNotIn("Traceback", output) + + def test_a_key_with_the_paid_properties_gets_no_note(self): + output = run_example(EVERY) + self.assertNotIn("paid Resource Key", output) + self.assertIn("value of hardwarevendor", output) + self.assertIn("Find out more:", output) + + def test_a_missing_free_property_is_not_named_in_the_note(self): + output = run_example(WITHOUT_REGISTERED_NAME) + note = ExampleUtils.get_paid_key_note(MISSING, EXAMPLE.CONTACT_US) + self.assertEqual(1, output.count(note), output) + self.assertNotIn("Registered Name", note) + + def test_a_key_missing_only_a_free_property_gets_no_note(self): + output = run_example(ALL_BUT_REGISTERED_NAME) + self.assertNotIn("paid Resource Key", output) + + def test_the_web_page_shows_the_note_once(self): + page = web_page(FREE) + missing = [ + label.rstrip(":") + for label, name in web.DEVICE_PROPERTIES + [ + (label, name) for label, name, _ in web.IP_PROPERTIES] + if name in web.PAID_PROPERTIES + and name not in FREE["device"] + FREE["ip"]] + note = ExampleUtils.get_paid_key_note_html(missing, web.CONTACT_US) + self.assertEqual(1, page.count(note), page) + self.assertIsNotNone(CONTACT_LINK.fullmatch(web.CONTACT_US)) + + def test_the_web_page_with_the_paid_properties_shows_no_note(self): + page = web_page({ + "device": [name for _, name in web.DEVICE_PROPERTIES], + "ip": [name for _, name, _ in web.IP_PROPERTIES]}) + self.assertNotIn("paid Resource Key", page) + + def test_the_note_names_one_property_as_it(self): + self.assertEqual( + "This property needs a paid Resource Key: Town. If yours is " + "paid, add it on the configuration page. If it is free, contact " + "us about a paid one at https://example.test/", + ExampleUtils.get_paid_key_note(["Town"], "https://example.test/")) + + +if __name__ == "__main__": + unittest.main() diff --git a/pipeline/fiftyone_pipeline_did/examples/fodid_example.py b/pipeline/fiftyone_pipeline_did/examples/fodid_example.py index a52b3c93..faab5fbf 100644 --- a/pipeline/fiftyone_pipeline_did/examples/fodid_example.py +++ b/pipeline/fiftyone_pipeline_did/examples/fodid_example.py @@ -31,7 +31,9 @@ envelopes. """ -from owid import Crypto, Creator +# OWID comes from the package's own copy, so the example runs with only +# the published fiftyone_pipeline_did package installed. +from fiftyone_pipeline_did._owid import Crypto, Creator from fiftyone_pipeline_did import FodId diff --git a/pipeline/fiftyone_pipeline_did/readme.md b/pipeline/fiftyone_pipeline_did/readme.md index 085997c2..ead0b7ef 100644 --- a/pipeline/fiftyone_pipeline_did/readme.md +++ b/pipeline/fiftyone_pipeline_did/readme.md @@ -76,8 +76,10 @@ submodule stays where it is and the same script puts the copy in place. Run `pwsh ./setup.ps1` from the repository root, or `git submodule update --init --recursive` followed by `pwsh ./ci/copy-owid-source.ps1`, before building or running the tests. The -tests and examples import OWID from the submodule under its own name, `owid`, -which is how they build signed envelopes to test against. +tests import OWID from the submodule under its own name, `owid`, which is how +they build signed envelopes to test against. The example imports it from the +package's own copy, `fiftyone_pipeline_did._owid`, so it runs with only the +published package installed. The OWID types the public API refers to are re-exported from the package itself, so a caller never has to reach into the private module. Catch @@ -88,6 +90,10 @@ from `FodId.signature_status`. An `Owid` only ever comes from a successful parse or from an OWID `Creator` that signs one into being, so there is no way to hold an unsigned or partly built envelope. +The offline example is the one exception. It imports `Crypto` and `Creator` +from `fiftyone_pipeline_did._owid` only to sign a sample 51Did, because only +the cloud issues real ones. A caller reading 51Dids does not need them. + ## Usage ```python diff --git a/pipeline/fiftyone_pipeline_did/tests/test_fodid_example.py b/pipeline/fiftyone_pipeline_did/tests/test_fodid_example.py index 39f5e22b..861bddfc 100644 --- a/pipeline/fiftyone_pipeline_did/tests/test_fodid_example.py +++ b/pipeline/fiftyone_pipeline_did/tests/test_fodid_example.py @@ -25,9 +25,11 @@ import importlib.util import io +import sys import unittest from contextlib import redirect_stdout from pathlib import Path +from unittest import mock EXAMPLE = Path(__file__).resolve().parents[1] / "examples" / "fodid_example.py" @@ -71,6 +73,17 @@ def test_run_reads_back_the_51did_it_signed(self): self.assertEqual("False", field(output, "Same envelope (base64)")) self.assertEqual("True", field(output, "Same match key")) + def test_runs_without_the_owid_package(self): + # The published package carries OWID only as its private module + # fiftyone_pipeline_did._owid, so the example must not need the + # owid package that the tests install from the submodule. + with mock.patch.dict(sys.modules, {"owid": None}): + example = load_example() + printed = io.StringIO() + with redirect_stdout(printed): + example.run() + self.assertEqual("True", field(printed.getvalue(), "Verifies")) + if __name__ == "__main__": unittest.main()