Best Python code snippet using avocado_python
test_plugin_vmimage.py
Source:test_plugin_vmimage.py  
...56      <a href="0.4.0/">0.4.0/</a>                                             2017-11-19 20:01    -57<hr></pre>58</body></html>"""59class VMImagePlugin(unittest.TestCase):60    def _get_temporary_dirs_mapping_and_config(self):61        """62        Creates a temporary bogus base data dir63        And returns a dictionary containing the temporary data dir paths and64        the path to a configuration file contain those same settings65        """66        prefix = temp_dir_prefix(__name__, self, 'setUp')67        base_dir = tempfile.TemporaryDirectory(prefix=prefix)68        data_directory = os.path.join(base_dir.name, 'data')69        os.mkdir(data_directory)70        os.mkdir(os.path.join(data_directory, 'cache'))71        mapping = {'base_dir': base_dir.name,72                   'data_dir': data_directory}73        temp_settings = ('[datadir.paths]\n'74                         'base_dir = %(base_dir)s\n'75                         'data_dir = %(data_dir)s\n') % mapping76        config_file = tempfile.NamedTemporaryFile('w', delete=False)77        config_file.write(temp_settings)78        config_file.close()79        return base_dir, mapping, config_file.name80    @unittest.mock.patch('avocado.utils.vmimage.urlopen')81    def _create_test_files(self, urlopen_mock):82        with unittest.mock.patch('avocado.core.data_dir.settings', self.stg):83            expected_images = [{'name': 'Fedora', 'file': 'Fedora-Cloud-Base-{version}-{build}.{arch}.qcow2',84                                'url': FEDORA_PAGE},85                               {'name': 'JeOS', 'file': 'jeos-{version}-{arch}.qcow2.xz', 'url': JEOS_PAGE},86                               {'name': 'CirrOS', 'file': 'cirros-{version}-{arch}-disk.img', 'url': CIRROS_PAGE}87                               ]88            cache_dir = data_dir.get_cache_dirs()[0]89            providers = [provider() for provider in vmimage_util.list_providers()]90            for provider in providers:91                for image in expected_images:92                    if image['name'] == provider.name:93                        urlread_mocked = unittest.mock.Mock(return_value=image["url"])94                        urlopen_mock.return_value = unittest.mock.Mock(read=urlread_mocked)95                        image['type'] = "vmimage"96                        image['version'] = provider.version97                        image['arch'] = provider.arch98                        image['build'] = "1234"99                        image['file'] = os.path.join(cache_dir, image['file'].format(100                            version=image['version'],101                            build=image['build'],102                            arch=image['arch']))103                        open(image["file"], "w").close()104                        create_metadata_file(image['file'], image)105            return sorted(expected_images, key=lambda i: i['name'])106    def setUp(self):107        (self.base_dir, self.mapping,108         self.config_file_path) = self._get_temporary_dirs_mapping_and_config()109        self.stg = Settings()110        with unittest.mock.patch('avocado.core.stgs', self.stg):111            import avocado.core112            avocado.core.register_core_options()113        self.stg.process_config_path(self.config_file_path)114        self.stg.merge_with_configs()115        self.expected_images = self._create_test_files()116    def test_list_downloaded_images(self):117        with unittest.mock.patch('avocado.core.data_dir.settings', self.stg):118            with unittest.mock.patch('avocado.utils.vmimage.ImageProviderBase.get_version'):119                images = sorted(vmimage_plugin.list_downloaded_images(), key=lambda i: i['name'])120                for index, image in enumerate(images):121                    for key in image:122                        self.assertEqual(self.expected_images[index][key], image[key],...test_datadir.py
Source:test_datadir.py  
...5from flexmock import flexmock6from avocado.core import settings7class DataDirTest(unittest.TestCase):8    @staticmethod9    def _get_temporary_dirs_mapping_and_config():10        """11        Creates a temporary bogus base data dir12        And returns a dictionary containing the temporary data dir paths and13        a the path to a configuration file contain those same settings14        """15        base_dir = tempfile.mkdtemp(prefix='avocado_' + __name__)16        mapping = {'base_dir': base_dir,17                   'test_dir': os.path.join(base_dir, 'tests'),18                   'data_dir': os.path.join(base_dir, 'data'),19                   'logs_dir': os.path.join(base_dir, 'logs')}20        temp_settings = ('[datadir.paths]\n'21                         'base_dir = %(base_dir)s\n'22                         'test_dir = %(test_dir)s\n'23                         'data_dir = %(data_dir)s\n'24                         'logs_dir = %(logs_dir)s\n') % mapping25        config_file = tempfile.NamedTemporaryFile(delete=False)26        config_file.write(temp_settings)27        config_file.close()28        return (mapping, config_file.name)29    def setUp(self):30        (self.mapping,31         self.config_file_path) = self._get_temporary_dirs_mapping_and_config()32    def testDataDirFromConfig(self):33        """34        When avocado.conf is present, honor the values coming from it.35        """36        stg_orig = settings.settings37        stg = settings.Settings(self.config_file_path)38        try:39            # Trick the module to think we're on a system wide install40            stg.intree = False41            flexmock(settings, settings=stg)42            from avocado.core import data_dir43            flexmock(data_dir.settings, settings=stg)44            self.assertFalse(data_dir.settings.settings.intree)45            for key in self.mapping.keys():46                data_dir_func = getattr(data_dir, 'get_%s' % key)47                self.assertEqual(data_dir_func(), stg.get_value('datadir.paths', key))48        finally:49            flexmock(settings, settings=stg_orig)50        del data_dir51    #def testUniqueLogDir(self):52    #    """53    #    Tests that multiple queries for a logdir at the same time provides54    #    unique results.55    #    """56    #    from avocado.core import data_dir57    #    flexmock(data_dir.time).should_receive('strftime').and_return("date")58    #    logdir = os.path.join(self.mapping['base_dir'], "foor", "bar", "baz")59    #    path_prefix = os.path.join(logdir, "job-date-")60    #    uid = "1234567890"*461    #    for i in xrange(7, 40):62    #        path = data_dir.create_job_logs_dir(logdir, uid)63    #        self.assertEqual(path, path_prefix + uid[:i])64    #        self.assertTrue(os.path.exists(path))65    #    path = data_dir.create_job_logs_dir(logdir, uid)66    #    self.assertEqual(path, path_prefix + uid + ".0")67    #    self.assertTrue(os.path.exists(path))68    #    path = data_dir.create_job_logs_dir(logdir, uid)69    #    self.assertEqual(path, path_prefix + uid + ".1")70    #    self.assertTrue(os.path.exists(path))71    def testSettingsDirAlternateDynamic(self):72        """73        Tests that changes to the data_dir settings are applied dynamically74        To guarantee that, first the data_dir module is loaded. Then a new,75        alternate set of data directories are created and set in the76        "canonical" settings location, that is, avocado.core.settings.settings.77        No data_dir module reload should be necessary to get the new locations78        from data_dir APIs.79        """80        stg_orig = settings.settings81        from avocado.core import data_dir82        (self.alt_mapping,83         self.alt_config_file_path) = self._get_temporary_dirs_mapping_and_config()84        stg = settings.Settings(self.alt_config_file_path)85        flexmock(settings, settings=stg)86        for key in self.alt_mapping.keys():87            data_dir_func = getattr(data_dir, 'get_%s' % key)88            self.assertEqual(data_dir_func(), self.alt_mapping[key])89        flexmock(settings, settings=stg_orig)90        del data_dir91    def tearDown(self):92        os.unlink(self.config_file_path)93        shutil.rmtree(self.mapping['base_dir'])94        # clean up alternate configuration file if set by the test95        if hasattr(self, 'alt_config_file_path'):96            os.unlink(self.alt_config_file_path)97        if hasattr(self, 'alt_mapping'):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
