From 4af0a8a40d795e074869a3b5f7e9270f350fbab6 Mon Sep 17 00:00:00 2001 From: Rakesh Bakhem Date: Sat, 5 Dec 2026 08:06:19 +0000 Subject: [PATCH 1/4] FIX: Point the cloud examples at contact-us when a key lacks a paid property, and run the 51Did example on the published package --- .../cloud/configurator_console.py | 18 + .../cloud/failuretomatch.py | 12 + .../cloud/gettingstarted_console.py | 31 +- .../example_utils.py | 59 ++++ .../onpremise/offlineprocessing.py | 25 +- .../onpremise/performance.py | 15 + .../tests/test_cloud_paid_key_note.py | 323 ++++++++++++++++++ .../tests/test_missing_evidence_file.py | 112 ++++++ .../cloud/countries_console.py | 15 +- .../cloud/getallproperties_console.py | 15 + .../cloud/gettingstarted_console.py | 18 +- .../cloud/gettingstarted_web/app.py | 21 ++ .../cloud/mixed_console.py | 17 +- .../example_utils.py | 43 +++ .../tests/test_cloud_paid_key_note.py | 306 +++++++++++++++++ location/examples/cloud/example_utils.py | 60 ++++ location/examples/cloud/gettingstarted.py | 19 +- location/examples/cloud/web.py | 31 ++ location/tests/test_paid_key_note.py | 204 +++++++++++ .../cloud/mixed/gettingstarted_console.py | 28 +- .../example_utils.py | 40 +++ .../tests/test_cloud_mixed_paid_key_note.py | 190 +++++++++++ .../examples/fodid_example.py | 4 +- pipeline/fiftyone_pipeline_did/readme.md | 6 +- .../tests/test_fodid_example.py | 13 + 25 files changed, 1597 insertions(+), 28 deletions(-) create mode 100644 device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py create mode 100644 device-detection/fiftyone_devicedetection_examples/tests/test_missing_evidence_file.py create mode 100644 ip-intelligence/fiftyone_ipintelligence_examples/tests/test_cloud_paid_key_note.py create mode 100644 location/examples/cloud/example_utils.py create mode 100644 location/tests/test_paid_key_note.py create mode 100644 pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_paid_key_note.py 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..99676763 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,13 @@ 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. +PAID_PROPERTIES = ["hardwarevendor", "hardwarename"] + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("Device detection", @@ -91,6 +98,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 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(property_name) + if missing: + output(ExampleUtils.get_paid_key_note(missing, CONTACT_US)) + ExampleUtils.print_find_out_more(FIND_OUT_MORE, output) def main(argv): 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..dc7e918f 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", @@ -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.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_console.py index 7d525358..674f2de1 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 = [ diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py index ac2de32d..d9c34e43 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py @@ -138,6 +138,65 @@ def get_human_readable(device, property): return f"Unknown ({reason})" + # 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. + """ + + try: + value = data.get(property_name) + except Exception: + return True + 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_missing_evidence_file_message(file_name, argument): + """! + The message shown when the file of evidence records an example reads + is missing, saying where the file goes. argument says how the + example takes the file's path instead. + """ + + return (f"The evidence file '{file_name}' is missing, so the example " + "cannot run. It goes in the " + f"'{ExampleUtils.DATA_FOLDER}' folder of a clone of this " + f"repository, beside '{file_name}.link', where the example " + "downloads it when it can. Or give its path " + f"{argument}.") + @staticmethod def get_resource_key(): return ExampleUtils.__get_env_variable( diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/offlineprocessing.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/offlineprocessing.py index d6320371..c210edfe 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/offlineprocessing.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/offlineprocessing.py @@ -242,14 +242,25 @@ def main(argv): # This file contains the 20,000 most commonly seen combinations of header values # that are relevant to device detection. For example, User-Agent and UA-CH headers. evidence_file = argv[1] if len(argv) > 1 else ExampleUtils.find_file(EVIDENCE_FILE_NAME) - # Finally, get the location for the output file. Use the same location as the - # evidence if a path is not supplied on the command line. - output_file = argv[2] if len(argv) > 2 else Path.joinpath(Path(evidence_file).absolute().parent, "offline-processing-output.yml") # Configure a logger to output to the console. logger = Logger(min_level="info") - if (data_file != None): + if data_file is None: + logger.log("error", + "Failed to find a device detection data file. Make sure the " + + "data submodule is there, by running " + + "`git submodule update --init --recursive`, and run this " + + "example again to download the file.") + if evidence_file is None: + # The file could not be found or downloaded, so say where it goes. + logger.log("error", ExampleUtils.get_missing_evidence_file_message( + EVIDENCE_FILE_NAME, "as the second argument")) + if data_file is not None and evidence_file is not None: + # Finally, get the location for the output file. Use the same + # location as the evidence if a path is not supplied on the command + # line. + output_file = argv[2] if len(argv) > 2 else Path.joinpath(Path(evidence_file).absolute().parent, "offline-processing-output.yml") with open(output_file, "w") as output: with open(evidence_file, "r") as input: needs_enterprise = OfflineProcessing().run( @@ -257,12 +268,6 @@ def main(argv): print(f"Processing complete. See results in: '{output_file}'") if needs_enterprise: print(ExampleUtils.get_enterprise_note(CONTACT_US)) - else: - logger.log("error", - "Failed to find a device detection data file. Make sure the " + - "data submodule is there, by running " + - "`git submodule update --init --recursive`, and run this " + - "example again to download the file.") # The results are in the output file, so the links are printed to the # console. diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/performance.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/performance.py index 697cf96b..348cf00d 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/performance.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/onpremise/performance.py @@ -44,6 +44,7 @@ import argparse import json +import sys import time import multiprocessing as mp @@ -174,6 +175,20 @@ def run(data_file, skip = False): if args.evidence_file == "": args.evidence_file = ExampleUtils.find_file(EVIDENCE_FILE_NAME) + # Without both files there is nothing to time, so say which is missing + # and where it goes, and end. + if args.data_file is None: + print("Failed to find a device detection data file. Make sure the " + "data submodule is there, by running " + "`git submodule update --init --recursive`, and run this " + "example again to download the file.") + if args.evidence_file is None: + print(ExampleUtils.get_missing_evidence_file_message( + EVIDENCE_FILE_NAME, "with the -e option")) + if args.data_file is None or args.evidence_file is None: + ExampleUtils.print_find_out_more(FIND_OUT_MORE) + sys.exit(0) + # First we read the user agent of each of the 20000 evidence records as a list user_agents = ExampleUtils.read_user_agents(args.evidence_file) diff --git a/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py b/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py new file mode 100644 index 00000000..f0e6ee76 --- /dev/null +++ b/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py @@ -0,0 +1,323 @@ +# ********************************************************************* +# 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 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 ast +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 + +import json5 + +from fiftyone_pipeline_core.logger import Logger + +from fiftyone_devicedetection_examples.example_utils import ExampleUtils +from fiftyone_devicedetection_examples.cloud import configurator_console +from fiftyone_devicedetection_examples.cloud import gettingstarted_console + +# The failure to match example is a script that does its work when it is +# imported, so it is only ever run, never imported. +FAILURE_TO_MATCH = "fiftyone_devicedetection_examples.cloud.failuretomatch" + +# The properties a free resource key returns, as the cloud service names +# them, with their types. +FREE_PROPERTIES = { + "IsMobile": "Boolean", + "PlatformName": "String", + "PlatformVersion": "String", + "BrowserName": "String", + "BrowserVersion": "String", +} + +# The properties only a paid resource key returns. +PAID_PROPERTIES = { + "HardwareVendor": "String", + "HardwareName": "Array", +} + +# The values the stand-in gives each property. +VALUES = { + "ismobile": True, + "platformname": "Android", + "platformversion": "9.0", + "browsername": "Samsung Browser", + "browserversion": "10.1", + "hardwarevendor": "Samsung", + "hardwarename": ["Galaxy S9"], +} + +# Some of the evidence keys the cloud service accepts. +EVIDENCE_KEYS = [ + "header.user-agent", "header.sec-ch-ua", "header.sec-ch-ua-mobile", + "header.sec-ch-ua-platform", "header.sec-ch-ua-platform-version"] + +# Any resource key, as the stand-in does not check it. +RESOURCE_KEY = "stand-in-key" + +# A contact link as rule 2 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 name. +CONTENT = ("fiftyone_devicedetection_examples-src-" + "fiftyone_devicedetection_examples-cloud-") + + +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, 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): + properties = self.server.properties + path = self.path.split("?", 1)[0].lower() + if path.endswith("/accessibleproperties"): + self.answer(200, {"Products": {"device": { + "DataTier": "CloudV4Free", + "Properties": [ + {"Name": name, "Type": kind, "Category": "Device"} + for name, kind in properties.items()]}}}) + elif path.endswith("/evidencekeys"): + self.answer(200, EVIDENCE_KEYS) + elif path.endswith(".json"): + self.answer(200, { + "device": {name.lower(): VALUES[name.lower()] + for name in properties}, + "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, and the cloud endpoint, the resource key + and nothing else among the examples' settings 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): + os.environ.pop(ExampleUtils.LICENSE_KEY_ENV_VAR, None) + os.environ[ExampleUtils.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_getting_started(): + config = json5.loads( + Path(gettingstarted_console.__file__).with_name( + "gettingstarted_console.json").read_text(encoding="utf-8")) + ExampleUtils.set_resource_key_in_config(config, RESOURCE_KEY) + printed = [] + gettingstarted_console.GettingStartedConsole().run( + config, Logger(min_level="error"), printed.append) + return "\n".join(printed) + + +def run_configurator(): + printed = [] + configurator_console.ConfiguratorConsole().run( + RESOURCE_KEY, Logger(min_level="error"), printed.append) + return "\n".join(printed) + + +def run_failure_to_match(): + printed = io.StringIO() + with redirect_stdout(printed): + runpy.run_module(FAILURE_TO_MATCH, run_name="__main__") + return printed.getvalue() + + +def contact_us(module_name): + """The CONTACT_US link of an example, read from its file without + running it.""" + path = importlib.util.find_spec(module_name).origin + tree = ast.parse(Path(path).read_text(encoding="utf-8")) + for node in tree.body: + if isinstance(node, ast.Assign) and any( + getattr(target, "id", None) == "CONTACT_US" + for target in node.targets): + return path, ast.literal_eval(node.value) + return path, None + + +# Each example, how it is run, and the properties its note names. +EXAMPLES = [ + (gettingstarted_console.__name__, run_getting_started, + ["Hardware Vendor", "Hardware Name"]), + (configurator_console.__name__, run_configurator, + ["hardwarevendor", "hardwarename"]), + (FAILURE_TO_MATCH, run_failure_to_match, ["HardwareVendor"]), +] + + +class PaidKeyNoteTests(unittest.TestCase): + + def test_each_contact_link_is_tagged_with_its_file(self): + for name, _, _ in EXAMPLES: + with self.subTest(name): + path, link = contact_us(name) + match = CONTACT_LINK.fullmatch(link or "") + self.assertIsNotNone(match, link) + self.assertEqual(CONTENT + Path(path).name, 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 name, run, missing in EXAMPLES: + with self.subTest(name), stand_in_cloud(FREE_PROPERTIES): + output = run() + note = ExampleUtils.get_paid_key_note( + missing, contact_us(name)[1]) + self.assertEqual(1, output.count(note), output) + self.assertIn(note + "\n", output + "\n") + self.assertIn("Find out more:", output) + self.assertNotIn("Traceback", output) + + def test_a_key_with_the_paid_properties_gets_no_note(self): + for name, run, _ in EXAMPLES: + with self.subTest(name), stand_in_cloud( + {**FREE_PROPERTIES, **PAID_PROPERTIES}): + output = run() + self.assertNotIn("paid Resource Key", output) + self.assertIn("Samsung", output) + + +class FakeValue: + """A property value as the cloud engines give one.""" + + def __init__(self, value=None, reason=None): + self._value = value + self._reason = reason + + def has_value(self): + return self._value is not None + + def value(self): + return self._value + + def no_value_message(self): + return self._reason + + +class MissingProperty(Exception): + """Raised for a property the element data does not hold.""" + + +class FakeData: + """Element data holding the values given, which raises for any other + property, as cloud element data does.""" + + def __init__(self, **values): + self.values = values + + def get(self, name): + if name not in self.values: + raise MissingProperty(f"Property {name} not found in device") + return self.values[name] + + +class PaidKeyHelperTests(unittest.TestCase): + + def test_names_one_property_as_it(self): + self.assertEqual( + "This property needs a paid Resource Key: HardwareVendor. 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( + ["HardwareVendor"], "https://example.test/")) + + def test_names_several_properties_once_each_as_them(self): + self.assertEqual( + "These properties need a paid Resource Key: HardwareVendor, " + "HardwareName. 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( + ["HardwareVendor", "HardwareName", "HardwareVendor"], + "https://example.test/")) + + def test_needs_a_paid_key_for_a_property_left_out(self): + self.assertTrue(ExampleUtils.needs_paid_key(FakeData(), "x")) + self.assertTrue(ExampleUtils.needs_paid_key(None, "x")) + + def test_needs_a_paid_key_for_a_paid_feature(self): + data = FakeData(x=FakeValue(reason=( + "HardwareVendor is a paid feature. You need a licence key to " + "retrieve data."))) + self.assertTrue(ExampleUtils.needs_paid_key(data, "x")) + + def test_needs_no_paid_key_for_a_value_or_another_reason(self): + self.assertFalse(ExampleUtils.needs_paid_key( + FakeData(x=FakeValue("Samsung")), "x")) + self.assertFalse(ExampleUtils.needs_paid_key( + FakeData(x=FakeValue(reason="No matching profiles.")), "x")) + + +if __name__ == "__main__": + unittest.main() diff --git a/device-detection/fiftyone_devicedetection_examples/tests/test_missing_evidence_file.py b/device-detection/fiftyone_devicedetection_examples/tests/test_missing_evidence_file.py new file mode 100644 index 00000000..8a9411e5 --- /dev/null +++ b/device-detection/fiftyone_devicedetection_examples/tests/test_missing_evidence_file.py @@ -0,0 +1,112 @@ +# ********************************************************************* +# 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 offline processing and performance examples, as python -m runs +them, in a stand-in checkout where the file of evidence records is missing +and its download fails, because the data repository's script there +downloads nothing. Each must say plainly that the evidence file is missing +and where it goes, end normally with its Find out more section, and never +stop with a traceback. The Lite data file is given as an argument, and +nothing is downloaded. +""" + +import os +import subprocess +import sys +import tempfile +import unittest + +from fiftyone_devicedetection_examples.example_utils import ExampleUtils +from fiftyone_devicedetection_shared.example_constants import \ + EVIDENCE_FILE_NAME, LITE_DATAFILE_NAME + +# Stops a run that never finishes. +HANG_TIMEOUT_SECONDS = 300 + +# The settings a fresh clone does not have. +SETTINGS = ("_51DEGREES_DD_PATH", "_51DEGREES_LICENSE_KEY") + + +class MissingEvidenceFileTests(unittest.TestCase): + + def setUp(self): + self.data_file = ExampleUtils.find_file(LITE_DATAFILE_NAME) + self.assertIsNotNone( + self.data_file, f"{LITE_DATAFILE_NAME} was not found") + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.checkout = folder.name + data = os.path.join(self.checkout, "cxx", "data") + os.makedirs(os.path.join(data, "device-detection")) + # The evidence file's link, so the example tries to download it, + # and scripts that download nothing, so the download fails. + with open(os.path.join(data, "device-detection", + EVIDENCE_FILE_NAME + ".link"), "w", + encoding="utf-8"): + pass + for script in ("get-data-files.sh", "get-data-files.ps1"): + with open(os.path.join(data, script), "w", + encoding="utf-8") as file: + file.write("exit 1\n") + + def run_example(self, module, *arguments): + environment = {name: value for name, value in os.environ.items() + if name not in SETTINGS} + finished = subprocess.run( + [sys.executable, "-m", module, *arguments], + capture_output=True, text=True, env=environment, + cwd=self.checkout, timeout=HANG_TIMEOUT_SECONDS, check=False) + output = finished.stdout + finished.stderr + self.assertEqual(0, finished.returncode, output) + self.assertNotIn("Traceback", output) + self.assertIn("Find out more:", output) + self.assertFalse(os.path.exists(os.path.join( + self.checkout, "cxx", "data", "device-detection", + EVIDENCE_FILE_NAME))) + return output + + def test_offline_processing_says_the_evidence_file_is_missing(self): + output = self.run_example( + "fiftyone_devicedetection_examples.onpremise.offlineprocessing", + self.data_file) + self.assertIn(ExampleUtils.get_missing_evidence_file_message( + EVIDENCE_FILE_NAME, "as the second argument"), output) + self.assertNotIn("Processing complete", output) + + def test_performance_says_the_evidence_file_is_missing(self): + output = self.run_example( + "fiftyone_devicedetection_examples.onpremise.performance", + "-d", self.data_file) + self.assertIn(ExampleUtils.get_missing_evidence_file_message( + EVIDENCE_FILE_NAME, "with the -e option"), output) + self.assertNotIn("Processing ", output) + + def test_the_message_says_where_the_file_goes(self): + message = ExampleUtils.get_missing_evidence_file_message( + EVIDENCE_FILE_NAME, "as the second argument") + self.assertIn(f"'{EVIDENCE_FILE_NAME}' is missing", message) + self.assertIn(ExampleUtils.DATA_FOLDER, message) + + +if __name__ == "__main__": + unittest.main() diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py index 66d14fa4..daa736cd 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py @@ -66,8 +66,14 @@ # The line that introduces the "All" list of an address. LIST_HEADING = "Every country, most likely first:" -# Where to create a resource key that carries the translated country names. -CONFIGURE = "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-countries_console.py&utm_term=key-lacks-countries" +# The translated country names, which only a paid resource key returns. +TRANSLATED_PROPERTIES = [ + "CountryNamesGeographicalTranslated", + "CountryNamesGeographicalAllTranslated"] + +# 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-countries_console.py&utm_term=paid-resource-key" # Where to go next, printed when the example ends. FIND_OUT_MORE = [ @@ -104,9 +110,8 @@ def run(self, resource_key, logger, output, cloud_endpoint = None): for evidence in EVIDENCE_VALUES: self.analyse_evidence(evidence, pipeline, output) else: - output( - "The resource key in use does not carry the translated " - f"country names. Create a key that does at {CONFIGURE}\n") + output(ExampleUtils.get_paid_key_note( + TRANSLATED_PROPERTIES, CONTACT_US) + "\n") def analyse_evidence(self, evidence, pipeline, output): diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py index 171effa4..17a876b2 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py @@ -46,6 +46,14 @@ # Long values are truncated to this many characters for readability. MAX_VALUE_LENGTH = 200 +# Properties that only a paid resource key returns, which the list above +# leaves out when the key in use cannot return them. +PAID_PROPERTIES = ["Country", "Town"] + +# 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-getallproperties_console.py&utm_term=paid-resource-key" + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("IP intelligence", @@ -91,6 +99,13 @@ def analyse_evidence(self, ip_address, pipeline, output): output(f"\t{property_name} = " f"{self.get_value_to_output(ip_data, property_name)}") + # The list only holds what the key returns, so say once what to do + # about the paid properties it cannot return. + missing = [name for name in PAID_PROPERTIES + if ExampleUtils.needs_paid_key(ip_data, name.lower())] + if missing: + output(ExampleUtils.get_paid_key_note(missing, CONTACT_US)) + def get_value_to_output(self, ip_data, property_name): # Retrieve the value via the engine. Missing properties return a # readable "Unknown" message rather than raising. diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py index 5f70133a..713575ff 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py @@ -74,6 +74,10 @@ "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_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-gettingstarted_console.py&utm_term=paid-resource-key" + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("IP intelligence", @@ -105,9 +109,15 @@ def run(self, resource_key, logger, output, cloud_endpoint = None): .add_logger(logger) \ .build() - # carry out some sample lookups + # carry out some sample lookups, noting the properties that the + # resource key cannot return + missing = [] for values in EVIDENCE_VALUES: - 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)) def analyseEvidence(self, evidence, pipeline, output): @@ -142,9 +152,13 @@ def analyseEvidence(self, evidence, pipeline, output): # Display the results of the lookup. See the property dictionary # at https://51degrees.com/developers/property-dictionary?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-gettingstarted_console.py&utm_term=analyseevidence for # details of all available properties. + missing = [] for name in OUTPUT_PROPERTIES: self.outputValue(ip_data, name, message) + if ExampleUtils.needs_paid_key(ip_data, name.lower()): + missing.append(name) output("".join(message)) + return missing def outputValue(self, ip_data, name, message): # Individual result values have a wrapper called diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py index 117c1fbf..6bb8b2cb 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py @@ -43,6 +43,8 @@ # read the values it needs from the Flow Data first and pass those values, # not the Flow Data. +import html + from flask import Flask, request from fiftyone_pipeline_core.logger import Logger @@ -51,6 +53,10 @@ from fiftyone_ipintelligence_examples.example_utils import ExampleUtils from fiftyone_ipintelligence_shared.constants import Constants +# 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-gettingstarted_web-app.py&utm_term=paid-resource-key" + # Where to go next, shown at the end of the page. FIND_OUT_MORE = [ ("IP intelligence", @@ -79,6 +85,19 @@ def get_value(ip_data, property): return ExampleUtils.get_human_readable(ip_data, property) +def get_paid_key_note_html(ip_data): + """! + A paragraph saying what to do about the country, which only a paid + resource key returns, with the contact link as a link, or nothing when + the key returns it. + """ + if not ExampleUtils.needs_paid_key(ip_data, "country"): + return "" + note = html.escape(ExampleUtils.get_paid_key_note(["Country"], CONTACT_US)) + link = html.escape(CONTACT_US) + return "

" + note.replace(link, f'{link}') + "

" + + @app.route("/") def index(): @@ -107,7 +126,9 @@ def index(): + {get_paid_key_note_html(ip_data)}

Add ?client-ip=x.x.x.x to the url to lookup a different address.

{ExampleUtils.get_find_out_more_html(FIND_OUT_MORE)} """ 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..bde818b9 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,10 @@ "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 +135,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 +158,21 @@ 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 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 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..dfe146f6 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,49 @@ 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_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..5cfaf133 --- /dev/null +++ b/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_cloud_paid_key_note.py @@ -0,0 +1,306 @@ +# ********************************************************************* +# 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 rule 2 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) + + +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..8dd5045b --- /dev/null +++ b/location/examples/cloud/example_utils.py @@ -0,0 +1,60 @@ +# ********************************************************************* +# 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.""" + +# 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}") diff --git a/location/examples/cloud/gettingstarted.py b/location/examples/cloud/gettingstarted.py index 54366221..9d1dea98 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 = [ @@ -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..803693a7 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, 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-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,18 @@ 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 "" + note = html.escape(get_paid_key_note(["Country"], CONTACT_US)) + link = html.escape(CONTACT_US) + return ("") + + 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.""" @@ -160,6 +186,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 +226,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..5b52dd93 --- /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 rule 2 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 = html.escape(module.get_paid_key_note( + ["Country"], module.CONTACT_US)).replace( + link, f"{link}") + 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/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..d5323534 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 @@ -159,6 +159,10 @@ class GettingStartedConsole(): ("Time Zone Offset", "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 +199,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 +245,37 @@ 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): + """! + Add the heading and each property's value to message, and return + the labels of the 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 ExampleUtils.needs_paid_key(element_data, property_name): + missing.append(label) + return missing def create_pipeline(logger, resource_key=None, license_key=None, 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..2aaf4e7b 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 @@ -174,6 +174,46 @@ 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_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..fded1aba --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_paid_key_note.py @@ -0,0 +1,190 @@ +# ********************************************************************* +# 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_examples.cloud.mixed import gettingstarted_console +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 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 not in FREE["device"] + FREE["ip"]] + +# 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 rule 2 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() + + +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_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..7c388dfb 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 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() From 2f5e62228f991b80400d2cb13e1b02ee2f5640b4 Mon Sep 17 00:00:00 2001 From: Rakesh Bakhem Date: Sat, 5 Dec 2026 08:34:05 +0000 Subject: [PATCH 2/4] FIX: Note only the paid properties a key lacks, and show the note on the cloud web pages --- .../cloud/configurator_console.py | 15 ++-- .../cloud/failuretomatch.py | 2 +- .../cloud/gettingstarted_console.json | 4 +- .../cloud/gettingstarted_console.py | 2 +- .../cloud/gettingstarted_web/app.py | 24 ++++++ .../gettingstarted_web/templates/index.html | 3 + .../cloud/useragentclienthints_web/app.py | 24 ++++++ .../templates/index.html | 3 + .../example_utils.py | 15 ++++ .../tests/test_cloud_paid_key_note.py | 75 ++++++++++++++++++- .../cloud/countries_console.py | 4 +- .../cloud/getallproperties_console.py | 2 +- .../cloud/gettingstarted_console.py | 16 +++- .../cloud/gettingstarted_web/app.py | 10 +-- .../cloud/mixed_console.py | 18 ++++- .../example_utils.py | 14 ++++ .../tests/test_cloud_paid_key_note.py | 37 ++++++++- location/examples/cloud/example_utils.py | 12 +++ location/examples/cloud/gettingstarted.py | 2 +- location/examples/cloud/web.py | 10 +-- location/tests/test_paid_key_note.py | 8 +- .../cloud/mixed/gettingstarted_console.py | 26 +++++-- .../cloud/mixed/gettingstarted_web/app.py | 26 +++++++ .../gettingstarted_web/templates/index.html | 4 + .../example_utils.py | 15 ++++ .../tests/test_cloud_mixed_paid_key_note.py | 67 ++++++++++++++++- pipeline/fiftyone_pipeline_did/readme.md | 4 + 27 files changed, 392 insertions(+), 50 deletions(-) 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 99676763..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 @@ -29,8 +29,11 @@ # 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. -PAID_PROPERTIES = ["hardwarevendor", "hardwarename"] +# 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 = [ @@ -101,11 +104,11 @@ def run(self, resource_key, logger, output): # The same for the properties only a paid resource key returns, # saying once what to do about any the key cannot return. missing = [] - for property_name in PAID_PROPERTIES: + 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(property_name) + missing.append(label) if missing: output(ExampleUtils.get_paid_key_note(missing, CONTACT_US)) @@ -129,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 dc7e918f..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 @@ -55,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: 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..c2708cfd 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 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 "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 674f2de1..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 @@ -216,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..fc4fb3aa 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 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 @@

Device data

Device Id:{{ utils.get_human_readable(data.device, "deviceid") }} + {% if paid_key_note %} +

{{ paid_key_note|safe }}

+ {% endif %}

Client-side evidence and Apple models

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..7c04531a 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 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 @@

Detection results

Browser Version:{{ utils.get_human_readable(data.device, "browserversion") }} + {% if paid_key_note %} +

{{ paid_key_note|safe }}

+ {% endif %}

Want to try on-premise? Contact us to discuss requirements.

Contact us
diff --git a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py index d9c34e43..35c7d285 100644 --- a/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py +++ b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py @@ -22,6 +22,7 @@ from datetime import datetime, timedelta from threading import Event, Thread +import html import os import shlex import shutil @@ -182,6 +183,20 @@ def get_paid_key_note(missing, contact_us): 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_missing_evidence_file_message(file_name, argument): """! diff --git a/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py b/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py index f0e6ee76..4143fe7b 100644 --- a/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py +++ b/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py @@ -31,6 +31,7 @@ """ import ast +import html import http.server import importlib.util import io @@ -51,6 +52,10 @@ from fiftyone_devicedetection_examples.example_utils import ExampleUtils from fiftyone_devicedetection_examples.cloud import configurator_console from fiftyone_devicedetection_examples.cloud import gettingstarted_console +from fiftyone_devicedetection_examples.cloud.gettingstarted_web import ( + app as gettingstarted_web) +from fiftyone_devicedetection_examples.cloud.useragentclienthints_web import ( + app as useragentclienthints_web) # The failure to match example is a script that does its work when it is # imported, so it is only ever run, never imported. @@ -70,6 +75,7 @@ PAID_PROPERTIES = { "HardwareVendor": "String", "HardwareName": "Array", + "DeviceType": "String", } # The values the stand-in gives each property. @@ -81,6 +87,7 @@ "browserversion": "10.1", "hardwarevendor": "Samsung", "hardwarename": ["Galaxy S9"], + "devicetype": "SmartPhone", } # Some of the evidence keys the cloud service accepts. @@ -91,8 +98,9 @@ # Any resource key, as the stand-in does not check it. RESOURCE_KEY = "stand-in-key" -# A contact link as rule 2 asks: exactly five parameters in this order, the -# last two being lowercase slugs, the term at most 60 characters. +# 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._-]*)" @@ -212,7 +220,7 @@ def contact_us(module_name): (gettingstarted_console.__name__, run_getting_started, ["Hardware Vendor", "Hardware Name"]), (configurator_console.__name__, run_configurator, - ["hardwarevendor", "hardwarename"]), + ["HardwareVendor", "HardwareName"]), (FAILURE_TO_MATCH, run_failure_to_match, ["HardwareVendor"]), ] @@ -248,6 +256,67 @@ def test_a_key_with_the_paid_properties_gets_no_note(self): self.assertIn("Samsung", output) +# Each web example's module and the class that builds its pipeline and app. +WEB_EXAMPLES = [ + (gettingstarted_web, gettingstarted_web.GettingStartedWeb), + (useragentclienthints_web, + useragentclienthints_web.UserAgentClientHintsWeb), +] + +# The labels of the paid properties each web page shows. +WEB_PAID_LABELS = ["Hardware Vendor", "Hardware Name", "Device Type"] + +# A User-Agent for the web pages to detect. +USER_AGENT = ( + "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G960U) AppleWebKit/537.36 " + "(KHTML, like Gecko) SamsungBrowser/10.1 Chrome/71.0.3578.99 Mobile " + "Safari/537.36") + + +def web_page(example): + """Builds a web example's pipeline against the stand-in and returns its + page.""" + example().build(RESOURCE_KEY, Logger(min_level="error")) + try: + page = example.app.test_client().get( + "/", headers={"User-Agent": USER_AGENT}) + return page.get_data(as_text=True) + finally: + example.pipeline.close() + + +class WebPaidKeyNoteTests(unittest.TestCase): + + def test_each_contact_link_is_tagged_with_its_file(self): + for module, _ in WEB_EXAMPLES: + with self.subTest(module.__name__): + match = CONTACT_LINK.fullmatch(module.CONTACT_US) + self.assertIsNotNone(match, module.CONTACT_US) + folder = Path(module.__file__).parent.name + self.assertEqual( + f"{CONTENT}{folder}-app.py", match.group(1)) + self.assertEqual("paid-resource-key", match.group(2)) + + def test_a_key_without_the_paid_properties_shows_the_note_once(self): + for module, example in WEB_EXAMPLES: + with self.subTest(module.__name__), \ + stand_in_cloud(FREE_PROPERTIES): + page = web_page(example) + note = ExampleUtils.get_paid_key_note_html( + WEB_PAID_LABELS, module.CONTACT_US) + self.assertEqual(1, page.count(note), page) + self.assertIn(f'', + page) + + def test_a_key_with_the_paid_properties_shows_no_note(self): + for module, example in WEB_EXAMPLES: + with self.subTest(module.__name__), stand_in_cloud( + {**FREE_PROPERTIES, **PAID_PROPERTIES}): + page = web_page(example) + self.assertNotIn("paid Resource Key", page) + self.assertIn("Samsung", page) + + class FakeValue: """A property value as the cloud engines give one.""" diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py index daa736cd..8b95b03b 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py @@ -197,8 +197,8 @@ 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_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-countries_console.py&utm_term=resource-key-required. " - "A resource key with the properties required by this example " - "can be created for free at " + "The translated country names this example shows need a paid " + "resource key. A free one can be created 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-countries_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/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py index 17a876b2..ca68205f 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/getallproperties_console.py @@ -133,7 +133,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_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-getallproperties_console.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-getallproperties_console.py&utm_term=resource-key-required.") ExampleUtils.print_find_out_more(FIND_OUT_MORE) diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py index 713575ff..8883f13d 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_console.py @@ -74,6 +74,15 @@ "AccuracyRadiusMin", "TimeZoneOffset"] +# The properties above that the free resource key returns. The free Lite +# data file has the same ones. Every other property needs a paid resource +# key. +FREE_PROPERTIES = ["RegisteredName", "RegisteredOwner", "RegisteredCountry"] + +# The properties above that only a paid resource key returns. +PAID_PROPERTIES = [ + name for name in OUTPUT_PROPERTIES if name not in FREE_PROPERTIES] + # 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-gettingstarted_console.py&utm_term=paid-resource-key" @@ -155,7 +164,10 @@ def analyseEvidence(self, evidence, pipeline, output): missing = [] for name in OUTPUT_PROPERTIES: self.outputValue(ip_data, name, message) - if ExampleUtils.needs_paid_key(ip_data, name.lower()): + # Only a paid property the key cannot return is noted. A free + # one that is missing shows its reason above and no note. + if name in PAID_PROPERTIES and \ + ExampleUtils.needs_paid_key(ip_data, name.lower()): missing.append(name) output("".join(message)) return missing @@ -199,7 +211,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_ipintelligence_examples-src-fiftyone_ipintelligence_examples-cloud-gettingstarted_console.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_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/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py index 6bb8b2cb..871eccf6 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/gettingstarted_web/app.py @@ -43,8 +43,6 @@ # read the values it needs from the Flow Data first and pass those values, # not the Flow Data. -import html - from flask import Flask, request from fiftyone_pipeline_core.logger import Logger @@ -93,9 +91,9 @@ def get_paid_key_note_html(ip_data): """ if not ExampleUtils.needs_paid_key(ip_data, "country"): return "" - note = html.escape(ExampleUtils.get_paid_key_note(["Country"], CONTACT_US)) - link = html.escape(CONTACT_US) - return "

" + note.replace(link, f'{link}') + "

" + return ("

" + + ExampleUtils.get_paid_key_note_html(["Country"], CONTACT_US) + + "

") @app.route("/") @@ -150,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 bde818b9..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,18 @@ "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" @@ -162,13 +174,15 @@ def analyse_evidence(self, evidence, pipeline, output): message.append("Device Detection Results:\n") for name in DEVICE_PROPERTIES: self.outputValue(data.device, name, message) - if ExampleUtils.needs_paid_key(data.device, name.lower()): + 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 ExampleUtils.needs_paid_key(data.ip, name.lower()): + if name in PAID_PROPERTIES and \ + ExampleUtils.needs_paid_key(data.ip, name.lower()): missing.append(name) output("".join(message)) 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 dfe146f6..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 @@ -172,6 +172,20 @@ def get_paid_key_note(missing, contact_us): 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 index 5cfaf133..7f8a6549 100644 --- 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 @@ -107,8 +107,9 @@ # Any resource key, as the stand-in does not check it. RESOURCE_KEY = "stand-in-key" -# A contact link as rule 2 asks: exactly five parameters in this order, the -# last two being lowercase slugs, the term at most 60 characters. +# 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._-]*)" @@ -283,6 +284,38 @@ def test_a_key_with_the_paid_properties_gets_no_note(self): 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): diff --git a/location/examples/cloud/example_utils.py b/location/examples/cloud/example_utils.py index 8dd5045b..2e513b52 100644 --- a/location/examples/cloud/example_utils.py +++ b/location/examples/cloud/example_utils.py @@ -22,6 +22,8 @@ """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" @@ -58,3 +60,13 @@ def get_paid_key_note(missing, contact_us): 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 9d1dea98..c0d7ef39 100644 --- a/location/examples/cloud/gettingstarted.py +++ b/location/examples/cloud/gettingstarted.py @@ -78,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: diff --git a/location/examples/cloud/web.py b/location/examples/cloud/web.py index 803693a7..f4d4920f 100644 --- a/location/examples/cloud/web.py +++ b/location/examples/cloud/web.py @@ -54,11 +54,11 @@ try: # Imported as part of a package, as Flask does. - from .example_utils import get_paid_key_note, needs_paid_key + 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, needs_paid_key # pylint: disable=import-error + 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. @@ -93,10 +93,8 @@ def paid_key_note_html(location): when the key returns it.""" if not needs_paid_key(location, "country"): return "" - note = html.escape(get_paid_key_note(["Country"], CONTACT_US)) - link = html.escape(CONTACT_US) return ("") + get_paid_key_note_html(["Country"], CONTACT_US) + "

") def find_out_more_html(): @@ -123,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: diff --git a/location/tests/test_paid_key_note.py b/location/tests/test_paid_key_note.py index 5b52dd93..fb4ac9f4 100644 --- a/location/tests/test_paid_key_note.py +++ b/location/tests/test_paid_key_note.py @@ -58,7 +58,8 @@ # Any resource key, as the stand-in does not check it. RESOURCE_KEY = "stand-in-key" -# A contact link as rule 2 asks: exactly five parameters in this order. +# 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._-]*)" @@ -180,9 +181,8 @@ 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 = html.escape(module.get_paid_key_note( - ["Country"], module.CONTACT_US)).replace( - link, f"{link}") + 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) 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 d5323534..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,15 @@ 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" @@ -259,12 +270,12 @@ def analyse_evidence(self, evidence, pipeline, output): 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 properties that the key cannot return. + the labels of the paid properties that the key cannot return. """ message.append(heading) @@ -273,7 +284,8 @@ def append_results(heading, element_data, properties, message): for label, property_name in properties: value = ExampleUtils.get_human_readable(element_data, property_name) message.append(f"\t{label}: {value}") - if ExampleUtils.needs_paid_key(element_data, property_name): + if property_name in cls.PAID_PROPERTIES and \ + ExampleUtils.needs_paid_key(element_data, property_name): missing.append(label) return missing @@ -324,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..42f46aae 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 @@ -151,6 +151,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 +376,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], 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 @@

