Example #1
0
def test_merge_profile(cls):
    profile = cls(preferences={"foo": "bar"})
    assert profile._addons == []
    assert os.path.isfile(
        os.path.join(profile.profile, profile.preference_file_names[0]))

    other_profile = os.path.join(here, "files", "dummy-profile")
    profile.merge(other_profile)

    # make sure to add a pref file for each preference_file_names in the dummy-profile
    prefs = {}
    for name in profile.preference_file_names:
        path = os.path.join(profile.profile, name)
        assert os.path.isfile(path)

        try:
            prefs.update(Preferences.read_json(path))
        except ValueError:
            prefs.update(Preferences.read_prefs(path))

    assert "foo" in prefs
    assert len(prefs) == len(profile.preference_file_names) + 1
    assert all(name in prefs for name in profile.preference_file_names)

    # for Google Chrome currently we ignore webext in profile prefs
    if cls == Profile:
        assert len(profile._addons) == 1
        assert profile._addons[0].endswith("empty.xpi")
        assert os.path.exists(profile._addons[0])
    else:
        assert len(profile._addons) == 0
    def test_prefs_write(self):
        """test that the Preferences.write() method correctly serializes preferences"""

        _prefs = {'browser.startup.homepage': "http://planet.mozilla.org",
                  'zoom.minPercent': 30,
                  'zoom.maxPercent': 300}

        # make a Preferences manager with the testing preferences
        preferences = Preferences(_prefs)

        # write them to a temporary location
        path = None
        read_prefs = None
        try:
            with mozfile.NamedTemporaryFile(suffix='.js', delete=False) as f:
                path = f.name
                preferences.write(f, _prefs)

            # read them back and ensure we get what we put in
            read_prefs = dict(Preferences.read_prefs(path))

        finally:
            # cleanup
            if path and os.path.exists(path):
                os.remove(path)

        self.assertEqual(read_prefs, _prefs)
Example #3
0
    def test_nonce(self):

        # make a profile with one preference
        path = tempfile.mktemp()
        self.addCleanup(mozfile.remove, path)
        profile = Profile(path, preferences={'foo': 'bar'}, restore=False)
        user_js = os.path.join(profile.profile, 'user.js')
        self.assertTrue(os.path.exists(user_js))

        # ensure the preference is correct
        prefs = Preferences.read_prefs(user_js)
        self.assertEqual(dict(prefs), {'foo': 'bar'})

        del profile

        # augment the profile with a second preference
        profile = Profile(path, preferences={'fleem': 'baz'}, restore=True)
        prefs = Preferences.read_prefs(user_js)
        self.assertEqual(dict(prefs), {'foo': 'bar', 'fleem': 'baz'})

        # cleanup the profile;
        # this should remove the new preferences but not the old
        profile.cleanup()
        prefs = Preferences.read_prefs(user_js)
        self.assertEqual(dict(prefs), {'foo': 'bar'})
    def test_nonce(self):

        # make a profile with one preference
        path = tempfile.mktemp()
        profile = Profile(path,
                          preferences={'foo': 'bar'},
                          restore=False)
        user_js = os.path.join(profile.profile, 'user.js')
        self.assertTrue(os.path.exists(user_js))

        # ensure the preference is correct
        prefs = Preferences.read_prefs(user_js)
        self.assertEqual(dict(prefs), {'foo': 'bar'})

        del profile

        # augment the profile with a second preference
        profile = Profile(path,
                          preferences={'fleem': 'baz'},
                          restore=True)
        prefs = Preferences.read_prefs(user_js)
        self.assertEqual(dict(prefs), {'foo': 'bar', 'fleem': 'baz'})

        # cleanup the profile;
        # this should remove the new preferences but not the old
        profile.cleanup()
        prefs = Preferences.read_prefs(user_js)
        self.assertEqual(dict(prefs), {'foo': 'bar'})
Example #5
0
def test_prefs_write():
    """test that the Preferences.write() method correctly serializes preferences"""

    _prefs = {
        "browser.startup.homepage": "http://planet.mozilla.org",
        "zoom.minPercent": 30,
        "zoom.maxPercent": 300,
    }

    # make a Preferences manager with the testing preferences
    preferences = Preferences(_prefs)

    # write them to a temporary location
    path = None
    read_prefs = None
    try:
        with mozfile.NamedTemporaryFile(suffix=".js", delete=False,
                                        mode="w+t") as f:
            path = f.name
            preferences.write(f, _prefs)

        # read them back and ensure we get what we put in
        read_prefs = dict(Preferences.read_prefs(path))

    finally:
        # cleanup
        if path and os.path.exists(path):
            os.remove(path)

    assert read_prefs == _prefs
