[Pkg-mozext-commits] [requestpolicy] 132/257: [tst][add] Auto-import of old (v0.5) rules

David Prévot taffit at moszumanska.debian.org
Thu Jan 28 03:20:05 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 62d511946dd99f0f29f7a08232f7c1988d354260
Author: Martin Kimmerle <dev at 256k.de>
Date:   Tue Nov 10 14:08:37 2015 +0100

    [tst][add] Auto-import of old (v0.5) rules
---
 .../dev-helper/content/console-observer.jsm        |  16 ++-
 tests/marionette/rp_puppeteer/__init__.py          |   4 +
 tests/marionette/rp_puppeteer/api/addon.py         |  12 ++
 tests/marionette/rp_puppeteer/api/rules.py         |  59 +++++++++
 tests/marionette/rp_puppeteer/tests/test_addon.py  |  12 +-
 tests/marionette/rp_puppeteer/tests/test_rules.py  |  40 +++++-
 tests/marionette/rp_ui_harness/decorators.py       |  13 ++
 tests/marionette/tests/policy/manifest.ini         |   1 +
 .../marionette/tests/policy/old_rules/manifest.ini |   1 +
 .../tests/policy/old_rules/test_auto_import.py     | 134 +++++++++++++++++++++
 10 files changed, 287 insertions(+), 5 deletions(-)

diff --git a/tests/helper-addons/dev-helper/content/console-observer.jsm b/tests/helper-addons/dev-helper/content/console-observer.jsm
index 9965683..a5a2889 100644
--- a/tests/helper-addons/dev-helper/content/console-observer.jsm
+++ b/tests/helper-addons/dev-helper/content/console-observer.jsm
@@ -44,6 +44,20 @@ function isRPException(aMessage) {
   return true;
 }
 
