[Pkg-mozext-commits] [requestpolicy] 58/257: [tst][add] RP Puppeteer "Rules" API

David Prévot taffit at moszumanska.debian.org
Thu Jan 28 03:19:56 UTC 2016


This is an automated email from the git hooks/post-receive script.

taffit pushed a commit to branch master
in repository requestpolicy.

commit d9bddfb9cb0b7427696c8fe67b1cc60cfe7c036d
Author: Martin Kimmerle <dev at 256k.de>
Date:   Sat Sep 26 17:59:03 2015 +0200

    [tst][add] RP Puppeteer "Rules" API
---
 tests/marionette/rp_puppeteer/api/rules.py        | 206 ++++++++++++++++++++
 tests/marionette/rp_puppeteer/tests/manifest.ini  |   1 +
 tests/marionette/rp_puppeteer/tests/test_rules.py | 226 ++++++++++++++++++++++
 3 files changed, 433 insertions(+)

diff --git a/tests/marionette/rp_puppeteer/api/rules.py b/tests/marionette/rp_puppeteer/api/rules.py
new file mode 100644
index 0000000..268ceff
--- /dev/null
+++ b/tests/marionette/rp_puppeteer/api/rules.py
@@ -0,0 +1,206 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from firefox_puppeteer.base import BaseLib
+
+
+class Rules(BaseLib):
+    """Class for managing user rules."""
+
+    #################################
+    # Public Properties and Methods #
+    #################################
+
+    @property
+    def all(self):
+        return self.get_rules()
+
+    def create_rule(self, rule_data, allow, temp=False):
+        """Create a `Rule` instance."""
+
+        return Rule(lambda: self.marionette, rule_data, allow, temp)
+
+    def get_rules(self, allow=[True, False], temp=[True, False]):
+        if not isinstance(allow, list):
+            allow = [allow]
+        if not isinstance(temp, list):
+            temp = [temp]
+
+        rules = []
+
+        for allow_value in allow:
+            for temp_value in temp:
+                rules += self._get_rules(allow_value, temp_value)
+
+        return rules
+
+    def rule_exists(self, rule_data, allow=[True, False], temp=[True, False]):
+        if not isinstance(allow, list):
+            allow = [allow]
+        if not isinstance(temp, list):
+            temp = [temp]
+
+        for allow_value in allow:
+            for temp_value in temp:
+                rule = self.create_rule(rule_data, allow_value, temp_value)
+                if rule.exists():
+                    return True
+
+        return False
+
+    def count_rules(self, allow=[True, False], temp=[True, False]):
+        """Count the number of rules."""
+
+        if not isinstance(allow, list):
+            allow = [allow]
+        if not isinstance(temp, list):
+            temp = [temp]
+
+        counter = 0
+        for allow_value in allow:
+            for temp_value in temp:
+                counter += self._count_rules(allow_value, temp_value)
+        return counter
+
+    def remove_all(self):
+        for rule in self.all:
+            rule.remove()
+
+    ##################################
+    # Private Properties and Methods #
+    ##################################
+
+    def _count_rules(self, allow, temp):
+        """Count the number of rules for one specific allow/temp combination.
+        """
+
+        ruleset_name = "temp" if temp else "user"
+
+        return self.marionette.execute_script("""
+          var rulesetName = arguments[0];
+          var allow = arguments[1];
+          var mod = {};
+          Components.utils.import("chrome://rpcontinued/content/lib/" +
+                                  "policy-manager.jsm", mod);
+          var rawRuleset = mod.PolicyManager.getUserRulesets()[rulesetName]
+                                            .rawRuleset;
+          if (allow === true) {
+            return rawRuleset.getAllowRuleCount();
+          } else {
+            return rawRuleset.getDenyRuleCount();
+          }
+        """, script_args=[ruleset_name, allow])
+
+    def _get_rules(self, allow, temp):
+        """Get the rules for one specific allow/temp combination."""
+
+        ruleset_name = "temp" if temp else "user"
+        rule_action_string = "allow" if allow else "deny"
+
+        rule_data_list = self.marionette.execute_script("""
+          var rulesetName = arguments[0];
+          var ruleActionString = arguments[1];
+          var mod = {};
+          Components.utils.import("chrome://rpcontinued/content/lib/" +
+                                  "policy-manager.jsm", mod);
+          var rawRuleset = mod.PolicyManager.getUserRulesets()[rulesetName]
+                                            .rawRuleset;
+          return rawRuleset._entries[ruleActionString];
+        """, script_args=[ruleset_name, rule_action_string])
+
+        return [self.create_rule(rule_data, allow, temp)
+                for rule_data in rule_data_list]
+
+
+class Rule(BaseLib):
+    """Class to represent a specific rule."""
+
+    def __init__(self, marionette_getter, rule_data, allow, temp):
+        super(Rule, self).__init__(marionette_getter)
+        self.rule_data = rule_data
+        self.allow = allow
+        self.temp = temp
+
+    def __eq__(self, other):
+        return (self.allow == other.allow and self.temp == other.temp and
+                self.rule_data == other.rule_data)
+
+    def __cmp__(self, other):
+        # Temporary rules first.
+        if self.temp != other.temp:
+            return -1 if self.temp else 1
+        # "Deny" rules first.
+        if self.allow != other.allow:
+            return -1 if not self.allow else 1
+        # Use the dictionary's (`dict`) comparison operators on `rule_data`.
+        if self.rule_data < other.rule_data:
+            return -1
+        elif self.rule_data == other.rule_data:
+            return 0
+        else:
+            return 1
+
+    #################################
+    # Public Properties and Methods #
+    #################################
+
+    def add(self, store=False):
+        """Add the rule to the user policy."""
+
+        self.marionette.execute_script("""
+          var ruleAction = arguments[0];
+          var ruleData = arguments[1];
+          var temp = arguments[2];
+          var noStore = arguments[3];
+          var mod = {};
+          Components.utils.import("chrome://rpcontinued/content/lib/" +
+                                  "policy-manager.jsm", mod);
+          if (temp === true) {
+            mod.PolicyManager.addTemporaryRule(ruleAction, ruleData);
+          } else {
+            mod.PolicyManager.addRule(ruleAction, ruleData, noStore);
+          }
+        """, script_args=[self._rule_action, self.rule_data, self.temp,
+                          not store])
+
+    def remove(self, store=False):
+        """Remove the rule from the user policy."""
+
+        self.marionette.execute_script("""
+          var ruleAction = arguments[0];
+          var ruleData = arguments[1];
+          var noStore = arguments[2];
+          var mod = {};
+          Components.utils.import("chrome://rpcontinued/content/lib/" +
+                                  "policy-manager.jsm", mod);
+          mod.PolicyManager.removeRule(ruleAction, ruleData, noStore);
+        """, script_args=[self._rule_action, self.rule_data, not store])
+
+    def exists(self):
+        """Check if the rule exists."""
+
+        return self.marionette.execute_script("""
+          var rulesetName = arguments[0];
+          var ruleAction = arguments[1];
+          var ruleData = arguments[2];
+          var mod = {};
+          Components.utils.import("chrome://rpcontinued/content/lib/" +
+                                  "policy-manager.jsm", mod);
+          return mod.PolicyManager.getUserRulesets()[rulesetName]
+                                  .rawRuleset
+                                  .ruleExists(ruleAction, ruleData);
+        """, script_args=[self._ruleset_name, self._rule_action,
+                          self.rule_data])
+
+    ##################################
+    # Private Properties and Methods #
+    ##################################
+
+    @property
+    def _ruleset_name(self):
+        return "temp" if self.temp else "user"
+
+    @property
+    def _rule_action(self):
+        return 1 if self.allow else 2
diff --git a/tests/marionette/rp_puppeteer/tests/manifest.ini b/tests/marionette/rp_puppeteer/tests/manifest.ini
index ed6a809..50c7fb6 100644
--- a/tests/marionette/rp_puppeteer/tests/manifest.ini
+++ b/tests/marionette/rp_puppeteer/tests/manifest.ini
@@ -1,3 +1,4 @@
 [test_addons.py]
 [test_error_detection.py]
 [test_prefs.py]