Example #6
0
def test_common_prefs_are_all_set(build_profile, profile_data_dir):
    # We set e10s=False here because MochitestDesktop.buildProfile overwrites
    # the value defined in the base profile.
    # TODO stop setting browser.tabs.remote.autostart in the base profile
    md, result = build_profile(e10s=False)

    with open(os.path.join(profile_data_dir, "profiles.json"), "r") as fh:
        base_profiles = json.load(fh)["mochitest"]

    # build the expected prefs
    expected_prefs = {}
    for profile in base_profiles:
        for name in Profile.preference_file_names:
            path = os.path.join(profile_data_dir, profile, name)
            if os.path.isfile(path):
                expected_prefs.update(Preferences.read_prefs(path))

    # read the actual prefs
    actual_prefs = {}
    for name in Profile.preference_file_names:
        path = os.path.join(md.profile.profile, name)
        if os.path.isfile(path):
            actual_prefs.update(Preferences.read_prefs(path))

    # keep this in sync with the values in MochitestDesktop.merge_base_profiles
    interpolation = {
        "server": "127.0.0.1:8888",
    }
    for k, v in expected_prefs.items():
        if isinstance(v, string_types):
            v = v.format(**interpolation)

        assert k in actual_prefs
        assert k and actual_prefs[k] == v
Example #7
0
def test_merge_profile(cls):
    profile = cls(preferences={'foo': 'bar'})
    assert profile._addons == []
    assert os.path.isfile(
        os.path.join(profile.profile, profile.preference_file_names[0]))

    other_profile = os.path.join(here, 'files', 'dummy-profile')
    profile.merge(other_profile)

    # make sure to add a pref file for each preference_file_names in the dummy-profile
    prefs = {}
    for name in profile.preference_file_names:
        path = os.path.join(profile.profile, name)
        assert os.path.isfile(path)

        try:
            prefs.update(Preferences.read_json(path))
        except ValueError:
            prefs.update(Preferences.read_prefs(path))

    assert 'foo' in prefs
    assert len(prefs) == len(profile.preference_file_names) + 1
    assert all(name in prefs for name in profile.preference_file_names)

    assert len(profile._addons) == 1
    assert profile._addons[0].endswith('empty.xpi')
    assert os.path.exists(profile._addons[0])
Example #8
0
    def test_reset_should_remove_added_prefs(self):
        """Check that when we call reset the items we expect are updated"""

        profile = Profile()
        prefs_file = os.path.join(profile.profile, 'user.js')

        # we shouldn't have any initial preferences
        initial_prefs = Preferences.read_prefs(prefs_file)
        self.assertFalse(initial_prefs)
        initial_prefs = file(prefs_file).read().strip()
        self.assertFalse(initial_prefs)

        # add some preferences
        prefs1 = [("mr.t.quotes", "i aint getting on no plane!")]
        profile.set_preferences(prefs1)
        self.assertEqual(prefs1, Preferences.read_prefs(prefs_file))
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue(
            bool([
                line for line in lines
                if line.startswith('#MozRunner Prefs Start')
            ]))
        self.assertTrue(
            bool([
                line for line in lines
                if line.startswith('#MozRunner Prefs End')
            ]))

        profile.reset()
        self.assertNotEqual(
            prefs1,
            Preferences.read_prefs(os.path.join(profile.profile, 'user.js')),
            "I pity the fool who left my pref")
