def test_missing_property_service_not_found_anywhere(self):
        """!
        Trigger the missing property service by requesting a property
        not available in cloud
        """

        pipeline = DeviceDetectionCloudPipelineBuilder(
            resource_key=os.environ['resource_key']).build()

        fd = pipeline.create_flowdata()

        fd.evidence.add("header.User-Agent", mobile_ua)

        fd.process()

        result = ""

        try:
            fd.device.get("notpresent")
        except Exception as e:
            result = str(e)

        self.maxDiff = None

        self.assertEqual(
            result,
            "Property notpresent not found in data for element device. This is because your resource key does not include access to this property. Properties that are included for this key under device are "
            + ', '.join(
                list(pipeline.get_element("device").get_properties().keys())) +
            ". For more details on resource keys, see our explainer: https://51degrees.com/documentation/_info__resourcekeys.html"
        )
    def test_missing_property_service_element_not_found(self):
        """!
        Trigger the missing property service by requesting a property
        not available in any datafile
        """

        pipeline = DeviceDetectionCloudPipelineBuilder(
            resource_key=os.environ['resource_key']).build()

        fd = pipeline.create_flowdata()

        fd.evidence.add("header.User-Agent", mobile_ua)

        fd.process()

        result = ""

        try:
            fd.get("notpresent")
        except Exception as e:
            result = str(e)

        self.assertEqual(
            result,
            "Your resource key does not include access to any properties under notpresent. For more details on resource keys, see our explainer: https://51degrees.com/documentation/_info__resourcekeys.html Available element data keys are: ['device']"
        )
    def test_engine_init_performance(self):
        """!
        Test how long it takes for the engine to be initialised
        by looking at the metadata dictionary created on init
        """

        start = time.time()

        pipeline = DeviceDetectionCloudPipelineBuilder(
            resource_key=os.environ['resource_key']).build()

        fd = pipeline.create_flowdata()

        fd.evidence.add("header.user-agent", mobile_ua)

        fd.process()

        properties = fd.pipeline.get_element("device").get_properties()

        for engine_property in properties:
            self.assertNotEqual(fd.device.get(engine_property), None)

        end = time.time()

        total = end - start

        self.assertLess(total, 5)
    def test_cloud_request_origin(self):
        """!
        Verify that making requests using a resource key that        
        is limited to particular origins will fail or succeed
        in the expected scenarios. 
        This is an integration test that uses the live cloud service
        so any problems with that service could affect the result
        of this test.
        """

        for origin, expectedException in cloud_request_origin_test_params:

            with self.subTest():

                exception = False

                try:
                    pipeline = DeviceDetectionCloudPipelineBuilder(
                        resource_key="AQS5HKcyVj6B8wNG2Ug",
                        cloud_request_origin=origin).build()

                    fd = pipeline.create_flowdata()

                    fd.evidence.add(
                        "header.user-agent",
                        "Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Mobile/15C114"
                    )

                    fd.process()

                except Exception as e:
                    message = str(e)

                    expectedMessage = "This resource key is not authorized for use with domain: '{}'.".format(
                        origin)

                    self.assertTrue(
                        message.find(expectedMessage) >= 0,
                        "Exception did not contain expected text ({})".format(
                            message))

                    exception = True

                self.assertEqual(expectedException, exception)
    def test_basic_get_cloud(self):
        """!
        Check property lookup works
        """

        if not "resource_key" in os.environ:
            return

        pipeline = DeviceDetectionCloudPipelineBuilder(
            resource_key=os.environ['resource_key']).build()

        fd = pipeline.create_flowdata()

        fd.evidence.add(
            "header.user-agent",
            "Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Mobile/15C114"
        )

        fd.process()

        self.assertTrue(fd.device.ismobile.value())
    def test_pipeline_builder_cloud_engine_init(self):
        """!
        Tests whether the device detection pipeline builder adds the correct engines when initialised with a resource key
        """

        if not "resource_key" in os.environ:
            return

        pipeline = DeviceDetectionCloudPipelineBuilder(
            resource_key=os.environ['resource_key']).build()

        self.assertTrue(pipeline.flow_elements[0].datakey == "cloud")
        self.assertTrue(pipeline.flow_elements[1].datakey == "device")
    def test_properties_cloud(self):
        """!
        Tests whether a properties list is created on the cloud engine
        """

        if not "resource_key" in os.environ:
            return

        pipeline = DeviceDetectionCloudPipelineBuilder(
            resource_key=os.environ['resource_key']).build()

        properties = pipeline.flow_elements[1].get_properties()

        self.assertTrue(len(properties.keys()) > 0)