IP intelligence results

+ {% if paid_key_note %} +

{{ paid_key_note|safe }}

+ {% endif %} +
Evidence used

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 2aaf4e7b..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 @@ -214,6 +215,20 @@ def get_paid_key_note(missing, contact_us): 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 index fded1aba..cb1b7e57 100644 --- 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 @@ -40,7 +40,11 @@ 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 @@ -59,11 +63,22 @@ "ip": [name for _, name in EXAMPLE.IP_PROPERTIES], } -# The labels of the properties a free key cannot return, as the note names -# them. +# 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 not in FREE["device"] + FREE["ip"]] + 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"] @@ -71,7 +86,8 @@ # Any resource key, as the stand-in does not check it. RESOURCE_KEY = "stand-in-key" -# The contact link as rule 2 asks: exactly five parameters in this order. +# 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._-]*)" @@ -153,6 +169,21 @@ def run_example(sections): 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): @@ -178,6 +209,34 @@ def test_a_key_with_the_paid_properties_gets_no_note(self): 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 " diff --git a/pipeline/fiftyone_pipeline_did/readme.md b/pipeline/fiftyone_pipeline_did/readme.md index 7c388dfb..ead0b7ef 100644 --- a/pipeline/fiftyone_pipeline_did/readme.md +++ b/pipeline/fiftyone_pipeline_did/readme.md @@ -90,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 From 6ae7db8d4d6a4cb356024126d5781e98c77c6d01 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Sat, 5 Dec 2026 10:35:13 +0000 Subject: [PATCH 3/4] FIX: Stop the cloud examples saying a free key has their paid properties Four places still told the reader that a free resource key carries every property the example uses, while the same example now notes that some of those properties need a paid key. - The Device Detection getting started and User-Agent Client Hints web pages now say a key with the free properties the example uses can be created for free, which is what their console versions say. - The mixed getting started web page has the same wording in its header comment and in its no-key message. Its header now also says which of the properties it shows need a paid key, and what the page does when the key cannot return them. - The cloud request engine examples readme has the same wording, and says the hardware and IP location properties need a paid key. The countries console example can only show translated country names, and those need a paid key, but its no-key message offered a free key first. It now says the names need a paid key, links to contact us, and then says where a key carrying them is created with a License Key. Its header comment says the same. The Device Detection settings file comment no longer says "for free" twice. --- .../cloud/gettingstarted_console.json | 2 +- .../cloud/gettingstarted_web/app.py | 4 ++-- .../cloud/useragentclienthints_web/app.py | 4 ++-- .../cloud/countries_console.py | 7 +++++-- .../examples/readme.md | 6 ++++-- .../cloud/mixed/gettingstarted_web/app.py | 9 ++++++--- 6 files changed, 20 insertions(+), 12 deletions(-) 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 c2708cfd..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 @@ -7,7 +7,7 @@ "elementParameters": { "settings": { // Obtain a resource key with the free properties this - // example uses 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 + // 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_web/app.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/gettingstarted_web/app.py index fc4fb3aa..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 @@ -249,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/useragentclienthints_web/app.py b/device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/cloud/useragentclienthints_web/app.py index 7c04531a..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 @@ -185,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/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py index 8b95b03b..14af2fa4 100644 --- a/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py +++ b/ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/cloud/countries_console.py @@ -33,7 +33,8 @@ # 3. How to read the "All" lists used to build a country dropdown # # A resource key carrying the IP intelligence and the translated country -# names properties is required. You can create one at +# names properties is required. The translated country names need a paid +# resource key, which you can create with a License Key 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-countries_console.py&utm_term=top # # Required PyPi Dependencies: @@ -198,7 +199,9 @@ def main(argv): "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-countries_console.py&utm_term=resource-key-required. " "The translated country names this example shows need a paid " - "resource key. A free one can be created at " + "resource key. To ask about one, contact us at " + CONTACT_US + + ". With a License Key, a resource key carrying them can be " + "created 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-countries_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/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_web/app.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py index 42f46aae..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 @@ -495,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. " From 4735752428fb13cb0675934416a72e6563490888 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Sat, 5 Dec 2026 14:57:21 +0000 Subject: [PATCH 4/4] TEST: Put back web example pipelines after the paid key note page The web examples keep their pipeline on the class, and the getting started web tests build theirs when they are collected. The paid key note tests then built a page against a stand-in cloud. Once the stand-in stopped, the class still held a pipeline pointing at it. With a resource key set, the getting started web tests ran later against that pipeline. The call was refused and the page answered 500. The paid key note tests now put back the pipeline the class had, or remove it where the class had none. A new test checks both. --- .../tests/test_cloud_paid_key_note.py | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py b/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py index 4143fe7b..6252f758 100644 --- a/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py +++ b/device-detection/fiftyone_devicedetection_examples/tests/test_cloud_paid_key_note.py @@ -273,9 +273,19 @@ def test_a_key_with_the_paid_properties_gets_no_note(self): "Safari/537.36") +def set_pipeline(example, pipeline): + """Sets the pipeline on a web example's class. None leaves the class + with no pipeline.""" + if pipeline is not None: + example.pipeline = pipeline + elif "pipeline" in example.__dict__: + del example.pipeline + + def web_page(example): - """Builds a web example's pipeline against the stand-in and returns its - page.""" + """Returns the example's page, built against the stand-in cloud. + Restores the class's pipeline attribute, deleting it if there was none.""" + previous = example.__dict__.get("pipeline") example().build(RESOURCE_KEY, Logger(min_level="error")) try: page = example.app.test_client().get( @@ -283,6 +293,7 @@ def web_page(example): return page.get_data(as_text=True) finally: example.pipeline.close() + set_pipeline(example, previous) class WebPaidKeyNoteTests(unittest.TestCase): @@ -316,6 +327,22 @@ def test_a_key_with_the_paid_properties_shows_no_note(self): self.assertNotIn("paid Resource Key", page) self.assertIn("Samsung", page) + def test_a_page_leaves_the_example_the_pipeline_it_had(self): + # Later web tests use the pipeline on the class. A page built here + # must not leave one pointing at a stand-in that has stopped. + earlier = object() + for module, example in WEB_EXAMPLES: + kept = example.__dict__.get("pipeline") + try: + for had in (earlier, None): + with self.subTest(module.__name__, had=had): + set_pipeline(example, had) + with stand_in_cloud(FREE_PROPERTIES): + web_page(example) + self.assertIs(had, example.__dict__.get("pipeline")) + finally: + set_pipeline(example, kept) + class FakeValue: """A property value as the cloud engines give one."""