Example #9
0
    def test_prefs_write(self):
        """test that the Preferences.write() method correctly serializes preferences"""

        _prefs = {
            'browser.startup.homepage': "http://planet.mozilla.org",
            'zoom.minPercent': 30,
            'zoom.maxPercent': 300
        }

        # make a Preferences manager with the testing preferences
        preferences = Preferences(_prefs)

        # write them to a temporary location
        path = None
        try:
            with tempfile.NamedTemporaryFile(suffix='.js', delete=False) as f:
                path = f.name
                preferences.write(f, _prefs)

            # read them back and ensure we get what we put in
            self.assertEqual(dict(Preferences.read_prefs(path)), _prefs)

        finally:
            # cleanup
            os.remove(path)
    def test_reset_should_remove_added_prefs(self):
        """Check that when we call reset the items we expect are updated"""

        profile = Profile()
        prefs_file = os.path.join(profile.profile, 'user.js')

        # we shouldn't have any initial preferences
        initial_prefs = Preferences.read_prefs(prefs_file)
        self.assertFalse(initial_prefs)
        initial_prefs = file(prefs_file).read().strip()
        self.assertFalse(initial_prefs)

        # add some preferences
        prefs1 = [("mr.t.quotes", "i aint getting on no plane!")]
        profile.set_preferences(prefs1)
        self.assertEqual(prefs1, Preferences.read_prefs(prefs_file))
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue(bool([line for line in lines
                              if line.startswith('#MozRunner Prefs Start')]))
        self.assertTrue(bool([line for line in lines
                              if line.startswith('#MozRunner Prefs End')]))

        profile.reset()
        self.assertNotEqual(prefs1,
                            Preferences.read_prefs(os.path.join(profile.profile, 'user.js')),
                            "I pity the fool who left my pref")
Example #11
0
def test_json_datatypes():
    # minPercent is at 30.1 to test if non-integer data raises an exception
    json = """{"zoom.minPercent": 30.1, "zoom.maxPercent": 300}"""

    with mozfile.NamedTemporaryFile(suffix=".json") as f:
        f.write(json.encode())
        f.flush()

        with pytest.raises(PreferencesReadError):
            Preferences.read_json(f._path)
Example #12
0
    def test_json_datatypes(self):
        # minPercent is at 30.1 to test if non-integer data raises an exception
        json = """{"zoom.minPercent": 30.1, "zoom.maxPercent": 300}"""

        with mozfile.NamedTemporaryFile(suffix='.json') as f:
            f.write(json)
            f.flush()

            with self.assertRaises(PreferencesReadError):
                Preferences.read_json(f._path)
Example #13
0
    def _clean_pref_file(name):
        js_file = os.path.join(profile_dir, name)
        prefs = Preferences.read_prefs(js_file)
        cleaned_prefs = dict([pref for pref in prefs if _keep_pref(*pref)])
        if name == "prefs.js":
            # When we start Firefox, forces startupScanScopes to SCOPE_PROFILE (1)
            # otherwise, side loading will be deactivated and the
            # Raptor web extension won't be able to run.
            cleaned_prefs["extensions.startupScanScopes"] = 1

        with open(js_file, "w") as f:
            Preferences.write(f, cleaned_prefs)
Example #14
0
    def test_magic_markers(self):
        """ensure our magic markers are working"""

        profile = Profile()
        prefs_file = os.path.join(profile.profile, 'user.js')

        # we shouldn't have any initial preferences
        initial_prefs = Preferences.read_prefs(prefs_file)
        self.assertFalse(initial_prefs)
        initial_prefs = file(prefs_file).read().strip()
        self.assertFalse(initial_prefs)

        # add some preferences
        prefs1 = [("browser.startup.homepage", "http://planet.mozilla.org/"),
                  ("zoom.minPercent", 30)]
        profile.set_preferences(prefs1)
        self.assertEqual(prefs1, Preferences.read_prefs(prefs_file))
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue(
            bool([
                line for line in lines
                if line.startswith('#MozRunner Prefs Start')
            ]))
        self.assertTrue(
            bool([
                line for line in lines
                if line.startswith('#MozRunner Prefs End')
            ]))

        # add some more preferences
        prefs2 = [("zoom.maxPercent", 300), ("webgl.verbose", 'false')]
        profile.set_preferences(prefs2)
        self.assertEqual(prefs1 + prefs2, Preferences.read_prefs(prefs_file))
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue(
            len([
                line for line in lines
                if line.startswith('#MozRunner Prefs Start')
            ]) == 2)
        self.assertTrue(
            len([
                line for line in lines
                if line.startswith('#MozRunner Prefs End')
            ]) == 2)

        # now clean it up
        profile.clean_preferences()
        final_prefs = Preferences.read_prefs(prefs_file)
        self.assertFalse(final_prefs)
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue('#MozRunner Prefs Start' not in lines)
        self.assertTrue('#MozRunner Prefs End' not in lines)
