Best Python code snippet using playwright-python
__init__.py
Source:__init__.py  
...217            assert_attributes_equal(218                resource.translations[translation_index],219                source_string="Empty Translation",220            )221    def assert_file_content(self, file_path, expected_content, strip=True):222        with open(file_path) as f:223            actual_content = f.read()224            # Strip leading and trailing whitespace by default as we225            # normally don't care about this.226            if strip:227                actual_content = actual_content.strip()228                expected_content = expected_content.strip()229            self.assertMultiLineEqual(actual_content, expected_content)230    # Save tests take in an input and expected string that contain the231    # state of the translation file before and after the change being232    # tested is made to the parsed resource and saved.233    def run_save_basic(234        self,235        input_string,236        expected_string,237        source_string=None,238        expected_translation=None,239    ):240        """241        Test saving changes to an entity with a single translation.242        """243        path, resource = self.parse_string(input_string, source_string=source_string)244        translation = resource.translations[0]245        translation.strings[None] = expected_translation or "New Translated String"246        translation.fuzzy = True247        resource.save(self.locale)248        self.assert_file_content(path, expected_string)249    def run_save_remove(250        self, input_string, expected_string, source_string=None, remove_cb=None251    ):252        """Test saving a removed entity with a single translation."""253        path, resource = self.parse_string(input_string, source_string=source_string)254        def default_remove(res):255            translation = res.translations[0]256            translation.strings = {}257        (remove_cb or default_remove)(resource)258        resource.save(self.locale)259        self.assert_file_content(path, expected_string)260    def run_save_plural(self, input_string, expected_string, source_string=None):261        path, resource = self.parse_string(input_string, source_string=source_string)262        translation = resource.translations[0]263        translation.strings[0] = "New Plural"264        translation.strings[1] = "New Plurals"265        resource.save(self.locale)266        self.assert_file_content(path, expected_string)267    def run_save_plural_remove(self, input_string, expected_string, source_string=None):268        """269        Any missing plurals should be set to an empty string in the270        pofile.271        """272        path, resource = self.parse_string(input_string, source_string=source_string)273        translation = resource.translations[0]274        translation.strings[0] = "New Plural"275        del translation.strings[1]276        resource.save(self.locale)277        self.assert_file_content(path, expected_string)278    def run_save_remove_fuzzy(self, input_string, expected_string, source_string=None):279        path, resource = self.parse_string(input_string, source_string=source_string)280        resource.translations[0].fuzzy = False281        resource.save(self.locale)282        self.assert_file_content(path, expected_string)283    # Save tests specifically for asymmetric formats.284    def run_save_translation_missing(285        self, source_string, input_string, expected_string, expected_translation=None286    ):287        """288        If the source resource has a string but the translated resource289        doesn't, the returned resource should have an empty translation290        that can be modified and saved.291        Source Example:292            String=Source String293            MissingString=Missing Source String294        Input Example:295            String=Translated String296        Expected Example:297            String=Translated String298            MissingString=Translated Missing String299        """300        path, resource = self.parse_string(input_string, source_string=source_string)301        missing_translation = match_attr(302            resource.translations, key=self.key("Missing String")303        )304        missing_translation.strings = {305            None: expected_translation or "Translated Missing String"306        }307        resource.save(self.locale)308        self.assert_file_content(path, expected_string)309    def run_save_translation_identical(310        self, source_string, input_string, expected_string, expected_translation=None311    ):312        """313        If the updated translation is identical to the source314        translation, keep it.315        Source Example:316            String=Source String317        Input Example:318            String=Translated String319        Expected Example:320            String=Source String321        """322        path, resource = self.parse_string(input_string, source_string=source_string)323        translation = match_attr(resource.translations, key="String")324        translation.strings = {None: expected_translation or "Source String"}325        resource.save(self.locale)326        self.assert_file_content(path, expected_string)327    def run_save_no_changes(self, input_string, expected_string, source_string=None):328        """Test what happens when no changes are made."""329        path, resource = self.parse_string(input_string, source_string=source_string)330        resource.save(self.locale)...test_features.py
Source:test_features.py  
...12    return docker.from_env()13img1 = helpers.creates_images(*"target2_bases target3_bases".split())14def test_multiple_bases(img1):15    run_docker_make("-f data/multibase.yml target2_bases target3_bases")16    helpers.assert_file_content("target2_bases", "/opt/success", "success2")17    helpers.assert_file_content("target3_bases", "/opt/success", "success3")18img2 = helpers.creates_images("target_include")19def test_paths_relative_interpreted_relative_to_definition_file(img2):20    run_docker_make("-f data/include.yml target_include")21    helpers.assert_file_content(22        "target_include",23        "/opt/testfile.txt",24        "this is a file used in tests for relative path resolution",25    )26_FILES = {27    "a": {"content": "a", "path": "/opt/a"},28    "b": {"content": "b", "path": "/opt/b"},29    "c": {"content": "c", "path": "/opt/c"},30    "d": {"content": "d", "path": "/opt/d/d"},31}32def _check_files(img, **present):33    for f, record in _FILES.items():34        if not present.get(f, True):35            with pytest.raises(AssertionError):36                helpers.assert_file_content(img, record["path"], record["content"])37        else:38            helpers.assert_file_content(img, record["path"], record["content"])39img3 = helpers.creates_images("target_ignore_string")40def test_ignore_string(img3):41    run_docker_make("-f data/ignores.yml target_ignore_string")42    _check_files("target_ignore_string", b=False)43img4 = helpers.creates_images("target_ignorefile")44def test_ignorefile(img4):45    run_docker_make("-f data/ignores.yml target_ignorefile")46    _check_files("target_ignorefile", c=False)47img5 = helpers.creates_images("target_regular_ignore")48def test_regular_ignore(img5):49    run_docker_make("-f data/ignores.yml target_regular_ignore")50    _check_files("target_regular_ignore", a=False, b=False)51img6 = helpers.creates_images("target_ignore_directory")52def test_ignore_directory(img6):53    run_docker_make("-f data/ignores.yml target_ignore_directory")54    _check_files("target_ignore_directory", d=False)55def test_dockerfile_write(tmpdir):56    tmpdir = str(tmpdir)57    run_docker_make("-f data/write.yml -p -n --dockerfile-dir %s writetarget" % tmpdir)58    assert os.path.isfile(os.path.join(tmpdir, "Dockerfile.writetarget"))59img7 = helpers.creates_images("simple-target")60@pytest.fixture(scope="function")61def twin_simple_targets(img7, docker_client):62    run_docker_make("-f data/simple.yml simple-target")63    image1 = docker_client.images.get("simple-target")64    run_docker_make("-f data/simple.yml simple-target --no-cache")65    image2 = docker_client.images.get("simple-target")66    return image1, image267def test_no_cache(twin_simple_targets):68    image1, image2 = twin_simple_targets69    assert image1.id != image2.id70clean8 = helpers.creates_images(71    "img1repo/simple-target:img1tag", "img2repo/simple-target:img2tag"72)73def test_explicit_cache_from(twin_simple_targets, docker_client, clean8):74    image1, image2 = twin_simple_targets75    image1.tag("img1repo/simple-target", tag="img1tag")76    image2.tag("img2repo/simple-target", tag="img2tag")77    run_docker_make(78        "-f data/simple.yml simple-target --cache-repo img1repo --cache-tag img1tag"79    )80    final_image = docker_client.images.get("simple-target")81    assert final_image.id == image1.id82def test_cache_fallback(twin_simple_targets, docker_client):83    image1, image2 = twin_simple_targets84    run_docker_make(85        "-f data/simple.yml simple-target" " --cache-repo fakerepo --cache-tag faketag"86    )87    final_image = docker_client.images.get("simple-target")88    assert final_image.id == image2.id89squashimgs = helpers.creates_images("visible-secret", "invisible-secret")90def test_squashed_secrets(experimental_daemon, squashimgs):91    run_docker_make("-f data/secret-squash.yml invisible-secret visible-secret")92    files_to_find = ["/opt/a", "/root/c", "/root/copy-c"]93    visfiles = helpers.find_files_in_layers("visible-secret", files_to_find)94    assert visfiles["/opt/a"]95    assert not visfiles["/root/c"]96    assert not visfiles["/root/copy-c"]97    invisfiles = helpers.find_files_in_layers("invisible-secret", files_to_find)98    assert invisfiles["/opt/a"]99    assert not invisfiles["/root/c"]100    assert invisfiles["/root/copy-c"]101def test_squashing_error_without_experimental_daemon(non_experimental_daemon):102    with pytest.raises(dockermake.errors.ExperimentalDaemonRequiredError):103        run_docker_make("-f data/secret-squash.yml invisible-secret visible-secret")104squashcache = helpers.creates_images("cache-test")105def test_cache_used_after_squash(experimental_daemon, squashcache):106    run_docker_make("-f data/secret-squash.yml cache-test")107    client = helpers.get_client()108    firstimg = client.images.get("cache-test")109    run_docker_make("-f data/secret-squash.yml cache-test")110    assert client.images.get("cache-test").id == firstimg.id111def test_handle_missing_squash_cache(experimental_daemon, squashcache):112    run_docker_make("-f data/secret-squash.yml cache-test invisible-secret")113    client = helpers.get_client()114    cachelayer = client.images.get("invisible-secret")115    firstimg = client.images.get("cache-test")116    for _id in ("cache-test", firstimg.id, "invisible_secret", cachelayer.id):117        try:118            client.images.remove(_id)119        except docker.errors.ImageNotFound:120            pass121    # Make sure the image can rebuild even if original layers are missing122    run_docker_make("-f data/secret-squash.yml cache-test")123    # Sanity check - makes sure that the first image was in fact removed and not used for cache124    assert client.images.get("cache-test").id != firstimg.id125hassecrets = helpers.creates_images("has-secrets")126def test_secret_files(experimental_daemon, hassecrets):127    run_docker_make("-f data/secret-squash.yml has-secrets")128    foundfiles = helpers.find_files_in_layers(129        "has-secrets",130        ["/root/secret1", "/root/secretdir/secretfile", "/root/copy-of-secret1"],131    )132    assert not foundfiles["/root/secret1"]133    assert not foundfiles["/root/secretdir/secretfile"]134    assert foundfiles["/root/copy-of-secret1"]135secretfail = helpers.creates_images("secretfail")136def test_build_fails_if_secrets_already_exist(experimental_daemon, secretfail):137    with pytest.raises(dockermake.errors.BuildError):138        run_docker_make("-f data/secret-squash.yml secretfail")139copy_with_secrets = helpers.creates_images("copy_with_secrets")140def test_error_if_copy_with_secrets(copy_with_secrets):141    with pytest.raises(dockermake.errors.ParsingFailure):142        run_docker_make("-f data/copy_with_secrets.yml copy_with_secrets")143twostep = helpers.creates_images(144    "target-twostep", "1.target-twostep.dmk", "2.target-twostep.dmk"145)146def test_keep_build_tags(twostep, docker_client):147    run_docker_make("-f data/twostep.yml target-twostep --keep-build-tags")148    assert docker_client.images.list("1.target-twostep.dmk")149    assert docker_client.images.list("2.target-twostep.dmk")150alltest = helpers.creates_images("t1", "t2", "t3", "t4")151def test_implicit_all(alltest):152    run_docker_make("-f data/implicit_all.yml --all")153    for s in "t1 t2 t3 t4".split():154        helpers.assert_file_content(s, "/opt/%s" % s, s)155def test_explicit_all(alltest):156    run_docker_make("-f data/explicit_all.yml --all")157    for s in "t1 t3".split():158        helpers.assert_file_content(s, "/opt/%s" % s, s)159    client = helpers.get_client()160    for s in "t2 t4".split():161        with pytest.raises(docker.errors.ImageNotFound):162            client.images.get(s)163buildargs = helpers.creates_images("target-buildargs")164def test_build_args(buildargs):165    run_docker_make(166        "-f data/build-args.yml --build-arg FILENAME=hello-world.txt target-buildargs"167    )168    helpers.assert_file_content("target-buildargs", "hello-world.txt", "hello world")169abstract_steps = helpers.creates_images("definite", "abstract")170def test_implicit_all_with_abstract_steps(abstract_steps):171    run_docker_make("-f data/abstract-steps.yml --all")172    client = helpers.get_client()173    client.images.get("definite")174    with pytest.raises(docker.errors.ImageNotFound):...test_smb_sync.py
Source:test_smb_sync.py  
...75    assert os.path.exists(os.path.join(TEST_FOLDER, 'dir2', 'file2.txt'))76    assert os.path.exists(os.path.join(TEST_FOLDER, 'dir3', 'file1.txt'))77    assert os.path.exists(os.path.join(TEST_FOLDER, 'dir3', 'file2.txt'))78    assert os.path.exists(os.path.join(TEST_FOLDER, 'dir3', 'file3.txt'))79def assert_file_content(filename, test_string):80    data = None81    with open(filename, 'r') as fp:82        data = fp.read()83    assert data.endswith(test_string)84def check_basic_sync(config, connection):85    syncer = create_smb_sync(config)86    create_remote_structure(connection)87    syncer.sync()88    assert_local_file_structure()89# ------- Pytest Test Methods ------- #90def test_sync_basic(config, connection):91    check_basic_sync(config, connection)92@pytest.mark.parametrize('conflict_handling, answer', [93    ('ask', 'y'),94    ('ask', 'n'),95    ('overwrite', None),96    ('keep', None),97    ('makeCopy', None),98])99def test_local_changes(config, connection, monkeypatch, conflict_handling, answer):100    TEST_STR_REMOTE = 'remote change'101    TEST_STR_LOCAL = 'local change'102    config['sync']['conflict-handling']['local-changes'] = conflict_handling103    check_basic_sync(config, connection)104    # change local file105    with open(os.path.join(TEST_FOLDER, 'dir1', 'file1.txt'), 'a') as fp:106        fp.write(TEST_STR_LOCAL)107    # nothing has changed on the remote yet, so nothing should change108    syncer = create_smb_sync(config)109    syncer.sync()110    assert_local_file_structure()111    # Change remote file112    for filename in generate_files(1, TEST_STR_REMOTE):113        with open(filename, 'rb') as file:114            path = os.path.join(TEST_FOLDER, 'dir1', filename)115            connection.storeFile(TEST_SHARE, path, file)116    if conflict_handling == 'ask':117        monkeypatch.setattr(builtins, 'input', lambda x: answer)118    syncer = create_smb_sync(config)119    syncer.sync()120    if conflict_handling == 'keep' or answer == 'n':121        expected_content = TEST_STR_LOCAL122    elif conflict_handling in ['overwrite', 'makeCopy'] or answer == 'y':123        expected_content = TEST_STR_REMOTE124    file1_path = os.path.join(TEST_FOLDER, 'dir1', 'file1.txt')125    assert_file_content(file1_path, expected_content)126    if conflict_handling == 'makeCopy':127        expected_name_path = syncer.get_copy_filename(file1_path)128        assert os.path.exists(expected_name_path)129        assert_file_content(expected_name_path, TEST_STR_LOCAL)130@pytest.mark.parametrize('conflict_handling, answer', [131    ('ask', 'y'),132    ('ask', 'n'),133    ('delete', None),134    ('keep', None),135])136def test_remote_deleted(config, connection, monkeypatch, conflict_handling, answer):137    config['sync']['conflict-handling']['remote-deleted'] = conflict_handling138    check_basic_sync(config, connection)139    remove_smb_tree(TEST_SHARE, connection, os.path.join(TEST_FOLDER, 'dir1'))140    connection.deleteFiles(TEST_SHARE, os.path.join(TEST_FOLDER, 'dir2', 'file1.txt'))141    if conflict_handling == 'ask':142        monkeypatch.setattr(builtins, 'input', lambda x: answer)143    syncer = create_smb_sync(config)144    syncer.sync()145    if conflict_handling == 'keep' or answer == 'n':146        assert_local_file_structure()147    elif conflict_handling == 'delete' or answer == 'y':148        assert not os.path.exists(os.path.join(TEST_FOLDER, 'dir1'))149        assert not os.path.exists(os.path.join(TEST_FOLDER, 'dir2', 'file1.txt'))150        assert os.path.exists(os.path.join(TEST_FOLDER, 'dir2', 'file2.txt'))151@pytest.mark.parametrize('conflict_handling, expected_content', [152    ('keep', 'existing file'),153    ('overwrite', 'default content'),154])155def test_existing_local_files(config, connection, conflict_handling, expected_content):156    config['sync']['conflict-handling']['local-changes'] = conflict_handling157    dirname = os.path.join(TEST_FOLDER, 'dir1')158    os.makedirs(dirname)159    for filename in generate_files(2, 'existing file'):160        os.rename(filename, os.path.join(dirname, filename))161    check_basic_sync(config, connection)162    assert_file_content(os.path.join(TEST_FOLDER, 'dir1', 'file1.txt'), expected_content)163    # on a second sync, no question should be asked164    config['sync']['conflict-handling']['local-changes'] = 'ask'165    syncer = create_smb_sync(config)166    syncer.sync()167    assert_local_file_structure()...test_all_provisioners.py
Source:test_all_provisioners.py  
...45        deploy_ostree([os.path.join(TESTS_DIR, 'all-provisioners.json')])46    def test_should_copy_etc_fstab_from_host(self):47        self.assert_files_equal('/etc/fstab', self.deployment('etc', 'fstab'))48    def test_should_create_interfaces_file_for_loopback(self):49        self.assert_file_content(50            self.deployment('etc', 'network', 'interfaces.d', 'lo'),51            'auto lo\niface lo inet loopback\n'52        )53    def test_should_create_interfaces_file_for_specified_interface(self):54        self.assert_file_content(55            self.deployment('etc', 'network', 'interfaces.d', 'enp0s3'),56            'allow-hotplug enp0s3\niface enp0s3 inet dhcp\n'57        )58    def test_should_set_root_password(self):59        self.assertTrue(self.get_shadow('root').password_is('rootpw'))60    def test_should_create_test_user(self):61        self.assertIsNotNone(self.get_pwd('testuser'))62        self.assertTrue(self.get_shadow('testuser').password_is('testpw'))63    def test_should_create_test_user_with_default_shell(self):64        self.assertEqual(self.get_pwd('testuser').shell, '')65    def test_should_create_user_with_custom_shell(self):66        self.assertEqual(self.get_pwd('shell-user').shell, '/my/custom/shell')67    def test_should_create_home_directories(self):68        self.assertTrue(os.path.isfile(self.var('home', 'testuser', '.bashrc')))69        self.assertTrue(os.path.isfile(self.var('home', 'shell-user', '.bashrc')))70    def test_should_copy_authorized_keys_file(self):71        ssh_dir = self.var('home', 'testuser', '.ssh')72        auth_keys = os.path.join(ssh_dir, 'authorized_keys')73        pwd = self.get_pwd('testuser')74        self.assert_file_mode(ssh_dir, pwd.uid, 0o700)75        self.assert_file_mode(auth_keys, pwd.uid, 0o600)76        self.assert_file_content(auth_keys, 'authorized keys file')77    def test_should_create_sudoers_file(self):78        sudoers_file = self.deployment('etc', 'sudoers.d', 'testuser-passwordless-sudo')79        self.assert_file_mode(sudoers_file, 0, 0o440)80        self.assert_file_content(sudoers_file, 'testuser ALL=(ALL) NOPASSWD: ALL\n')81    def test_should_recreate_existing_user_with_new_parameters(self):82        self.assertEqual(self.get_pwd('existing-user').shell, '/new/shell')83        self.assertTrue(self.get_shadow('existing-user').password_is('overwritten-password'))84    # helper functions85    def get_pwd(self, name) -> PasswdEntry:86        for pwd in passwd(self.deployment()):87            if pwd.name == name:88                return pwd89        self.fail('no passwd entry for %s' % name)90    def get_shadow(self, name) -> ShadowEntry:91        for spwd in shadow(self.deployment()):92            if spwd.name == name:93                return spwd94        self.fail('no shadow entry for %s' % name)95    def var(self, *args):96        return os.path.join('/ostree', 'deploy', 'test-stateroot', 'var', *args)97    def deployment(self, *args):98        deployments_dir = '/ostree/deploy/test-stateroot/deploy'99        elems = [elem for elem in os.listdir(deployments_dir) if not elem.endswith('.origin')]100        self.assertEqual(len(elems), 1)101        deployment = os.path.join(deployments_dir, elems[0])102        return os.path.join(deployment, *args)103    # helper asserts104    def assert_file_content(self, path, expected_content):105        with open(path, 'r') as f:106            file_content = f.read()107        self.assertEqual(file_content, expected_content)108    def assert_files_equal(self, path1, path2):109        with open(path1, 'r') as f:110            self.assert_file_content(path2, f.read())111    def assert_file_mode(self, path, owner, mode):112        statresult = os.stat(path)113        self.assertEqual(stat.S_IMODE(statresult.st_mode), mode)114        self.assertEqual(statresult.st_uid, owner)...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