+const knownBugs = [
+  // issue #597
+  `[JavaScript Error: "TypeError: sub is undefined" {file: "chrome://rpcontinued/content/lib/subscription.jsm"`
+];
+  
+function isKnownBug(aMessage) {
+  for (bugMsg of knownBugs) {
+    if (aMessage.startsWith(bugMsg)) {
+      return true;
+    }
+  }
+  return false;
+}
+
 /**
  * ConsoleObserver observes all messages sent to the
  * Browser Console and detects errors caused by
@@ -78,7 +92,7 @@ var ConsoleObserver = (function (self) {
   self.observe = function (aSubject) {
     var msg = aSubject.message;
 
-    if (isRPException(msg)) {
+    if (isRPException(msg) && !isKnownBug(msg)) {
       ++numErrors;
       messages.push(msg);
       dump("[RequestPolicy] [Browser Console] " + msg + "\n");
diff --git a/tests/marionette/rp_puppeteer/__init__.py b/tests/marionette/rp_puppeteer/__init__.py
index 5b778f8..c834013 100644
--- a/tests/marionette/rp_puppeteer/__init__.py
+++ b/tests/marionette/rp_puppeteer/__init__.py
@@ -36,6 +36,10 @@ class RequestPolicyPuppeteer(object):
     def rules(self):
         pass
 
+    @use_class_as_property('api.rules.RulesFile')
+    def rules_file(self):
+        pass
+
     @use_class_as_property('ui.context_menu.ContextMenu')
     def ctx_menu(self):
         pass
diff --git a/tests/marionette/rp_puppeteer/api/addon.py b/tests/marionette/rp_puppeteer/api/addon.py
index 797b5a4..f278cdc 100644
--- a/tests/marionette/rp_puppeteer/api/addon.py
+++ b/tests/marionette/rp_puppeteer/api/addon.py
@@ -7,6 +7,7 @@ from firefox_puppeteer.base import BaseLib
 from rp_puppeteer.api.error_detection import (LoggingErrorDetection,
                                               ConsoleErrorDetection)
 from contextlib import contextmanager
+import time
 
 
 class Addon(BaseLib):
@@ -64,6 +65,14 @@ class Addon(BaseLib):
         self._set_user_disabled(True)
         Wait(self.marionette).until(lambda _: not self.is_active)
 
+    @contextmanager
+    def tmp_disabled(self):
+        self.disable()
+        try:
+            yield
+        finally:
+            self.enable()
+
     @property
     def is_installed(self):
         with self._addon():
@@ -220,6 +229,9 @@ class RequestPolicy(Addon):
             super(RequestPolicy, self).enable()
 
     def disable(self, ignore_errors=False):
+        # FIXME: issue #728
+        time.sleep(0.2)
+
         with self._ensure_no_errors():
             super(RequestPolicy, self).disable()
 
diff --git a/tests/marionette/rp_puppeteer/api/rules.py b/tests/marionette/rp_puppeteer/api/rules.py
index d892e9d..e2b0d43 100644
--- a/tests/marionette/rp_puppeteer/api/rules.py
+++ b/tests/marionette/rp_puppeteer/api/rules.py
@@ -4,6 +4,8 @@
 
 from firefox_puppeteer.base import BaseLib
 import copy
+import os.path
+import json
 
 
 class Rules(BaseLib):
@@ -68,6 +70,16 @@ class Rules(BaseLib):
         for rule in self.all:
             rule.remove()
 
+    def save(self):
+        """Save the rules to the json file."""
+
+        return self.marionette.execute_script("""
+          var mod = {};
+          Components.utils.import("chrome://rpcontinued/content/lib/" +
+                                  "policy-manager.jsm", mod);
+          mod.PolicyManager.storeRules();
+        """)
+
     ##################################
     # Private Properties and Methods #
     ##################################
@@ -114,6 +126,49 @@ class Rules(BaseLib):
                 for rule_data in rule_data_list]
 
 
+class RulesFile(BaseLib):
+
+    def __init__(self, marionette_getter, file_path="user.json"):
+        super(RulesFile, self).__init__(marionette_getter)
+
+        if os.path.isabs(file_path):
+            self.file_path = file_path
+        else:
+            profile_path = self.marionette.instance.profile.profile
+            self.file_path = ("{}/requestpolicy/policies/{}"
+                              .format(profile_path, file_path))
+
+    #################################
+    # Public Properties and Methods #
+    #################################
+
+    def get_rules(self):
+        if not os.path.isfile(self.file_path):
+            return None
+
+        with open(self.file_path, 'r') as f:
+            json_data = json.loads(f.read())
+
+        assert json_data["metadata"]["version"] is 1
+
+        entries = json_data["entries"]
+        rules = []
+
+        for (keyword, is_allow) in [("allow", True), ("deny", False)]:
+            if keyword not in entries:
+                continue
+
+            for rule_data in entries[keyword]:
+                rules.append(Rule(lambda: self.marionette, rule_data,
+                                  allow=is_allow, temp=False))
+
+        return rules
+
+    def remove(self):
+        if os.path.isfile(self.file_path):
+            os.remove(self.file_path)
+
+
 class Rule(BaseLib):
     """Class to represent a specific rule."""
 
@@ -147,6 +202,10 @@ class Rule(BaseLib):
         else:
             return 1
 
+    def __repr__(self):
+        return ("Rule(rule_data={}, allow={}, temp={})"
+                .format(self.rule_data, self.allow, self.temp))
+
     #################################
     # Public Properties and Methods #
     #################################
diff --git a/tests/marionette/rp_puppeteer/tests/test_addon.py b/tests/marionette/rp_puppeteer/tests/test_addon.py
index 49df254..bfff2f3 100644
--- a/tests/marionette/rp_puppeteer/tests/test_addon.py
+++ b/tests/marionette/rp_puppeteer/tests/test_addon.py
@@ -6,10 +6,10 @@ from rp_ui_harness import RequestPolicyTestCase
 from rp_puppeteer.api.addon import Addon
 
 
-class TestAddons(RequestPolicyTestCase):
+class TestAddon(RequestPolicyTestCase):
 
     def setUp(self):
-        super(TestAddons, self).setUp()
+        super(TestAddon, self).setUp()
         self.addon = Addon(lambda: self.marionette,
                            addon_id="dummy-ext at requestpolicy.org",
                            install_url="http://localhost/.dist/dummy-ext.xpi")
@@ -19,7 +19,7 @@ class TestAddons(RequestPolicyTestCase):
         try:
             self.addon.uninstall()
         finally:
-            super(TestAddons, self).tearDown()
+            super(TestAddon, self).tearDown()
 
     def test_uninstall_install(self):
         self.assertTrue(self.addon.is_installed)
@@ -47,6 +47,12 @@ class TestAddons(RequestPolicyTestCase):
         self.addon.enable()
         self.addon.enable()
 
+    def test_tmp_disabled(self):
+        self.assertTrue(self.addon.is_active)
+        with self.addon.tmp_disabled():
+            self.assertFalse(self.addon.is_active)
+        self.assertTrue(self.addon.is_active)
+
     def test_is_installed(self):
         self.assertTrue(self.addon.is_installed)
         self.addon.disable()
diff --git a/tests/marionette/rp_puppeteer/tests/test_rules.py b/tests/marionette/rp_puppeteer/tests/test_rules.py
index 248071e..3d10378 100644
--- a/tests/marionette/rp_puppeteer/tests/test_rules.py
+++ b/tests/marionette/rp_puppeteer/tests/test_rules.py
@@ -3,7 +3,7 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from rp_ui_harness import RequestPolicyTestCase
-from rp_puppeteer.api.rules import Rule
+from rp_puppeteer.api.rules import Rule, RulesFile
 from marionette import SkipTest
 
 
@@ -169,6 +169,44 @@ class TestRules(RulesTestCase):
         self.rules.remove_all()
         self.assertEqual(self.rules.count_rules(), 0)
 
+    def test_save(self):
+        self.rules_file.remove()
+        self.assertIsNone(self.rules_file.get_rules())
+
+        self.rules.save()
+        self.assertListEqual(self.rules_file.get_rules(), [])
+
+
+class TestRulesFile(RulesTestCase):
+
+    def setUp(self):
+        super(TestRulesFile, self).setUp()
+        self.nonexistant_file = RulesFile(lambda: self.marionette,
+                                          "foobar.json")
+
+    def test_get_rules_from_nonexistant_file(self):
+        self.assertIsNone(self.nonexistant_file.get_rules())
+
+    def test_get_rules(self):
+        # Some permanent rules.
+        rules = [self.baserule,
+                 self.baserule_variants["different_allow"],
+                 self.baserule_variants["different_rule_data"]]
+
+        # add the rules via API
+        for rule in rules:
+            rule.add()
+        self.rules.save()
+        self.assertListEqual(sorted(self.rules_file.get_rules()), sorted(rules))
+
+        self.rules.remove_all()
+        self.rules.save()
+        self.assertListEqual(self.rules_file.get_rules(), [])
+
+    def test_remove_nonexistant_file(self):
+        # remove() should not raise an exception.
+        self.nonexistant_file.remove()
+
 
 class TestRule(RulesTestCase):
 
diff --git a/tests/marionette/rp_ui_harness/decorators.py b/tests/marionette/rp_ui_harness/decorators.py
new file mode 100644
index 0000000..95b98a1
--- /dev/null
+++ b/tests/marionette/rp_ui_harness/decorators.py
@@ -0,0 +1,13 @@
+# 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/.
+
+
+def lazyprop(target):
+    attr_name = '_lazy_' + target.__name__
+    @property
+    def wrapper(self, *args, **kwargs):
+        if not hasattr(self, attr_name):
+            setattr(self, attr_name, target(self, *args, **kwargs))
+        return getattr(self, attr_name)
+    return wrapper
diff --git a/tests/marionette/tests/policy/manifest.ini b/tests/marionette/tests/policy/manifest.ini
index 5ce7ba9..e8cfe6e 100644
--- a/tests/marionette/tests/policy/manifest.ini
+++ b/tests/marionette/tests/policy/manifest.ini
@@ -1,2 +1,3 @@
+[include:old_rules/manifest.ini]
 [test_rule_with_scheme_only.py]
 [test_uris.py]
diff --git a/tests/marionette/tests/policy/old_rules/manifest.ini b/tests/marionette/tests/policy/old_rules/manifest.ini
new file mode 100644
index 0000000..660c619
--- /dev/null
+++ b/tests/marionette/tests/policy/old_rules/manifest.ini
@@ -0,0 +1 @@
+[test_auto_import.py]
diff --git a/tests/marionette/tests/policy/old_rules/test_auto_import.py b/tests/marionette/tests/policy/old_rules/test_auto_import.py
new file mode 100644
index 0000000..c548a2e
--- /dev/null
+++ b/tests/marionette/tests/policy/old_rules/test_auto_import.py
@@ -0,0 +1,134 @@
+# 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.testcases import RequestPolicyTestCase
+from rp_ui_harness.decorators import lazyprop
+from marionette.marionette_test import SkipTest
+
+
+PREF_PREFIX = "extensions.requestpolicy."
+PREF_DEFAULT_ALLOW = PREF_PREFIX + "defaultPolicy.allow"
+PREF_WELCOME_WIN_SHOWN = PREF_PREFIX + "welcomeWindowShown"
+PREF_LAST_RP_VERSION = PREF_PREFIX + "lastVersion"
+
+
+class TestAutomaticRulesImportOnUpgrade(RequestPolicyTestCase):
+
+    def tearDown(self):
+        try:
+            for pref in ("allowedOriginsToDestinations",
+                         "allowedOrigins",
+                         "allowedDestinations"):
+                self.prefs.reset_pref(PREF_PREFIX + pref)
+            self.rules.remove_all()
+        finally:
+            super(TestAutomaticRulesImportOnUpgrade, self).tearDown()
+
+    ################
+    # Test Methods #
+    ################
+
+    def test_autoimport__usual_first_upgrade(self):
+        self._test_autoimport_or_not(is_upgrade=True,
+                                     with_existing_rules_file=False,
+                                     with_welcomewin=True,
+                                     should_autoimport=True)
+
+    def test_autoimport__upgrade_without_welcomewin(self):
+        raise SkipTest("FIXME: issue #731")
+        self._test_autoimport_or_not(is_upgrade=True,
+                                     with_existing_rules_file=False,
+                                     with_welcomewin=False,
+                                     should_autoimport=True)
+
+    def test_no_autoimport__rules_file_removed(self):
+        self._test_autoimport_or_not(is_upgrade=False,
+                                     with_existing_rules_file=False,
+                                     with_welcomewin=True,
+                                     should_autoimport=False)
+
+    def test_no_autoimport__upgrade_with_existing_rules_file(self):
+        raise SkipTest("FIXME: issue #731")
+        self._test_autoimport_or_not(is_upgrade=True,
+                                     with_existing_rules_file=True,
+                                     with_welcomewin=True,
+                                     should_autoimport=False)
+
+    def _test_autoimport_or_not(self, is_upgrade, with_existing_rules_file,
+                                with_welcomewin, should_autoimport):
+        rules = self.typical_rules
+
+        if with_existing_rules_file:
+            # Ensure that a user.json file exists.
+            self.rules.save()
+
+        last_rp_version = "0.5.28" if is_upgrade else "1.0.beta9"
+
+        with self.rp_addon.tmp_disabled():
+            if not with_existing_rules_file:
+                self.rules_file.remove()
+            self.prefs.set_pref(PREF_LAST_RP_VERSION, last_rp_version)
+            self.prefs.set_pref(PREF_WELCOME_WIN_SHOWN, not with_welcomewin)
+
+            self._add_legacy_rules(rules["v0"])
+
+        expected_rules = rules["expected"] if should_autoimport else []
+        self.assertListEqual(sorted(self.rules.get_rules()),
+                             sorted(expected_rules))
+
+        if with_welcomewin:
+            # Close the setup tab.
+            self.browser.tabbar.tabs[-1].close()
+
+    @lazyprop
+    def typical_rules(self):
+        return {
+            "v0": {
+                "allowedOriginsToDestinations": (
+                    "https://www.mozilla.org|https://mozorg.cdn.mozilla.net "
+                    "www.mozilla.org|mozorg.cdn.mozilla.net "
+                    "mozilla.org|mozilla.net"
+                ),
+                "allowedOrigins": (
+                    "https://www.mozilla.org "
+                    "www.mozilla.org "
+                    "mozilla.org"
+                ),
+                "allowedDestinations": (
+                    "https://mozorg.cdn.mozilla.net "
+                    "mozorg.cdn.mozilla.net "
+                    "mozilla.net"
+                )
+            },
+            "expected": [
+                # origin-to-destination rules
+                self._rule({"o": {"s": "https", "h": "*.www.mozilla.org"},
+                            "d": {"s": "https", "h": "*.mozorg.cdn.mozilla.net"}}),
+                self._rule({"o": {"h": "*.www.mozilla.org"},
+                            "d": {"h": "*.mozorg.cdn.mozilla.net"}}),
+                self._rule({"o": {"h": "*.mozilla.org"},
+                            "d": {"h": "*.mozilla.net"}}),
+                # origin rules
+                self._rule({"o": {"s": "https", "h": "*.www.mozilla.org"}}),
+                self._rule({"o": {"h": "*.www.mozilla.org"}}),
+                self._rule({"o": {"h": "*.mozilla.org"}}),
+                # destination rules
+                self._rule({"d": {"s": "https", "h": "*.mozorg.cdn.mozilla.net"}}),
+                self._rule({"d": {"h": "*.mozorg.cdn.mozilla.net"}}),
+                self._rule({"d": {"h": "*.mozilla.net"}})
+            ]
+        }
+
+    ##########################
+    # Private Helper Methods #
+    ##########################
+
+    def _add_legacy_rules(self, rules):
+        """Add the rules for v0.*.*."""
+
+        for (pref, value) in rules.items():
+            self.prefs.set_pref(PREF_PREFIX + pref, value)
+
+    def _rule(self, rule_data):
+        return self.rules.create_rule(rule_data, allow=True, temp=False)

-- 
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