Example #15
0
def create_profile(addons, pref_categories, profile=None):
    from mozprofile.prefs import Preferences
    from mozprofile.profile import Profile
    from subprocess import check_output

    prefs = Preferences()
    for category in pref_categories:
        prefs.add_file("{}:{}".format(C.MOZRUNNER_PREFS_INI, category))

    return Profile(
        addons=addons,
        preferences=prefs(),
        restore=False,
    )
Example #16
0
def test_can_read_prefs_with_multiline_comments():
    """
    Ensure that multiple comments in the file header do not break reading
    the prefs (https://bugzilla.mozilla.org/show_bug.cgi?id=1233534).
    """
    user_js = tempfile.NamedTemporaryFile(suffix=".js", delete=False)
    try:
        with user_js:
            user_js.write("""
# Mozilla User Preferences

/* Do not edit this file.
*
* If you make changes to this file while the application is running,
* the changes will be overwritten when the application exits.
*
* To make a manual change to preferences, you can visit the URL about:config
*/

user_pref("webgl.enabled_for_all_sites", true);
user_pref("webgl.force-enabled", true);
""".encode())
        assert Preferences.read_prefs(user_js.name) == [
            ("webgl.enabled_for_all_sites", True),
            ("webgl.force-enabled", True),
        ]
    finally:
        mozfile.remove(user_js.name)
Example #17
0
 def add_prefs_from_file(self, fname):
     prefs = Preferences.read(fname)
     if prefs:
         nb_prefs = len(self.prefs)
         self.beginInsertRows(QModelIndex(), nb_prefs, nb_prefs + len(prefs) - 1)
         self.prefs.extend(list(prefs.items()))
         self.endInsertRows()
Example #18
0
    def test_can_read_prefs_with_multiline_comments(self):
        """
        Ensure that multiple comments in the file header do not break reading
        the prefs (https://bugzilla.mozilla.org/show_bug.cgi?id=1233534).
        """
        user_js = tempfile.NamedTemporaryFile(suffix='.js', delete=False)
        self.addCleanup(mozfile.remove, user_js.name)
        with user_js:
            user_js.write("""
# Mozilla User Preferences

/* Do not edit this file.
 *
 * If you make changes to this file while the application is running,
 * the changes will be overwritten when the application exits.
 *
 * To make a manual change to preferences, you can visit the URL about:config
 */

user_pref("webgl.enabled_for_all_sites", true);
user_pref("webgl.force-enabled", true);
""")
        self.assertEqual(
            Preferences.read_prefs(user_js.name),
            [('webgl.enabled_for_all_sites', True),
             ('webgl.force-enabled', True)]
        )
Example #19
0
    def run(self, metadata):
        if self.get_arg("directory") is not None:
            # no need to create one or load a conditioned one
            return

        # XXX we'll use conditioned profiles later
        profile = create_profile(app="firefox")

        # mozprofile.Profile.__del__ silently deletes the profile
        # it creates in a non-deterministic time (garbage collected) by
        # calling cleanup. We override this silly behavior here.
        profile.cleanup = self._cleanup

        prefs = metadata.get_options("browser_prefs")

        if prefs == {}:
            prefs["mozperftest"] = "true"

        # apply custom user prefs if any
        user_js = self.get_arg("user-js")
        if user_js is not None:
            self.info("Applying use prefs from %s" % user_js)
            default_prefs = dict(Preferences.read_prefs(user_js))
            prefs.update(default_prefs)

        profile.set_preferences(prefs)
        self.info("Created profile at %s" % profile.profile)
        self._created_dirs.append(profile.profile)
        self.set_arg("profile-directory", profile.profile)
        return metadata
Example #20
0
 def add_prefs_from_file(self, fname):
     prefs = Preferences.read(fname)
     if prefs:
         nb_prefs = len(self.prefs)
         self.beginInsertRows(QModelIndex(), nb_prefs,
                              nb_prefs + len(prefs) - 1)
         self.prefs.extend(prefs.items())
         self.endInsertRows()
