Best Python code snippet using tempest_python
test_0045_migration.py
Source:test_0045_migration.py  
1import pytest2from django.core.management import call_command3from metarecord.models import Action, Function, Phase, Record4from metarecord.models.bulk_update import BulkUpdate5def _prepare_structural_element(obj, cls, user, user_2):6    obj.created_by = user7    obj.modified_by = user_28    obj.save(update_fields=['created_by', 'modified_by'])9    cls.objects.filter(pk=obj.pk).update(_created_by='', _modified_by='')10@pytest.mark.django_db11def test_function_migration(function, user, user_2):12    _prepare_structural_element(function, Function, user, user_2)13    function.refresh_from_db()14    assert function._created_by == ''15    assert function._modified_by == ''16    try:17        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)18        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)19    except KeyError:20        pytest.skip()21    function.refresh_from_db()22    assert function._created_by == 'John Rambo'23    assert function._modified_by == 'Rocky Balboa'24@pytest.mark.django_db25def test_phase_migration(phase, user, user_2):26    _prepare_structural_element(phase, Phase, user, user_2)27    phase.refresh_from_db()28    assert phase._created_by == ''29    assert phase._modified_by == ''30    try:31        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)32        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)33    except KeyError:34        pytest.skip()35    phase.refresh_from_db()36    assert phase._created_by == 'John Rambo'37    assert phase._modified_by == 'Rocky Balboa'38@pytest.mark.django_db39def test_action_migration(action, user, user_2):40    _prepare_structural_element(action, Action, user, user_2)41    action.refresh_from_db()42    assert action._created_by == ''43    assert action._modified_by == ''44    try:45        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)46        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)47    except KeyError:48        pytest.skip()49    action.refresh_from_db()50    assert action._created_by == 'John Rambo'51    assert action._modified_by == 'Rocky Balboa'52@pytest.mark.django_db53def test_record_migration(record, user, user_2):54    _prepare_structural_element(record, Record, user, user_2)55    record.refresh_from_db()56    assert record._created_by == ''57    assert record._modified_by == ''58    try:59        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)60        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)61    except KeyError:62        pytest.skip()63    record.refresh_from_db()64    assert record._created_by == 'John Rambo'65    assert record._modified_by == 'Rocky Balboa'66@pytest.mark.django_db67def test_bulk_update_migration(bulk_update, user, user_2, super_user):68    BulkUpdate.objects.filter(pk=bulk_update.pk).update(69        approved_by=super_user,70        created_by=user,71        modified_by=user_2,72    )73    bulk_update.refresh_from_db()74    assert bulk_update._approved_by == ''75    assert bulk_update._created_by == ''76    assert bulk_update._modified_by == ''77    try:78        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)79        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)80    except KeyError:81        pytest.skip()82    bulk_update.refresh_from_db()83    assert bulk_update._approved_by == 'Kurt Sloane'84    assert bulk_update._created_by == 'John Rambo'85    assert bulk_update._modified_by == 'Rocky Balboa'86@pytest.mark.django_db87def test_metadata_version_migration(function, user):88    _prepare_structural_element(function, Function, user, user)89    function.refresh_from_db()90    function.create_metadata_version()91    function.metadata_versions.update(_modified_by='')92    metadata_version = function.metadata_versions.first()93    assert metadata_version._modified_by == ''94    try:95        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)96        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)97    except KeyError:98        pytest.skip()99    metadata_version.refresh_from_db()100    assert metadata_version._modified_by == 'John Rambo'101@pytest.mark.django_db102def test_migration_without_user(function):103    assert function.created_by == None104    assert function._created_by == ''105    try:106        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)107        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)108    except KeyError:109        pytest.skip()110    function.refresh_from_db()111    assert function._created_by == ''112@pytest.mark.django_db113def test_migration_without_first_name(function, user, user_2):114    user.first_name = ''115    user.save(update_fields=['first_name'])116    _prepare_structural_element(function, Function, user, user_2)117    function.refresh_from_db()118    assert function._created_by == ''119    assert function.created_by.get_full_name() == 'Rambo'120    try:121        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)122        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)123    except KeyError:124        pytest.skip()125    function.refresh_from_db()126    assert function._created_by == 'Rambo'127@pytest.mark.django_db128def test_migration_without_last_name(function, user, user_2):129    user.last_name = ''130    user.save(update_fields=['last_name'])131    _prepare_structural_element(function, Function, user, user_2)132    function.refresh_from_db()133    assert function._created_by == ''134    assert function.created_by.get_full_name() == 'John'135    try:136        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)137        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)138    except KeyError:139        pytest.skip()140    function.refresh_from_db()141    assert function._created_by == 'John'142@pytest.mark.django_db143def test_migration_wouthout_names(function, user, user_2):144    user.first_name = ''145    user.last_name = ''146    user.save(update_fields=['first_name', 'last_name'])147    _prepare_structural_element(function, Function, user, user_2)148    function.refresh_from_db()149    assert function._created_by == ''150    assert function.created_by.get_full_name() == ''151    try:152        call_command('migrate', app_label='metarecord', migration_name='0044', skip_checks=True, fake=True)153        call_command('migrate', app_label='metarecord', migration_name='0045', skip_checks=True)154    except KeyError:155        pytest.skip()156    function.refresh_from_db()...util.py
Source:util.py  
1# Copyright 2022 DeepL SE (https://www.deepl.com)2# Use of this source code is governed by an MIT3# license that can be found in the LICENSE file.4import itertools5import logging6from typing import Dict, Optional7logger = logging.getLogger("deepl")8def _get_log_text(message, **kwargs):9    return (10        message11        + " "12        + " ".join(f"{key}={value}" for key, value in sorted(kwargs.items()))13    )14def log_debug(message, **kwargs):15    text = _get_log_text(message, **kwargs)16    logger.debug(text)17def log_info(message, **kwargs):18    text = _get_log_text(message, **kwargs)19    logger.info(text)20def get_int_safe(d: dict, key: str) -> Optional[int]:21    """Returns value in dictionary with given key as int, or None."""22    try:23        return int(d.get(key))24    except (TypeError, ValueError):25        return None26def auth_key_is_free_account(auth_key: str) -> bool:27    """Returns True if the given authentication key belongs to a DeepL API Free28    account, otherwise False."""29    return auth_key.endswith(":fx")30def validate_glossary_term(term: str) -> None:31    """Checks if the given glossary term contains any disallowed characters.32    :param term: Glossary term to check for validity.33    :raises ValueError: If the term is not valid or a disallowed character is34    found."""35    if len(term) == 0:36        raise ValueError(f'Term "{term}" is not a valid string')37    if any(38        (39            0 <= ord(char) <= 31  # C0 control characters40            or 128 <= ord(char) <= 159  # C1 control characters41            or char in "\u2028\u2029"  # Unicode newlines42        )43        for char in term44    ):45        raise ValueError(f'Term "{term}" contains invalid character')46def convert_tsv_to_dict(47    tsv: str, term_separator: str = "\t", skip_checks: bool = False48) -> dict:49    """Converts the given tab-separated values (TSV) string to an entries50    dictionary for use in a glossary. Each line should contain a source and51    target term separated by a tab. Empty lines are ignored.52    :param tsv: string containing TSV to parse.53    :param term_separator: optional term separator to use.54    :param skip_checks: set to True to override entry validation.55    :return: dictionary containing parsed entries.56    """57    entries_dict = {}58    for line, index in zip(tsv.splitlines(), itertools.count(1)):59        if not line:60            continue61        if term_separator not in line:62            raise ValueError(63                f"Entry {index} does not contain separator: {line}"64            )65        source, target = line.split(term_separator, 1)66        source, target = source.strip(), target.strip()67        if source in entries_dict:68            raise ValueError(69                f'Entry {index} duplicates source term "{source}"'70            )71        if term_separator in target:72            raise ValueError(73                f"Entry {index} contains more than one term separator: {line}"74            )75        if not skip_checks:76            validate_glossary_term(source)77            validate_glossary_term(target)78        entries_dict[source] = target79    return entries_dict80def convert_dict_to_tsv(81    entry_dict: Dict[str, str], skip_checks: bool = False82) -> str:83    """Converts the given glossary entries dictionary to a tab-separated values84    (TSV) string.85    :param entry_dict: dictionary containing glossary entries.86    :param skip_checks: set to True to override entry validation.87    :return: string containing entries in TSV format.88    """89    if not skip_checks:90        for source, target in entry_dict.items():91            validate_glossary_term(source.strip())92            validate_glossary_term(target.strip())93    return "\n".join(94        f"{s.strip()}\t{t.strip()}" for s, t in entry_dict.items()...runner_filter.py
Source:runner_filter.py  
1import logging2import fnmatch3from typing import Set, Optional, Union, List4from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR5class RunnerFilter(object):6    # NOTE: This needs to be static because different filters may be used at load time versus runtime7    #       (see note in BaseCheckRegistery.register). The concept of which checks are external is8    #       logically a "static" concept anyway, so this makes logical sense.9    __EXTERNAL_CHECK_IDS: Set[str] = set()10    def __init__(11        self,12        framework: str = "all",13        checks: Union[str, List[str], None] = None,14        skip_checks: Union[str, List[str], None] = None,15        download_external_modules: bool = False,16        external_modules_download_path: str = DEFAULT_EXTERNAL_MODULES_DIR,17        evaluate_variables: bool = True,18        runners: Optional[List[str]] = None,19        skip_framework: Optional[str] = None,20        excluded_directories: Optional[List[str]] = None21    ) -> None:22        if checks is None:23            checks = []24        if isinstance(checks, str):25            self.checks = checks.split(",")26        elif isinstance(checks, list) and len(checks) == 1:27            self.checks = checks[0].split(",")28        else:29            self.checks = checks30        if skip_checks is None:31            skip_checks = []32        if isinstance(skip_checks, str):33            self.skip_checks = skip_checks.split(",")34        elif isinstance(skip_checks, list) and len(skip_checks) == 1:35            self.skip_checks = skip_checks[0].split(",")36        else:37            self.skip_checks = skip_checks38        if skip_framework is None:39            self.framework = framework40        else:41            if isinstance(skip_framework, str):42                if framework == "all":43                    if runners is None:44                        runners = []45                    selected_frameworks = list(set(runners) - set(skip_framework.split(",")))46                    self.framework = ",".join(selected_frameworks)47                else:48                    selected_frameworks = list(set(framework.split(",")) - set(skip_framework.split(",")))49                    self.framework = ",".join(selected_frameworks)50        logging.info(f"Resultant set of frameworks (removing skipped frameworks): {self.framework}")51        self.download_external_modules = download_external_modules52        self.external_modules_download_path = external_modules_download_path53        self.evaluate_variables = evaluate_variables54        self.excluded_paths = excluded_directories55    def should_run_check(self, check_id: str) -> bool:56        if RunnerFilter.is_external_check(check_id):57            pass  # enabled unless skipped58        elif self.checks:59            if check_id in self.checks:60                return True61            else:62                return False63        if self.skip_checks and any(fnmatch.fnmatch(check_id, pattern) for pattern in self.skip_checks):64            return False65        return True66    @staticmethod67    def notify_external_check(check_id: str) -> None:68        RunnerFilter.__EXTERNAL_CHECK_IDS.add(check_id)69    @staticmethod70    def is_external_check(check_id: str) -> bool:...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!!
