Best Python code snippet using prospector_python
test_profile.py
Source:test_profile.py  
...179        """Set up the default loader."""180        self.maxDiff = None181        self._loader = ProfileLoader()182        self._loader.load_profiles(PROFILE_DIR)183    def _load_profile(self, content):184        """Load a profile configuration with the given content."""185        with tempfile.NamedTemporaryFile("w") as f:186            f.write(content)187            f.flush()188            self._loader.load_profile(f.name)189            return f.name190    def _check_profile(self, profile_id, file_paths):191        """Check a profile."""192        assert self._loader.check_profile(profile_id)193        assert self._loader.collect_configurations(profile_id) == file_paths194    def _check_detection(self, profile_id, os_id, variant_id):195        """Check the profile detection."""196        assert self._loader.detect_profile(os_id, variant_id) == profile_id197    def _check_partitioning(self, config, partitioning):198        with patch("pyanaconda.modules.storage.partitioning.automatic.utils.platform") as platform:199            platform.partitions = []200            with patch("pyanaconda.modules.storage.partitioning.automatic.utils.conf", new=config):201                default = get_default_partitioning()202                print("Default: " + repr(default))203                print("Supplied: " + repr(partitioning))204                assert default == partitioning205    def _check_default_profile(self, profile_id, os_release_values, file_names, partitioning):206        """Check a default profile."""207        paths = [os.path.join(PROFILE_DIR, path) for path in file_names]208        self._check_profile(profile_id, paths)209        config = AnacondaConfiguration.from_defaults()210        paths = self._loader.collect_configurations(profile_id)211        for path in paths:212            config.read(path)213        config.validate()214        self._check_detection(profile_id, *os_release_values)215        self._check_partitioning(config, partitioning)216        assert "{}.conf".format(profile_id) == file_names[-1]217    def _get_config(self, profile_id):218        """Get parsed config file."""219        config = AnacondaConfiguration.from_defaults()220        paths = self._loader.collect_configurations(profile_id)221        for path in paths:222            config.read(path)223        config.validate()224        return config225    def test_fedora_profiles(self):226        self._check_default_profile(227            "fedora",228            ("fedora", ""),229            ["fedora.conf"],230            WORKSTATION_PARTITIONING231        )232        self._check_default_profile(233            "fedora-server",234            ("fedora", "server"),235            ["fedora.conf", "fedora-server.conf"],236            SERVER_PARTITIONING237        )238        self._check_default_profile(239            "fedora-workstation",240            ("fedora", "workstation"),241            ["fedora.conf", "fedora-workstation.conf"],242            WORKSTATION_PARTITIONING243        )244        self._check_default_profile(245            "fedora-silverblue",246            ("fedora", "silverblue"),247            ["fedora.conf", "fedora-workstation.conf", "fedora-silverblue.conf"],248            WORKSTATIONPLUS_PARTITIONING249        )250        self._check_default_profile(251            "fedora-kde",252            ("fedora", "kde"),253            ["fedora.conf", "fedora-kde.conf"],254            WORKSTATION_PARTITIONING255        )256        self._check_default_profile(257            "fedora-kinoite",258            ("fedora", "kinoite"),259            ["fedora.conf", "fedora-kde.conf", "fedora-kinoite.conf"],260            WORKSTATIONPLUS_PARTITIONING261        )262        self._check_default_profile(263            "fedora-iot",264            ("fedora", "iot"),265            ["fedora.conf", "fedora-iot.conf"],266            WORKSTATION_PARTITIONING267        )268        self._check_default_profile(269            "fedora-eln",270            ("fedora", "eln"),271            ["rhel.conf", "fedora-eln.conf"],272            ENTERPRISE_PARTITIONING273        )274    def test_rhel_profiles(self):275        self._check_default_profile(276            "rhel",277            ("rhel", ""),278            ["rhel.conf"],279            ENTERPRISE_PARTITIONING280        )281        self._check_default_profile(282            "centos",283            ("centos", ""),284            ["rhel.conf", "centos.conf"],285            ENTERPRISE_PARTITIONING286        )287        self._check_default_profile(288            "rhvh",289            ("rhel", "ovirt-node"),290            ["rhel.conf", "rhvh.conf"],291            VIRTUALIZATION_PARTITIONING292        )293        self._check_default_profile(294            "ovirt",295            ("centos", "ovirt-node"),296            ["rhel.conf", "centos.conf", "ovirt.conf"],297            VIRTUALIZATION_PARTITIONING298        )299        self._check_default_profile(300            "scientific-linux",301            ("scientific", ""),302            ["rhel.conf", "scientific-linux.conf"],303            ENTERPRISE_PARTITIONING304        )305        self._check_default_profile(306            "almalinux",307            ("almalinux", ""),308            ["rhel.conf", "almalinux.conf"],309            ENTERPRISE_PARTITIONING310        )311        self._check_default_profile(312            "rocky",313            ("rocky", ""),314            ["rhel.conf", "rocky.conf"],315            ENTERPRISE_PARTITIONING316        )317        self._check_default_profile(318            "virtuozzo-linux",319            ("virtuozzo", ""),320            ["rhel.conf", "virtuozzo-linux.conf"],321            ENTERPRISE_PARTITIONING322        )323        self._check_default_profile(324            "circle",325            ("circle", ""),326            ["rhel.conf", "circle.conf"],327            ENTERPRISE_PARTITIONING328        )329    def _compare_profile_files(self, file_name, other_file_name, ignored_sections=()):330        parser = create_parser()331        read_config(parser, os.path.join(PROFILE_DIR, file_name))332        other_parser = create_parser()333        read_config(other_parser, os.path.join(PROFILE_DIR, other_file_name))334        # Ignore the specified and profile-related sections.335        ignored_sections += ("Profile", "Profile Detection")336        sections = set(parser.sections()).difference(ignored_sections)337        other_sections = set(other_parser.sections()).difference(ignored_sections)338        # Otherwise, the defined sections should be the same.339        assert sections == other_sections340        for section in sections:341            # The defined options should be the same.342            assert parser.options(section) == other_parser.options(section)343            for key in parser.options(section):344                # The values of the options should be the same.345                assert parser.get(section, key) == other_parser.get(section, key)346    def test_ovirt_and_rhvh(self):347        """Test the similarity of oVirt Node Next with Red Hat Virtualization Host."""348        self._compare_profile_files("rhvh.conf", "ovirt.conf", ignored_sections=("License", ))349    def test_valid_profile(self):350        content = dedent("""351        [Profile]352        profile_id = custom-profile353        """)354        base_path = self._load_profile(content)355        self._check_profile("custom-profile", [base_path])356        content = dedent("""357        [Profile]358        profile_id = another-profile359        base_profile = custom-profile360        """)361        path = self._load_profile(content)362        self._check_profile("another-profile", [base_path, path])363    def test_profile_detection(self):364        content = dedent("""365        [Profile]366        profile_id = undetectable-profile367        """)368        self._load_profile(content)369        content = dedent("""370        [Profile]371        profile_id = custom-profile372        [Profile Detection]373        os_id = custom-os374        """)375        self._load_profile(content)376        content = dedent("""377        [Profile]378        profile_id = another-profile379        base_profile = custom-profile380        [Profile Detection]381        os_id = custom-os382        variant_id = custom-variant383        """)384        self._load_profile(content)385        self._check_detection(None, None, None)386        self._check_detection(None, "", "")387        self._check_detection(None, "", "another-variant")388        self._check_detection(None, "", "custom-variant")389        self._check_detection(None, "another-os", "custom-variant")390        self._check_detection("custom-profile", "custom-os", "")391        self._check_detection("custom-profile", "custom-os", None)392        self._check_detection("custom-profile", "custom-os", "another-variant")393        self._check_detection("another-profile", "custom-os", "custom-variant")394    def test_invalid_profile(self):395        with pytest.raises(ConfigurationError):396            self._load_profile("")397        with pytest.raises(ConfigurationError):398            self._load_profile("[Profile]")399        with pytest.raises(ConfigurationError):400            self._load_profile("[Profile Detection]")401        content = dedent("""402        [Profile]403        base_profile = custom-profile404        """)405        with pytest.raises(ConfigurationError):406            self._load_profile(content)407    def test_invalid_base_profile(self):408        content = dedent("""409        [Profile]410        profile_id = custom-profile411        base_profile = nonexistent-profile412        """)413        self._load_profile(content)414        with pytest.raises(ConfigurationError):415            self._loader.collect_configurations("custom-profile")416        assert not self._loader.check_profile("custom-profile")417    def test_repeated_base_profile(self):418        content = dedent("""419        [Profile]420        profile_id = custom-profile421        base_profile = custom-profile422        """)423        self._load_profile(content)424        with pytest.raises(ConfigurationError):425            self._loader.collect_configurations("custom-profile")426        assert not self._loader.check_profile("custom-profile")427    def test_existing_profile(self):428        content = dedent("""429        [Profile]430        profile_id = custom-profile431        """)432        self._load_profile(content)433        with pytest.raises(ConfigurationError):434            self._load_profile(content)435    def test_find_nonexistent_profile(self):436        assert self._loader.check_profile("custom-profile") is False437        assert self._loader.detect_profile("custom-os", "custom-variant") == None438    def test_ignore_invalid_profile(self):439        with tempfile.TemporaryDirectory() as config_dir:440            # A correct profile config.441            with open(os.path.join(config_dir, "1.conf"), "w") as f:442                f.write(dedent("""443                [Profile]444                profile_id = custom-profile-1445                """))446            # An invalid profile config.447            with open(os.path.join(config_dir, "2.conf"), "w") as f:448                f.write("")...profile_test.py
Source:profile_test.py  
...9    def test_profile_settings_update(self):10        prof = '''[settings]11os=Windows12'''13        new_profile, _ = _load_profile(prof, None, None)14        new_profile.update_settings(OrderedDict([("OTHER", "2")]))15        self.assertEqual(new_profile.settings, OrderedDict([("os", "Windows"), ("OTHER", "2")]))16        new_profile.update_settings(OrderedDict([("compiler", "2"), ("compiler.version", "3")]))17        self.assertEqual(new_profile.settings,18                         OrderedDict([("os", "Windows"), ("OTHER", "2"),19                                      ("compiler", "2"), ("compiler.version", "3")]))20    def test_env_vars_inheritance(self):21        tmp_dir = temp_folder()22        p1 = '''[env]\nVAR=1'''23        p2 = '''include(p1)\n[env]\nVAR=2'''24        save(os.path.join(tmp_dir, "p1"), p1)25        new_profile, _ = _load_profile(p2, tmp_dir, tmp_dir)26        self.assertEqual(new_profile.env_values.data[None]["VAR"], "2")27    def test_profile_subsettings_update(self):28        prof = '''[settings]29os=Windows30compiler=Visual Studio31compiler.runtime=MT32'''33        new_profile, _ = _load_profile(prof, None, None)34        new_profile.update_settings(OrderedDict([("compiler", "gcc")]))35        self.assertEqual(dict(new_profile.settings), {"compiler": "gcc", "os": "Windows"})36        new_profile, _ = _load_profile(prof, None, None)37        new_profile.update_settings(OrderedDict([("compiler", "Visual Studio"),38                                                 ("compiler.subsetting", "3"),39                                                 ("other", "value")]))40        self.assertEqual(dict(new_profile.settings), {"compiler": "Visual Studio",41                                                      "os": "Windows",42                                                      "compiler.runtime": "MT",43                                                      "compiler.subsetting": "3",44                                                      "other": "value"})45    def test_package_settings_update(self):46        prof = '''[settings]47MyPackage:os=Windows48    # In the previous line there are some spaces49'''50        np, _ = _load_profile(prof, None, None)51        np.update_package_settings({"MyPackage": [("OTHER", "2")]})52        self.assertEqual(np.package_settings_values,53                         {"MyPackage": [("os", "Windows"), ("OTHER", "2")]})54        np._package_settings_values = None  # invalidate caching55        np.update_package_settings({"MyPackage": [("compiler", "2"), ("compiler.version", "3")]})56        self.assertEqual(np.package_settings_values,57                         {"MyPackage": [("os", "Windows"), ("OTHER", "2"),58                                        ("compiler", "2"), ("compiler.version", "3")]})59    def test_profile_dump_order(self):60        # Settings61        profile = Profile()62        profile.package_settings["zlib"] = {"compiler": "gcc"}63        profile.settings["arch"] = "x86_64"64        profile.settings["compiler"] = "Visual Studio"...loader.py
Source:loader.py  
...36		else:37			log.info("loading profile: %s" % profile_names[0])38		profiles = []39		processed_files = []40		self._load_profile(profile_names, profiles, processed_files)41		if len(profiles) > 1:42			final_profile = self._profile_merger.merge(profiles)43		else:44			final_profile = profiles[0]45		final_profile.name = " ".join(profile_names)46		return final_profile47	def _load_profile(self, profile_names, profiles, processed_files):48		for name in profile_names:49			filename = self._profile_locator.get_config(name, processed_files)50			if filename is None:51				raise InvalidProfileException("Cannot find profile '%s' in '%s'." % (name, list(reversed(self._profile_locator._load_directories))))52			processed_files.append(filename)53			config = self._load_config_data(filename)54			profile = self._profile_factory.create(name, config)55			if "include" in profile.options:56				include_name = profile.options.pop("include")57				self._load_profile([include_name], profiles, processed_files)58			profiles.append(profile)59	def _load_config_data(self, file_name):60		try:61			config_obj = ConfigObj(file_name, raise_errors = True, list_values = False, interpolation = False)62		except ConfigObjError as e:63			raise InvalidProfileException("Cannot parse '%s'." % file_name, e)64		config = collections.OrderedDict()65		for section in config_obj.keys():66			if section == "variables":67				self._variables.add_from_cfg(config_obj[section], os.path.dirname(file_name))68			else:69				config[section] = collections.OrderedDict()70				for option in config_obj[section].keys():71					config[section][option] = config_obj[section][option]...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!!