Example #21
0
def test_preexisting_preferences():
    """ensure you don't clobber preexisting preferences"""

    # make a pretend profile
    tempdir = tempfile.mkdtemp()

    try:
        # make a user.js
        contents = """
user_pref("webgl.enabled_for_all_sites", true);
user_pref("webgl.force-enabled", true);
"""
        user_js = os.path.join(tempdir, "user.js")
        f = open(user_js, "w")
        f.write(contents)
        f.close()

        # make sure you can read it
        prefs = Preferences.read_prefs(user_js)
        original_prefs = [
            ("webgl.enabled_for_all_sites", True),
            ("webgl.force-enabled", True),
        ]
        assert prefs == original_prefs

        # now read this as a profile
        profile = Profile(
            tempdir, preferences={"browser.download.dir": "/home/jhammel"})

        # make sure the new pref is now there
        new_prefs = original_prefs[:] + [
            ("browser.download.dir", "/home/jhammel")
        ]
        prefs = Preferences.read_prefs(user_js)
        assert prefs == new_prefs

        # clean up the added preferences
        profile.cleanup()
        del profile

        # make sure you have the original preferences
        prefs = Preferences.read_prefs(user_js)
        assert prefs == original_prefs
    finally:
        shutil.rmtree(tempdir)
Example #22
0
 def inner(prefs, commandline):
     profile = run_command(*commandline)
     prefs_file = os.path.join(profile, "user.js")
     assert os.path.exists(prefs_file)
     read = Preferences.read_prefs(prefs_file)
     if isinstance(prefs, dict):
         read = dict(read)
     assert prefs == read
     shutil.rmtree(profile)
Example #23
0
    def test_read_prefs_with_comments(self):
        """test reading preferences from a prefs.js file that contains comments"""

        _prefs = {'browser.startup.homepage': 'http://planet.mozilla.org',
                  'zoom.minPercent': 30,
                  'zoom.maxPercent': 300,
                  'webgl.verbose': 'false'}
        path = os.path.join(here, 'files', 'prefs_with_comments.js')
        self.assertEqual(dict(Preferences.read_prefs(path)), _prefs)
Example #24
0
    def test_cache(self):
        download_dir = os.path.expanduser("~/.condprof-cache")
        if os.path.exists(download_dir):
            num_elmts = len(os.listdir(download_dir))
        else:
            num_elmts = 0

        get_profile(self.target, "win64", "settled", "default")

        # grabbing a profile should generate two files
        self.assertEqual(len(os.listdir(download_dir)), num_elmts + 2)

        # we do at least two network calls when getting a file,
        # a HEAD and a GET and possibly a TC secret
        self.assertTrue(len(responses.calls) >= 2)

        # reseting the response counters
        responses.calls.reset()

        # and we should reuse them without downloading the file again
        get_profile(self.target, "win64", "settled", "default")

        # grabbing a profile should not download new stuff
        self.assertEqual(len(os.listdir(download_dir)), num_elmts + 2)

        # and do a single extra HEAD call, everything else is cached,
        # even the TC secret
        self.assertEqual(len(responses.calls), 2)

        prefs_js = os.path.join(self.target, "prefs.js")
        prefs = Preferences.read_prefs(prefs_js)

        # check that the gfx.blacklist prefs where cleaned out
        for name, value in prefs:
            self.assertFalse(name.startswith("gfx.blacklist"))

        # check that we have the startupScanScopes option forced
        prefs = dict(prefs)
        self.assertEqual(prefs["extensions.startupScanScopes"], 1)

        # make sure we don't have any marionette option set
        user_js = os.path.join(self.target, "user.js")
        for name, value in Preferences.read_prefs(user_js):
            self.assertFalse(name.startswith("marionette."))
Example #25
0
def test_magic_markers():
    """ensure our magic markers are working"""

    profile = Profile()
    prefs_file = os.path.join(profile.profile, "user.js")

    # we shouldn't have any initial preferences
    initial_prefs = Preferences.read_prefs(prefs_file)
    assert not initial_prefs
    initial_prefs = open(prefs_file).read().strip()
    assert not initial_prefs

    # add some preferences
    prefs1 = [
        ("browser.startup.homepage", "http://planet.mozilla.org/"),
        ("zoom.minPercent", 30),
    ]
    profile.set_preferences(prefs1)
    assert prefs1 == Preferences.read_prefs(prefs_file)
    lines = open(prefs_file).read().strip().splitlines()
    assert bool(
        [line for line in lines if line.startswith("#MozRunner Prefs Start")])
    assert bool(
        [line for line in lines if line.startswith("#MozRunner Prefs End")])

    # add some more preferences
    prefs2 = [("zoom.maxPercent", 300), ("webgl.verbose", "false")]
    profile.set_preferences(prefs2)
    assert prefs1 + prefs2 == Preferences.read_prefs(prefs_file)
    lines = open(prefs_file).read().strip().splitlines()
    assert (len([
        line for line in lines if line.startswith("#MozRunner Prefs Start")
    ]) == 2)
    assert len([
        line for line in lines if line.startswith("#MozRunner Prefs End")
    ]) == 2

    # now clean it up
    profile.clean_preferences()
    final_prefs = Preferences.read_prefs(prefs_file)
    assert not final_prefs
    lines = open(prefs_file).read().strip().splitlines()
    assert "#MozRunner Prefs Start" not in lines
    assert "#MozRunner Prefs End" not in lines
