def test_profileprint(self): """ test the summary function """ keys = set(['Files', 'Path', 'user.js']) ff_prefs = mozprofile.FirefoxProfile.preferences # shorthand pref_string = '\n'.join([ '%s: %s' % (key, ff_prefs[key]) for key in sorted(ff_prefs.keys()) ]) tempdir = tempfile.mkdtemp() try: profile = mozprofile.FirefoxProfile(tempdir) parts = profile.summary(return_parts=True) parts = dict(parts) self.assertEqual(parts['Path'], tempdir) self.assertEqual(set(parts.keys()), keys) self.assertEqual(pref_string, parts['user.js'].strip()) except BaseException: raise finally: mozfile.rmtree(tempdir)
def __del__(self): try: Launcher.__del__(self) finally: # always remove tempdir if self.tempdir is not None: rmtree(self.tempdir)
def test_noclean(self): """test `restore=True/False` functionality""" profile = tempfile.mkdtemp() tmpdir = tempfile.mkdtemp() try: # empty initially self.assertFalse(bool(os.listdir(profile))) # make an addon stub = addon_stubs.generate_addon(name='empty-0-1.xpi', path=tmpdir) # install it with a restore=True AddonManager addons = mozprofile.addons.AddonManager(profile, restore=True) addons.install_from_path(stub) # now its there self.assertEqual(os.listdir(profile), ['extensions']) extensions = os.path.join(profile, 'extensions', 'staged') self.assertTrue(os.path.exists(extensions)) contents = os.listdir(extensions) self.assertEqual(len(contents), 1) # del addons; now its gone though the directory tree exists del addons self.assertEqual(os.listdir(profile), ['extensions']) self.assertTrue(os.path.exists(extensions)) contents = os.listdir(extensions) self.assertEqual(len(contents), 0) finally: mozfile.rmtree(tmpdir) mozfile.rmtree(profile)
def test_get_binary_error(self): """ Test an InvalidBinary error is raised """ tempdir_empty = tempfile.mkdtemp() self.assertRaises(mozinstall.InvalidBinary, mozinstall.get_binary, tempdir_empty, 'firefox') mozfile.rmtree(tempdir_empty)
def test_basic(self): """ Test mozhttpd can serve files """ tempdir = tempfile.mkdtemp() # sizes is a dict of the form: name -> [size, binary_string, filepath] sizes = {'small': [128], 'large': [16384]} for k in sizes.keys(): # Generate random binary string sizes[k].append(os.urandom(sizes[k][0])) # Add path of file with binary string to list fpath = os.path.join(tempdir, k) sizes[k].append(fpath) # Write binary string to file with open(fpath, 'wb') as f: f.write(sizes[k][1]) server = mozhttpd.MozHttpd(docroot=tempdir) server.start() server_url = server.get_url() # Retrieve file and check contents matchup for k in sizes.keys(): retrieved_content = mozfile.load(server_url + k).read() self.assertEqual(retrieved_content, sizes[k][1]) # Cleanup tempdir and related files mozfile.rmtree(tempdir)
def cleanup(self): try: Launcher.cleanup(self) finally: # always remove tempdir if self.tempdir is not None: rmtree(self.tempdir)
def install(self): rmtree("moznightlyapp") subprocess._cleanup = lambda: None # mikeal's fix for subprocess threading bug MozInstaller(src=self.dest, dest="moznightlyapp", dest_app="Mozilla.app") return True
def test_remove_directory(self): self.assertTrue(os.path.isdir(self.tempdir)) try: mozfile.rmtree(self.tempdir) except: shutil.rmtree(self.tempdir) raise self.assertFalse(os.path.exists(self.tempdir))
def _install(self, dest): self.tempdir = safe_mkdtemp() try: self.binary = mozinstall.get_binary( mozinstall.install(src=dest, dest=self.tempdir), self.app_name) except Exception: rmtree(self.tempdir) raise
def remove_addon(self, addon_id): """Remove the add-on as specified by the id :param addon_id: id of the add-on to be removed """ path = self.get_addon_path(addon_id) if os.path.isdir(path): mozfile.rmtree(path) elif os.path.isfile(path): os.remove(path)
def test_remove_directory(self): tempdir = create_stub() self.assertTrue(os.path.exists(tempdir)) self.assertTrue(os.path.isdir(tempdir)) try: mozfile.rmtree(tempdir) except: shutil.rmtree(tempdir) raise self.assertFalse(os.path.exists(tempdir))
def tearDown(self): mozfile.rmtree(self.tmpdir) self.am = None self.profile = None # Bug 934484 # Sometimes the profile folder gets recreated at the end and will be left # behind. So we should ensure that we clean it up correctly. mozfile.rmtree(self.profile_path)
def _install(self, dest): self.tempdir = tempfile.mkdtemp() try: self.binary = mozinstall.get_binary( mozinstall.install(src=dest, dest=self.tempdir), self.app_name ) except: rmtree(self.tempdir) raise
def test_remove_directory_after_closing_file(self): """ Test that the call to mozfile.rmtree succeeds on all platforms after file is closed """ filepath = os.path.join(self.tempdir, *stubs.files[1]) with open(filepath, "w") as f: f.write("foo-bar") # Delete directory tree mozfile.rmtree(self.tempdir) # Check deletion is successful self.assertFalse(os.path.exists(self.tempdir))
def _install(self, dest): self.tempdir = safe_mkdtemp() try: with zipfile.ZipFile(dest, "r") as z: z.extractall(self.tempdir) self.binary = os.path.join( self.tempdir, 'js' if mozinfo.os != 'win' else 'js.exe') # set the file executable os.chmod(self.binary, os.stat(self.binary).st_mode | stat.S_IEXEC) except Exception: rmtree(self.tempdir) raise
def _install(self, dest): self.tempdir = tempfile.mkdtemp() try: with zipfile.ZipFile(dest, "r") as z: z.extractall(self.tempdir) self.binary = os.path.join( self.tempdir, 'js' if mozinfo.os != 'win' else 'js.exe' ) # set the file executable os.chmod(self.binary, os.stat(self.binary).st_mode | stat.S_IEXEC) except: rmtree(self.tempdir) raise
def test_remove_directory_with_open_file(self): """ Tests handling when removing a directory tree which has a file in it is still open """ # Open a file in the generated stub filepath = os.path.join(self.tempdir, *stubs.files[1]) f = file(filepath, "w") f.write("foo-bar") # keep file open and then try removing the dir-tree if mozinfo.isWin: # On the Windows family WindowsError should be raised. self.assertRaises(WindowsError, mozfile.rmtree, self.tempdir) else: # Folder should be deleted on all other platforms mozfile.rmtree(self.tempdir) self.assertFalse(os.path.exists(self.tempdir))
def test_install_from_manifest(self): temp_manifest = addon_stubs.generate_manifest() m = ManifestParser() m.read(temp_manifest) addons = m.get() # Obtain details of addons to install from the manifest addons_to_install = [self.am.addon_details(x['path'])['id'] for x in addons] self.am.install_from_manifest(temp_manifest) # Generate a list of addons installed in the profile addons_installed = [unicode(x[:-len('.xpi')]) for x in os.listdir(os.path.join( self.profile.profile, 'extensions', 'staged'))] self.assertEqual(addons_installed.sort(), addons_to_install.sort()) # Cleanup the temporary addon and manifest directories mozfile.rmtree(os.path.dirname(temp_manifest))
def test_install_from_path(self): addons_to_install = [] addons_installed = [] # Generate installer stubs and install them tmpdir = tempfile.mkdtemp() for t in ['empty-0-1.xpi', 'another-empty-0-1.xpi']: temp_addon = addon_stubs.generate_addon(name=t, path=tmpdir) addons_to_install.append(self.am.addon_details(temp_addon)['id']) self.am.install_from_path(temp_addon) # Generate a list of addons installed in the profile addons_installed = [unicode(x[:-len('.xpi')]) for x in os.listdir(os.path.join( self.profile.profile, 'extensions', 'staged'))] self.assertEqual(addons_to_install.sort(), addons_installed.sort()) # Cleanup the temporary addon directories mozfile.rmtree(tmpdir)
def test_noclean(self): """test `restore=True/False` functionality""" server = mozhttpd.MozHttpd(docroot=os.path.join(here, 'addons')) server.start() profile = tempfile.mkdtemp() tmpdir = tempfile.mkdtemp() try: # empty initially self.assertFalse(bool(os.listdir(profile))) # make an addon addons = [] addons.append(generate_addon('*****@*****.**', path=tmpdir)) addons.append(server.get_url() + 'empty.xpi') # install it with a restore=True AddonManager am = mozprofile.addons.AddonManager(profile, restore=True) for addon in addons: am.install_from_path(addon) # now its there self.assertEqual(os.listdir(profile), ['extensions']) staging_folder = os.path.join(profile, 'extensions', 'staged') self.assertTrue(os.path.exists(staging_folder)) self.assertEqual(len(os.listdir(staging_folder)), 2) # del addons; now its gone though the directory tree exists downloaded_addons = am.downloaded_addons del am self.assertEqual(os.listdir(profile), ['extensions']) self.assertTrue(os.path.exists(staging_folder)) self.assertEqual(os.listdir(staging_folder), []) for addon in downloaded_addons: self.assertFalse(os.path.isfile(addon)) finally: mozfile.rmtree(tmpdir) mozfile.rmtree(profile)
def test_noclean(self): """test `restore=True/False` functionality""" server = mozhttpd.MozHttpd(docroot=os.path.join(here, 'addons')) server.start() profile = tempfile.mkdtemp() tmpdir = tempfile.mkdtemp() try: # empty initially self.assertFalse(bool(os.listdir(profile))) # make an addon addons = [] addons.append( generate_addon('*****@*****.**', path=tmpdir)) addons.append(server.get_url() + 'empty.xpi') # install it with a restore=True AddonManager am = mozprofile.addons.AddonManager(profile, restore=True) for addon in addons: am.install_from_path(addon) # now its there self.assertEqual(os.listdir(profile), ['extensions']) staging_folder = os.path.join(profile, 'extensions', 'staged') self.assertTrue(os.path.exists(staging_folder)) self.assertEqual(len(os.listdir(staging_folder)), 2) # del addons; now its gone though the directory tree exists downloaded_addons = am.downloaded_addons del am self.assertEqual(os.listdir(profile), ['extensions']) self.assertTrue(os.path.exists(staging_folder)) self.assertEqual(os.listdir(staging_folder), []) for addon in downloaded_addons: self.assertFalse(os.path.isfile(addon)) finally: mozfile.rmtree(tmpdir) mozfile.rmtree(profile)
def generate_addon(addon_id, path=None, name=None, xpi=True): """ Method to generate a single addon. :param addon_id: id of an addon to generate from the stubs dictionary :param path: path where addon and .xpi should be generated :param name: name for the addon folder or .xpi file :param xpi: Flag if an XPI or folder should be generated Returns the file-path of the addon's .xpi file """ if not addon_id in stubs.keys(): raise IOError('Requested addon stub "%s" does not exist' % addon_id) # Generate directory structure for addon try: tmpdir = path or tempfile.mkdtemp() addon_dir = os.path.join(tmpdir, name or addon_id) os.mkdir(addon_dir) except IOError: raise IOError('Could not generate directory structure for addon stub.') # Write install.rdf for addon if stubs[addon_id]: install_rdf = os.path.join(addon_dir, 'install.rdf') with open(install_rdf, 'w') as f: manifest = os.path.join(here, 'install_manifests', stubs[addon_id]) f.write(open(manifest, 'r').read()) if not xpi: return addon_dir # Generate the .xpi for the addon xpi_file = os.path.join(tmpdir, (name or addon_id) + '.xpi') with zipfile.ZipFile(xpi_file, 'w') as x: x.write(install_rdf, install_rdf[len(addon_dir):]) # Ensure we remove the temporary folder to not install the addon twice mozfile.rmtree(addon_dir) return xpi_file
def generate_addon(addon_id, path=None, name=None, xpi=True): """ Method to generate a single addon. :param addon_id: id of an addon to generate from the stubs dictionary :param path: path where addon and .xpi should be generated :param name: name for the addon folder or .xpi file :param xpi: Flag if an XPI or folder should be generated Returns the file-path of the addon's .xpi file """ if addon_id not in stubs.keys(): raise IOError('Requested addon stub "%s" does not exist' % addon_id) # Generate directory structure for addon try: tmpdir = path or tempfile.mkdtemp() addon_dir = os.path.join(tmpdir, name or addon_id) os.mkdir(addon_dir) except IOError: raise IOError('Could not generate directory structure for addon stub.') # Write install.rdf for addon if stubs[addon_id]: install_rdf = os.path.join(addon_dir, 'install.rdf') with open(install_rdf, 'w') as f: manifest = os.path.join(here, 'install_manifests', stubs[addon_id]) f.write(open(manifest, 'r').read()) if not xpi: return addon_dir # Generate the .xpi for the addon xpi_file = os.path.join(tmpdir, (name or addon_id) + '.xpi') with zipfile.ZipFile(xpi_file, 'w') as x: x.write(install_rdf, install_rdf[len(addon_dir):]) # Ensure we remove the temporary folder to not install the addon twice mozfile.rmtree(addon_dir) return xpi_file
def __init__(self, **kwargs): debug("uninstall constructor") assert (kwargs['dest'] != "" and kwargs['dest'] != None) assert (kwargs['productName'] != "" and kwargs['productName'] != None) assert (kwargs['branch'] != "" and kwargs['dest'] != None) self.dest = kwargs['dest'] self.productName = kwargs['productName'] self.branch = kwargs['branch'] # Handle the case where we haven't installed yet if not os.path.exists(self.dest): return if getPlatform() == "Windows": try: self.doWindowsUninstall() except: debug("Windows Uninstall threw - not overly urgent or worrisome") if os.path.exists(self.dest): try: os.rmdir(self.dest) except OSError: # Directories are still there - kill them all! rmtree(self.dest)
def test_profileprint(self): """ test the summary function """ keys = set(['Files', 'Path', 'user.js']) ff_prefs = mozprofile.FirefoxProfile.preferences # shorthand pref_string = '\n'.join(['%s: %s' % (key, ff_prefs[key]) for key in sorted(ff_prefs.keys())]) tempdir = tempfile.mkdtemp() try: profile = mozprofile.FirefoxProfile(tempdir) parts = profile.summary(return_parts=True) parts = dict(parts) self.assertEqual(parts['Path'], tempdir) self.assertEqual(set(parts.keys()), keys) self.assertEqual(pref_string, parts['user.js'].strip()) except: raise finally: mozfile.rmtree(tempdir)
raise Exception('Failure removing uninstall folder.') except Exception, e: cls, exc, trbk = sys.exc_info() error = UninstallError('Failed to uninstall %s' % install_folder) raise UninstallError, error, trbk finally: # trbk won't get GC'ed due to circular reference # http://docs.python.org/library/sys.html#sys.exc_info del trbk # Ensure that we remove any trace of the installation. Even the uninstaller # on Windows leaves files behind we have to explicitely remove. mozfile.rmtree(install_folder) def _install_dmg(src, dest): """Extract a dmg file into the destination folder and return the application folder. Arguments: src -- DMG image which has to be extracted dest -- the path to extract to """ try: proc = subprocess.Popen('hdiutil attach %s' % src, shell=True, stdout=subprocess.PIPE)
parser.add_option("-s", "--Source", dest="src", help="Installation Source File (whatever was downloaded) -\ accepts Zip, Exe, Tar.Bz, Tar.Gz, and DMG", metavar="SRC_FILE") parser.add_option("-d", "--Destination", dest="dest", help="Directory to install the build into", metavar="DEST") parser.add_option("-b", "--Branch", dest="branch", help="Branch the build is from must be one of: 1.8.0|1.8|\ 1.9", metavar="BRANCH") parser.add_option("-p", "--Product", dest="product", help="Product name - optional should be all lowercase if\ specified: firefox, fennec, thunderbird, etc", metavar="PRODUCT") parser.add_option("-o", "--Operation", dest="op", help="The operation you would like the script to perform.\ Should be either install (i) or uninstall (u) or delete\ (d) to recursively delete the directory specified in dest", metavar="OP") (options, args) = parser.parse_args() # Run it if string.upper(options.op) == "INSTALL" or string.upper(options.op) == "I": installer = MozInstaller(src = options.src, dest = options.dest, branch = options.branch, productName = options.product) elif string.upper(options.op) == "UNINSTALL" or string.upper(options.op) == "U": uninstaller = MozUninstaller(dest = options.dest, branch = options.branch, productName = options.product) elif string.upper(options.op) == "DELETE" or string.upper(options.op) == "D": rmtree(options.dest)
def tearDown(self): # Cleanup the stub if it sill exists if os.path.isdir(self.tempdir): mozfile.rmtree(self.tempdir)
def _stop(self): self.runner.stop() rmtree(self.tempdir)
def tearDown(self): self.httpd.stop() mozfile.rmtree(self.temp_dir)
def tearDown(self): mozfile.rmtree(self.temp_dir)
def install_from_path(self, path, unpack=False): """ Installs addon from a filepath, url or directory of addons in the profile. :param path: url, path to .xpi, or directory of addons :param unpack: whether to unpack unless specified otherwise in the install.rdf """ # if the addon is a URL, download it # note that this won't work with protocols urllib2 doesn't support if mozfile.is_url(path): path = self.download(path) self.downloaded_addons.append(path) addons = [path] # if path is not an add-on, try to install all contained add-ons if not self.is_addon(path): # If the path doesn't exist, then we don't really care, just return if not os.path.isdir(path): return addons = [os.path.join(path, x) for x in os.listdir(path) if self.is_addon(os.path.join(path, x))] addons.sort() # install each addon for addon in addons: # determine the addon id addon_details = self.addon_details(addon) addon_id = addon_details.get('id') assert addon_id, 'The addon id could not be found: %s' % addon # if the add-on has to be unpacked force it now # note: we might want to let Firefox do it in case of addon details orig_path = None if os.path.isfile(addon) and (unpack or addon_details['unpack']): orig_path = addon addon = tempfile.mkdtemp() mozfile.extract(orig_path, addon) # copy the addon to the profile extensions_path = os.path.join(self.profile, 'extensions', 'staged') addon_path = os.path.join(extensions_path, addon_id) if os.path.isfile(addon): addon_path += '.xpi' # move existing xpi file to backup location to restore later if os.path.exists(addon_path): self.backup_dir = self.backup_dir or tempfile.mkdtemp() shutil.move(addon_path, self.backup_dir) # copy new add-on to the extension folder if not os.path.exists(extensions_path): os.makedirs(extensions_path) shutil.copy(addon, addon_path) else: # move existing folder to backup location to restore later if os.path.exists(addon_path): self.backup_dir = self.backup_dir or tempfile.mkdtemp() shutil.move(addon_path, self.backup_dir) # copy new add-on to the extension folder shutil.copytree(addon, addon_path, symlinks=True) # if we had to extract the addon, remove the temporary directory if orig_path: mozfile.rmtree(addon) addon = orig_path self._addons.append(addon_id) self.installed_addons.append(addon)
def remove_tempdir(self): if self.tempdir: rmtree(self.tempdir) self.tempdir = None
def install_from_path(self, path, unpack=False): """ Installs addon from a filepath, url or directory of addons in the profile. :param path: url, path to .xpi, or directory of addons :param unpack: whether to unpack unless specified otherwise in the install.rdf """ # if the addon is a URL, download it # note that this won't work with protocols urllib2 doesn't support if mozfile.is_url(path): path = self.download(path) self.downloaded_addons.append(path) addons = [path] # if path is not an add-on, try to install all contained add-ons if not self.is_addon(path): # If the path doesn't exist, then we don't really care, just return if not os.path.isdir(path): return addons = [ os.path.join(path, x) for x in os.listdir(path) if self.is_addon(os.path.join(path, x)) ] addons.sort() # install each addon for addon in addons: # determine the addon id addon_details = self.addon_details(addon) addon_id = addon_details.get('id') assert addon_id, 'The addon id could not be found: %s' % addon # if the add-on has to be unpacked force it now # note: we might want to let Firefox do it in case of addon details orig_path = None if os.path.isfile(addon) and (unpack or addon_details['unpack']): orig_path = addon addon = tempfile.mkdtemp() mozfile.extract(orig_path, addon) # copy the addon to the profile extensions_path = os.path.join(self.profile, 'extensions', 'staged') addon_path = os.path.join(extensions_path, addon_id) if os.path.isfile(addon): addon_path += '.xpi' # move existing xpi file to backup location to restore later if os.path.exists(addon_path): self.backup_dir = self.backup_dir or tempfile.mkdtemp() shutil.move(addon_path, self.backup_dir) # copy new add-on to the extension folder if not os.path.exists(extensions_path): os.makedirs(extensions_path) shutil.copy(addon, addon_path) else: # move existing folder to backup location to restore later if os.path.exists(addon_path): self.backup_dir = self.backup_dir or tempfile.mkdtemp() shutil.move(addon_path, self.backup_dir) # copy new add-on to the extension folder shutil.copytree(addon, addon_path, symlinks=True) # if we had to extract the addon, remove the temporary directory if orig_path: mozfile.rmtree(addon) addon = orig_path self._addons.append(addon_id) self.installed_addons.append(addon)
def cleanup(self): rmtree('moznightlyapp') if self.lastdest: os.remove(self.lastdest)
def install(self): rmtree("moznightlyapp") subprocess._cleanup = lambda : None # mikeal's fix for subprocess threading bug MozInstaller(src=self.dest, dest="moznightlyapp", dest_app="Mozilla.app") return True
def tearDown(self): mozfile.rmtree(self.tmpdir)
def clobber(self): self.remove_objdir() outdir = os.path.join(self.b2g_home, 'out') if os.path.isdir(outdir): mozfile.rmtree(outdir) return 0