if "resource_key" in os.environ:
    resource_key = os.environ["resource_key"]
else:
    resource_key = "!!YOUR_RESOURCE_KEY!!"

if resource_key == "!!YOUR_RESOURCE_KEY!!":
    print("""
    You need to create a resource key at
    https://configure.51degrees.com and paste it into the code,
    'replacing !!YOUR_RESOURCE_KEY!!
    To include the properties used in this example, go to https://configure.51degrees.com/bxXqZhLT
    """)
else:

    pipeline = DeviceDetectionCloudPipelineBuilder({
        "resource_key": resource_key
    }).build()

    # We create a FlowData object from the pipeline
    # this is used to add evidence to and then process

    flowdata1 = pipeline.create_flowdata()

    # Here we add a User-Agent of a desktop as evidence

    desktop_ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"

    flowdata1.evidence.add("header.user-agent", desktop_ua)

    # Now we process the FlowData
Пример #9
0
if "resource_key" in os.environ:
    resource_key = os.environ["resource_key"]
else:
    resource_key = "!!YOUR_RESOURCE_KEY!!"

if resource_key == "!!YOUR_RESOURCE_KEY!!":
    print("""
    You need to create a resource key at
    https://configure.51degrees.com and paste it into the code,
    'replacing !!YOUR_RESOURCE_KEY!!
    To include the properties used by this example go to https://configure.51degrees.com/CfLML6rg
    """)
else:

    pipeline = DeviceDetectionCloudPipelineBuilder({
        "resource_key": resource_key
    }).build()

    # Now we see what properties are available in the pipeline

    properties = pipeline.get_properties()

    # Now we find out the details of the properties in the device engine

    for property_key, property_meta in properties["device"].items():
        print(property_key + " of category " + property_meta["category"])

    # Now we can take a User-Agent, run it through this pipeline and check
    # the supported media properties against it

    # First we create a FlowData object from the pipeline
if resource_key == "!!YOUR_RESOURCE_KEY!!":
    print("""
    You need to create a resource key at
    https://configure.51degrees.com and paste it into the code,
    'replacing !!YOUR_RESOURCE_KEY!!
    To include the properties used in this example, go to https://configure.51degrees.com/
    """)
else:

    # First create the device detection pipeline with the desired settings and include required UACH SetHeader properties which are in the following format
    # SetHeader[Component name][Response header name]
    # e.g. for browser component properties to be set in Accept-CH response header use following property
    # SetHeaderBrowserAccept-CH

    pipeline = DeviceDetectionCloudPipelineBuilder({
        "resource_key": resource_key
    }).build()

    from flask import Flask, request

    app = Flask(__name__)

    # Helper function to get a property value if it exists and return
    # the reason why if it doesn't


    def get_value_helper(flowdata, engine, property_key):

        engine_properties = getattr(flowdata, engine)

        try:
Пример #11
0
    You need to create a resource key at
    https://configure.51degrees.com and paste it into the code,
    'replacing !!YOUR_RESOURCE_KEY!!
    make sure to include the HardwareName, HardwareProfile and HardwareVendor, DeviceType,
    PlatformVendor, PlatformName, BrowserVendor, BrowserName, BrowserVersion, ScreenWidth
    and ScreenHeight properties used by this example
    """)
else:

    # Here we add some callback settings for the page to make a request with extra evidence from the client side, in this case the Flask /json route we will make below

    javascript_builder_settings = {"endpoint": "/json"}

    pipeline = DeviceDetectionCloudPipelineBuilder({
        "resource_key":
        resource_key,
        "javascript_builder_settings":
        javascript_builder_settings
    }).build()

    from flask import Flask, request

    app = Flask(__name__)

    # First we make a JSON route that will be called from the client side and will return
    # a JSON encoded property database using any additional evidence provided by the client

    @app.route('/json', methods=['POST'])
    def jsonroute():

        # Create the flowdata object for the JSON route
        flowdata = pipeline.create_flowdata()