Example #26
0
 def setData(self, index, new_value, role=Qt.EditRole):
     name, value = self.prefs[index.row()]
     if index.column() == 0:
         # change pref name
         name = new_value
     else:
         # change pref value
         value = Preferences.cast(new_value)
     self.prefs[index.row()] = (name, value)
     return True
Example #27
0
 def test_ordered_prefs(self):
     """ensure the prefs stay in the right order"""
     _prefs = [("browser.startup.homepage", "http://planet.mozilla.org/"),
               ("zoom.minPercent", 30), ("zoom.maxPercent", 300),
               ("webgl.verbose", 'false')]
     commandline = []
     for pref, value in _prefs:
         commandline += ["--pref", "%s:%s" % (pref, value)]
     _prefs = [(i, Preferences.cast(j)) for i, j in _prefs]
     self.compare_generated(_prefs, commandline)
Example #28
0
 def test_ordered_prefs(self):
     """ensure the prefs stay in the right order"""
     _prefs = [("browser.startup.homepage", "http://planet.mozilla.org/"),
               ("zoom.minPercent", 30),
               ("zoom.maxPercent", 300),
               ("webgl.verbose", 'false')]
     commandline = ["mozprofile"]
     for pref, value in _prefs:
         commandline += ["--pref", "%s:%s" % (pref, value)]
     _prefs = [(i, Preferences.cast(j)) for i, j in _prefs]
     self.compare_generated(_prefs, commandline)
Example #29
0
    def test_read_prefs_with_comments(self):
        """test reading preferences from a prefs.js file that contains comments"""

        _prefs = {
            'browser.startup.homepage': 'http://planet.mozilla.org',
            'zoom.minPercent': 30,
            'zoom.maxPercent': 300,
            'webgl.verbose': 'false'
        }
        path = os.path.join(here, 'files', 'prefs_with_comments.js')
        self.assertEqual(dict(Preferences.read_prefs(path)), _prefs)
Example #30
0
 def setData(self, index, new_value, role=Qt.EditRole):
     new_value = unicode(new_value.toString())
     name, value = self.prefs[index.row()]
     if index.column() == 0:
         # change pref name
         name = new_value
     else:
         # change pref value
         value = Preferences.cast(new_value)
     self.prefs[index.row()] = (name, value)
     return True
    def test_magic_markers(self):
        """ensure our magic markers are working"""

        profile = Profile()
        prefs_file = os.path.join(profile.profile, 'user.js')

        # we shouldn't have any initial preferences
        initial_prefs = Preferences.read_prefs(prefs_file)
        self.assertFalse(initial_prefs)
        initial_prefs = file(prefs_file).read().strip()
        self.assertFalse(initial_prefs)

        # add some preferences
        prefs1 = [("browser.startup.homepage", "http://planet.mozilla.org/"),
                   ("zoom.minPercent", 30)]
        profile.set_preferences(prefs1)
        self.assertEqual(prefs1, Preferences.read_prefs(prefs_file))
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue(bool([line for line in lines
                              if line.startswith('#MozRunner Prefs Start')]))
        self.assertTrue(bool([line for line in lines
                              if line.startswith('#MozRunner Prefs End')]))

        # add some more preferences
        prefs2 = [("zoom.maxPercent", 300),
                   ("webgl.verbose", 'false')]
        profile.set_preferences(prefs2)
        self.assertEqual(prefs1 + prefs2, Preferences.read_prefs(prefs_file))
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue(len([line for line in lines
                             if line.startswith('#MozRunner Prefs Start')]) == 2)
        self.assertTrue(len([line for line in lines
                             if line.startswith('#MozRunner Prefs End')]) == 2)

        # now clean it up
        profile.clean_preferences()
        final_prefs = Preferences.read_prefs(prefs_file)
        self.assertFalse(final_prefs)
        lines = file(prefs_file).read().strip().splitlines()
        self.assertTrue('#MozRunner Prefs Start' not in lines)
        self.assertTrue('#MozRunner Prefs End' not in lines)
    def test_read_prefs_ttw(self):
        """test reading preferences through the web via mozhttpd"""

        # create a MozHttpd instance
        docroot = os.path.join(here, 'files')
        host = '127.0.0.1'
        port = 8888
        httpd = mozhttpd.MozHttpd(host=host, port=port, docroot=docroot)

        # create a preferences instance
        prefs = Preferences()

        try:
            # start server
            httpd.start(block=False)

            # read preferences through the web
            read = prefs.read_prefs('http://%s:%d/prefs_with_comments.js' % (host, port))
            self.assertEqual(dict(read), self._prefs_with_comments)
        finally:
            httpd.stop()