+[test_rules.py]
diff --git a/tests/marionette/rp_puppeteer/tests/test_rules.py b/tests/marionette/rp_puppeteer/tests/test_rules.py
new file mode 100644
index 0000000..bade8f8
--- /dev/null
+++ b/tests/marionette/rp_puppeteer/tests/test_rules.py
@@ -0,0 +1,226 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from rp_ui_harness import RequestPolicyTestCase
+from rp_puppeteer.api.rules import Rules
+from marionette import SkipTest
+
+
+class RulesTestCase(RequestPolicyTestCase):
+    """Common test class."""
+
+    def setUp(self):
+        super(RulesTestCase, self).setUp()
+
+        self.rules = Rules(lambda: self.marionette)
+
+        cr = self.rules.create_rule
+
+        self.rules_1248 = [
+            cr({"o": {"h": "a"}}, allow=False, temp=False),
+
+            cr({"o": {"h": "b"}}, allow=False, temp=True),
+            cr({"o": {"h": "c"}}, allow=False, temp=True),
+
+            cr({"o": {"h": "d"}}, allow=True, temp=False),
+            cr({"o": {"h": "e"}}, allow=True, temp=False),
+            cr({"o": {"h": "f"}}, allow=True, temp=False),
+            cr({"o": {"h": "g"}}, allow=True, temp=False),
+
+            cr({"o": {"h": "h"}}, allow=True, temp=True),
+            cr({"o": {"h": "i"}}, allow=True, temp=True),
+            cr({"o": {"h": "j"}}, allow=True, temp=True),
+            cr({"o": {"h": "k"}}, allow=True, temp=True),
+            cr({"o": {"h": "l"}}, allow=True, temp=True),
+            cr({"o": {"h": "m"}}, allow=True, temp=True),
+            cr({"o": {"h": "n"}}, allow=True, temp=True),
+            cr({"o": {"h": "o"}}, allow=True, temp=True)
+        ]
+
+        self.rules_4combinations_different_rule_data = [
+            cr({"o": {"h": "a"}}, allow=False, temp=False),
+            cr({"o": {"h": "b"}}, allow=False, temp=True),
+            cr({"o": {"h": "c"}}, allow=True, temp=False),
+            cr({"o": {"h": "d"}}, allow=True, temp=True)
+        ]
+
+        self.rules_4combinations_same_rule_data = [
+            cr({"o": {"h": "a"}}, allow=False, temp=False),
+            cr({"o": {"h": "a"}}, allow=False, temp=True),
+            cr({"o": {"h": "a"}}, allow=True, temp=False),
+            cr({"o": {"h": "a"}}, allow=True, temp=True)
+        ]
+
+        self.baserule = cr({"o": {"h": "a"}}, allow=False, temp=False)
+        self.temp_baserule = cr({"o": {"h": "a"}}, allow=False, temp=True)
+        self.baserule_variants = dict(
+            different_rule_data=cr({"o": {"h": "b"}}, allow=False, temp=False),
+            different_allow=cr({"o": {"h": "a"}}, allow=True, temp=False),
+            different_temp=cr({"o": {"h": "a"}}, allow=False, temp=True)
+        )
+
+    def tearDown(self):
+        try:
+            self.rules.remove_all()
+        finally:
+            super(RulesTestCase, self).tearDown()
+
+    @property
+    def possible_allow_temp_param_combinations(self):
+        """Get all possible combinations of `allow`/`temp` values."""
+
+        # Both `allow` and `temp` parameters take a list of boolean values.
+        possible_boolean_combinations = [[True], [False], [True, False]]
+
+        return [(allow, temp)
+                for allow in possible_boolean_combinations
+                for temp in possible_boolean_combinations]
+
+
+class TestRules(RulesTestCase):
+
+    def test_get_and_count(self):
+        all_rules = self.rules_1248
+
+        # Add all rules.
+        for rule in all_rules:
+            rule.add()
+
+        # Test `get_rules()` and `count_rules()` for all possible
+        # combinations of `allow` and `temp` values.
+        for allow, temp in self.possible_allow_temp_param_combinations:
+            # Determine the rules which should be expected. To do so,
+            # take `all_rules` and filter out rules with non-matching
+            # `allow` and `temp` values.
+            def _filter(rule):
+                return rule.allow in allow and rule.temp in temp
+            expected_rules = filter(_filter, all_rules)
+            expected_rules.sort()
+
+            # Get the rules via `get_rules()`.
+            returned_rules = self.rules.get_rules(allow=allow, temp=temp)
+            returned_rules.sort()
+
+            # Some debug info about this sub-testcase.
+            debug_info = (
+                "allow: {}, temp: {}, returned rules: {}, "
+                "expected rules: {}"
+            ).format(
+                allow, temp,
+                [r.rule_data["o"]["h"] for r in returned_rules],
+                [r.rule_data["o"]["h"] for r in expected_rules]
+            )
+
+            # Check `get_rules()` output.
+            self.assertEqual(expected_rules, returned_rules, msg=debug_info)
+
+            expected_count = len(expected_rules)
+            returned_count = self.rules.count_rules(allow=allow, temp=temp)
+
+            # Check `count_rules()` output.
+            self.assertEqual(expected_count, returned_count, msg=debug_info)
+
+    def test_rule_exists_takes_list_or_boolean(self):
+        # Check that both lists and boolean values can be passed to
+        # `rule_exists()`.
+
+        rule = self.baserule
+        rule.add()
+        self.assertTrue(self.rules.rule_exists(rule.rule_data, rule.allow,
+                                               rule.temp))
+        self.assertTrue(self.rules.rule_exists(rule.rule_data, [rule.allow],
+                                               [rule.temp]))
+
+    def test_rule_exists_filtering(self):
+        # Test `rule_exists()` filtering by allow/deny values.
+
+        for rule in self.rules_4combinations_same_rule_data:
+            # add rule
+            rule.add()
+
+            # Check `rule_exists()` for all possible allow/temp combinations.
+            for allow, temp in self.possible_allow_temp_param_combinations:
+                expected_result = (rule.allow in allow and
+                                   rule.temp in temp)
+                returned_result = self.rules.rule_exists(rule.rule_data,
+                                                         allow=allow, temp=temp)
+                self.assertEqual(expected_result, returned_result)
+
+            # remove rule
+            rule.remove()
+
+    def test_remove_all(self):
+        for rule in self.rules_4combinations_different_rule_data:
+            rule.add()
+        self.rules.remove_all()
+        self.assertEqual(self.rules.count_rules(), 0)
+
+
+class TestRule(RulesTestCase):
+
+    def test__eq__operator(self):
+        # Create a copy of the "baserule".
+        baserule_copy = self.rules.create_rule(
+            rule_data=self.baserule.rule_data,
+            allow=self.baserule.allow,
+            temp=self.baserule.temp
+        )
+        self.assertEqual(self.baserule, baserule_copy,
+                         msg="Two copies of the same rule are equal.")
+
+        # All variants should be unequal to the base rule.
+        for variant_name, rule in self.baserule_variants.items():
+            self.assertNotEqual(self.baserule, rule,
+                                msg=("Variant '{}' and the Baserule are "
+                                     "unequal.".format(variant_name)))
+
+    def test_adding_and_removing_rule(self):
+        rule = self.baserule
+        self.assertEqual(self.rules.count_rules(), 0)
+        rule.add()
+        self.assertEqual(self.rules.count_rules(), 1,
+                         msg="Exactly one rule has been added.")
+        self.assertEqual(self.rules.all[0], self.baserule,
+                         msg="The rule has been added correctly.")
+        rule.remove()
+        self.assertEqual(self.rules.count_rules(), 0)
+
+    def test_removing_one_of_coexistent_temporary_and_permanent_rules(self):
+        raise SkipTest("Skipping due to issue #712.")
+
+        # (1) add a rule twice, once temp, once permanet.
+        # (2) remove one of them
+
+        perm_rule = self.baserule
+        temp_rule = self.temp_baserule
+
+        def add_both_rules():
+            perm_rule.add()
+            temp_rule.add()
+            self.assertTrue(perm_rule.exists())
+            self.assertTrue(temp_rule.exists())
+
+        # (1) add the rules
+        add_both_rules()
+
+        # (2) remove one rule
+        temp_rule.remove()
+        self.assertTrue(perm_rule.exists())
+        self.assertFalse(temp_rule.exists())
+
+        # back to (1)
+        add_both_rules()
+
+        # again (2)
+        perm_rule.remove()
+        self.assertFalse(perm_rule.exists())
+        self.assertTrue(temp_rule.exists())
+
+    def test_exists(self):
+        rules = self.rules_4combinations_different_rule_data
+
+        for rule in rules:
+            self.assertFalse(rule.exists())
+            rule.add()
+            self.assertTrue(rule.exists())

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-mozext/requestpolicy.git



More information about the Pkg-mozext-commits mailing list