Example #33
0
def test_read_prefs_ttw():
    """test reading preferences through the web via mozhttpd"""

    # create a MozHttpd instance
    docroot = os.path.join(here, 'files')
    host = '127.0.0.1'
    port = 8888
    httpd = mozhttpd.MozHttpd(host=host, port=port, docroot=docroot)

    # create a preferences instance
    prefs = Preferences()

    try:
        # start server
        httpd.start(block=False)

        # read preferences through the web
        read = prefs.read_prefs('http://%s:%d/prefs_with_comments.js' % (host, port))
        assert dict(read) == _prefs_with_comments
    finally:
        httpd.stop()
Example #34
0
def test_reset_should_keep_user_added_prefs():
    """Check that when we call reset the items we expect are updated"""
    profile = Profile()
    prefs_file = os.path.join(profile.profile, 'user.js')

    # we shouldn't have any initial preferences
    initial_prefs = Preferences.read_prefs(prefs_file)
    assert not initial_prefs
    initial_prefs = open(prefs_file).read().strip()
    assert not initial_prefs

    # add some preferences
    prefs1 = [("mr.t.quotes", "i aint getting on no plane!")]
    profile.set_persistent_preferences(prefs1)
    assert prefs1 == Preferences.read_prefs(prefs_file)
    lines = open(prefs_file).read().strip().splitlines()
    assert any(line.startswith('#MozRunner Prefs Start') for line in lines)
    assert any(line.startswith('#MozRunner Prefs End') for line in lines)

    profile.reset()
    assert prefs1 == Preferences.read_prefs(os.path.join(profile.profile, 'user.js'))
Example #35
0
    def test_preexisting_preferences(self):
        """ensure you don't clobber preexisting preferences"""

        # make a pretend profile
        tempdir = tempfile.mkdtemp()

        try:
            # make a user.js
            contents = """
user_pref("webgl.enabled_for_all_sites", true);
user_pref("webgl.force-enabled", true);
"""
            user_js = os.path.join(tempdir, 'user.js')
            f = file(user_js, 'w')
            f.write(contents)
            f.close()

            # make sure you can read it
            prefs = Preferences.read_prefs(user_js)
            original_prefs = [('webgl.enabled_for_all_sites', True), ('webgl.force-enabled', True)]
            self.assertTrue(prefs == original_prefs)

            # now read this as a profile
            profile = Profile(tempdir, preferences={"browser.download.dir": "/home/jhammel"})

            # make sure the new pref is now there
            new_prefs = original_prefs[:] + [("browser.download.dir", "/home/jhammel")]
            prefs = Preferences.read_prefs(user_js)
            self.assertTrue(prefs == new_prefs)

            # clean up the added preferences
            profile.cleanup()
            del profile

            # make sure you have the original preferences
            prefs = Preferences.read_prefs(user_js)
            self.assertTrue(prefs == original_prefs)
        except:
            shutil.rmtree(tempdir)
            raise
Example #36
0
def test_read_prefs_ttw():
    """test reading preferences through the web via wptserve"""

    # create a WebTestHttpd instance
    docroot = os.path.join(here, "files")
    host = "127.0.0.1"
    port = 8888
    httpd = server.WebTestHttpd(host=host, port=port, doc_root=docroot)

    # create a preferences instance
    prefs = Preferences()

    try:
        # start server
        httpd.start()

        # read preferences through the web
        read = prefs.read_prefs("http://%s:%d/prefs_with_comments.js" %
                                (host, port))
        assert dict(read) == _prefs_with_comments
    finally:
        httpd.stop()
Example #37
0
def test_nonce(tmpdir):
    # make a profile with one preference
    path = tmpdir.strpath
    profile = Profile(path, preferences={"foo": "bar"}, restore=False)
    user_js = os.path.join(profile.profile, "user.js")
    assert os.path.exists(user_js)

    # ensure the preference is correct
    prefs = Preferences.read_prefs(user_js)
    assert dict(prefs) == {"foo": "bar"}

    del profile

    # augment the profile with a second preference
    profile = Profile(path, preferences={"fleem": "baz"}, restore=True)
    prefs = Preferences.read_prefs(user_js)
    assert dict(prefs) == {"foo": "bar", "fleem": "baz"}

    # cleanup the profile;
    # this should remove the new preferences but not the old
    profile.cleanup()
    prefs = Preferences.read_prefs(user_js)
    assert dict(prefs) == {"foo": "bar"}
Example #38
0
def test_read_prefs_with_interpolation():
    """test reading preferences from a prefs.js file whose values
    require interpolation"""

    expected_prefs = {
        "browser.foo": "http://server-name",
        "zoom.minPercent": 30,
        "webgl.verbose": "false",
        "browser.bar": "somethingxyz",
    }
    values = {"server": "server-name", "abc": "something"}
    path = os.path.join(here, "files", "prefs_with_interpolation.js")
    read_prefs = Preferences.read_prefs(path, interpolation=values)
    assert dict(read_prefs) == expected_prefs
Example #39
0
 def compare_generated(self, _prefs, commandline):
     """
     writes out to a new profile with mozprofile command line
     reads the generated preferences with prefs.py
     compares the results
     cleans up
     """
     profile, stderr, code = self.run_command(*commandline)
     prefs_file = os.path.join(profile, 'user.js')
     self.assertTrue(os.path.exists(prefs_file))
     read = Preferences.read_prefs(prefs_file)
     if isinstance(_prefs, dict):
         read = dict(read)
     self.assertEqual(_prefs, read)
     shutil.rmtree(profile)
Example #40
0
 def compare_generated(self, _prefs, commandline):
     """
     writes out to a new profile with mozprofile command line
     reads the generated preferences with prefs.py
     compares the results
     cleans up
     """
     profile = self.run_command(*commandline)
     prefs_file = os.path.join(profile, 'user.js')
     self.assertTrue(os.path.exists(prefs_file))
     read = Preferences.read_prefs(prefs_file)
     if isinstance(_prefs, dict):
         read = dict(read)
     self.assertEqual(_prefs, read)
     shutil.rmtree(profile)
Example #41
0
    def test_read_prefs_with_interpolation(self):
        """test reading preferences from a prefs.js file whose values
        require interpolation"""

        expected_prefs = {
            "browser.foo": "http://server-name",
            "zoom.minPercent": 30,
            "webgl.verbose": "false",
            "browser.bar": "somethingxyz"
            }
        values = {
            "server": "server-name",
            "abc": "something"
            }
        path = os.path.join(here, 'files', 'prefs_with_interpolation.js')
        read_prefs = Preferences.read_prefs(path, interpolation=values)
        self.assertEqual(dict(read_prefs), expected_prefs)
Example #42
0
    def test_read_prefs_with_comments(self):
        """test reading preferences from a prefs.js file that contains comments"""

        path = os.path.join(here, 'files', 'prefs_with_comments.js')
        self.assertEqual(dict(Preferences.read_prefs(path)),
                         self._prefs_with_comments)
Example #43
0
def test_read_prefs_with_comments():
    """test reading preferences from a prefs.js file that contains comments"""

    path = os.path.join(here, "files", "prefs_with_comments.js")
    assert dict(Preferences.read_prefs(path)) == _prefs_with_comments
Example #44
0
def parse_pref(value):
    """parse a preference value from a string"""
    from mozprofile.prefs import Preferences

    return Preferences.cast(value)
    def test_read_prefs_with_comments(self):
        """test reading preferences from a prefs.js file that contains comments"""

        path = os.path.join(here, 'files', 'prefs_with_comments.js')
        self.assertEqual(dict(Preferences.read_prefs(path)), self._prefs_with_comments)
Example #46
0
def parse_pref(value):
    """parse a preference value from a string"""
    from mozprofile.prefs import Preferences
    return Preferences.cast(value)