Best Python code snippet using avocado_python
test_compileall.py
Source:test_compileall.py  
...248        self.pkgdir = os.path.join(self.directory, 'foo')249        os.mkdir(self.pkgdir)250        self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')251        # Create the __init__.py and a package module.252        self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')253        self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')254    def test_no_args_compiles_path(self):255        # Note that -l is implied for the no args case.256        self._skip_if_sys_path_not_writable()257        bazfn = script_helper.make_script(self.directory, 'baz', '')258        self.assertRunOK(PYTHONPATH=self.directory)259        self.assertCompiled(bazfn)260        self.assertNotCompiled(self.initfn)261        self.assertNotCompiled(self.barfn)262    @without_source_date_epoch  # timestamp invalidation test263    def test_no_args_respects_force_flag(self):264        self._skip_if_sys_path_not_writable()265        bazfn = script_helper.make_script(self.directory, 'baz', '')266        self.assertRunOK(PYTHONPATH=self.directory)267        pycpath = importlib.util.cache_from_source(bazfn)268        # Set atime/mtime backward to avoid file timestamp resolution issues269        os.utime(pycpath, (time.time()-60,)*2)270        mtime = os.stat(pycpath).st_mtime271        # Without force, no recompilation272        self.assertRunOK(PYTHONPATH=self.directory)273        mtime2 = os.stat(pycpath).st_mtime274        self.assertEqual(mtime, mtime2)275        # Now force it.276        self.assertRunOK('-f', PYTHONPATH=self.directory)277        mtime2 = os.stat(pycpath).st_mtime278        self.assertNotEqual(mtime, mtime2)279    def test_no_args_respects_quiet_flag(self):280        self._skip_if_sys_path_not_writable()281        script_helper.make_script(self.directory, 'baz', '')282        noisy = self.assertRunOK(PYTHONPATH=self.directory)283        self.assertIn(b'Listing ', noisy)284        quiet = self.assertRunOK('-q', PYTHONPATH=self.directory)285        self.assertNotIn(b'Listing ', quiet)286    # Ensure that the default behavior of compileall's CLI is to create287    # PEP 3147/PEP 488 pyc files.288    for name, ext, switch in [289        ('normal', 'pyc', []),290        ('optimize', 'opt-1.pyc', ['-O']),291        ('doubleoptimize', 'opt-2.pyc', ['-OO']),292    ]:293        def f(self, ext=ext, switch=switch):294            script_helper.assert_python_ok(*(switch +295                ['-m', 'compileall', '-q', self.pkgdir]))296            # Verify the __pycache__ directory contents.297            self.assertTrue(os.path.exists(self.pkgdir_cachedir))298            expected = sorted(base.format(sys.implementation.cache_tag, ext)299                              for base in ('__init__.{}.{}', 'bar.{}.{}'))300            self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)301            # Make sure there are no .pyc files in the source directory.302            self.assertFalse([fn for fn in os.listdir(self.pkgdir)303                              if fn.endswith(ext)])304        locals()['test_pep3147_paths_' + name] = f305    def test_legacy_paths(self):306        # Ensure that with the proper switch, compileall leaves legacy307        # pyc files, and no __pycache__ directory.308        self.assertRunOK('-b', '-q', self.pkgdir)309        # Verify the __pycache__ directory contents.310        self.assertFalse(os.path.exists(self.pkgdir_cachedir))311        expected = sorted(['__init__.py', '__init__.pyc', 'bar.py',312                           'bar.pyc'])313        self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)314    def test_multiple_runs(self):315        # Bug 8527 reported that multiple calls produced empty316        # __pycache__/__pycache__ directories.317        self.assertRunOK('-q', self.pkgdir)318        # Verify the __pycache__ directory contents.319        self.assertTrue(os.path.exists(self.pkgdir_cachedir))320        cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')321        self.assertFalse(os.path.exists(cachecachedir))322        # Call compileall again.323        self.assertRunOK('-q', self.pkgdir)324        self.assertTrue(os.path.exists(self.pkgdir_cachedir))325        self.assertFalse(os.path.exists(cachecachedir))326    @without_source_date_epoch  # timestamp invalidation test327    def test_force(self):328        self.assertRunOK('-q', self.pkgdir)329        pycpath = importlib.util.cache_from_source(self.barfn)330        # set atime/mtime backward to avoid file timestamp resolution issues331        os.utime(pycpath, (time.time()-60,)*2)332        mtime = os.stat(pycpath).st_mtime333        # without force, no recompilation334        self.assertRunOK('-q', self.pkgdir)335        mtime2 = os.stat(pycpath).st_mtime336        self.assertEqual(mtime, mtime2)337        # now force it.338        self.assertRunOK('-q', '-f', self.pkgdir)339        mtime2 = os.stat(pycpath).st_mtime340        self.assertNotEqual(mtime, mtime2)341    def test_recursion_control(self):342        subpackage = os.path.join(self.pkgdir, 'spam')343        os.mkdir(subpackage)344        subinitfn = script_helper.make_script(subpackage, '__init__', '')345        hamfn = script_helper.make_script(subpackage, 'ham', '')346        self.assertRunOK('-q', '-l', self.pkgdir)347        self.assertNotCompiled(subinitfn)348        self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))349        self.assertRunOK('-q', self.pkgdir)350        self.assertCompiled(subinitfn)351        self.assertCompiled(hamfn)352    def test_recursion_limit(self):353        subpackage = os.path.join(self.pkgdir, 'spam')354        subpackage2 = os.path.join(subpackage, 'ham')355        subpackage3 = os.path.join(subpackage2, 'eggs')356        for pkg in (subpackage, subpackage2, subpackage3):357            script_helper.make_pkg(pkg)358        subinitfn = os.path.join(subpackage, '__init__.py')359        hamfn = script_helper.make_script(subpackage, 'ham', '')360        spamfn = script_helper.make_script(subpackage2, 'spam', '')361        eggfn = script_helper.make_script(subpackage3, 'egg', '')362        self.assertRunOK('-q', '-r 0', self.pkgdir)363        self.assertNotCompiled(subinitfn)364        self.assertFalse(365            os.path.exists(os.path.join(subpackage, '__pycache__')))366        self.assertRunOK('-q', '-r 1', self.pkgdir)367        self.assertCompiled(subinitfn)368        self.assertCompiled(hamfn)369        self.assertNotCompiled(spamfn)370        self.assertRunOK('-q', '-r 2', self.pkgdir)371        self.assertCompiled(subinitfn)372        self.assertCompiled(hamfn)373        self.assertCompiled(spamfn)374        self.assertNotCompiled(eggfn)375        self.assertRunOK('-q', '-r 5', self.pkgdir)376        self.assertCompiled(subinitfn)377        self.assertCompiled(hamfn)378        self.assertCompiled(spamfn)379        self.assertCompiled(eggfn)380    def test_quiet(self):381        noisy = self.assertRunOK(self.pkgdir)382        quiet = self.assertRunOK('-q', self.pkgdir)383        self.assertNotEqual(b'', noisy)384        self.assertEqual(b'', quiet)385    def test_silent(self):386        script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')387        _, quiet, _ = self.assertRunNotOK('-q', self.pkgdir)388        _, silent, _ = self.assertRunNotOK('-qq', self.pkgdir)389        self.assertNotEqual(b'', quiet)390        self.assertEqual(b'', silent)391    def test_regexp(self):392        self.assertRunOK('-q', '-x', r'ba[^\\/]*$', self.pkgdir)393        self.assertNotCompiled(self.barfn)394        self.assertCompiled(self.initfn)395    def test_multiple_dirs(self):396        pkgdir2 = os.path.join(self.directory, 'foo2')397        os.mkdir(pkgdir2)398        init2fn = script_helper.make_script(pkgdir2, '__init__', '')399        bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')400        self.assertRunOK('-q', self.pkgdir, pkgdir2)401        self.assertCompiled(self.initfn)402        self.assertCompiled(self.barfn)403        self.assertCompiled(init2fn)404        self.assertCompiled(bar2fn)405    def test_d_compile_error(self):406        script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')407        rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)408        self.assertRegex(out, b'File "dinsdale')409    def test_d_runtime_error(self):410        bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')411        self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)412        fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')413        pyc = importlib.util.cache_from_source(bazfn)414        os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))415        os.remove(bazfn)416        rc, out, err = script_helper.assert_python_failure(fn, __isolated=False)417        self.assertRegex(err, b'File "dinsdale')418    def test_include_bad_file(self):419        rc, out, err = self.assertRunNotOK(420            '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)421        self.assertRegex(out, b'rror.*nosuchfile')422        self.assertNotRegex(err, b'Traceback')423        self.assertFalse(os.path.exists(importlib.util.cache_from_source(424                                            self.pkgdir_cachedir)))425    def test_include_file_with_arg(self):426        f1 = script_helper.make_script(self.pkgdir, 'f1', '')427        f2 = script_helper.make_script(self.pkgdir, 'f2', '')428        f3 = script_helper.make_script(self.pkgdir, 'f3', '')429        f4 = script_helper.make_script(self.pkgdir, 'f4', '')430        with open(os.path.join(self.directory, 'l1'), 'w') as l1:431            l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)432            l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)433        self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)434        self.assertCompiled(f1)435        self.assertCompiled(f2)436        self.assertNotCompiled(f3)437        self.assertCompiled(f4)438    def test_include_file_no_arg(self):439        f1 = script_helper.make_script(self.pkgdir, 'f1', '')440        f2 = script_helper.make_script(self.pkgdir, 'f2', '')441        f3 = script_helper.make_script(self.pkgdir, 'f3', '')442        f4 = script_helper.make_script(self.pkgdir, 'f4', '')443        with open(os.path.join(self.directory, 'l1'), 'w') as l1:444            l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)445        self.assertRunOK('-i', os.path.join(self.directory, 'l1'))446        self.assertNotCompiled(f1)447        self.assertCompiled(f2)448        self.assertNotCompiled(f3)449        self.assertNotCompiled(f4)450    def test_include_on_stdin(self):451        f1 = script_helper.make_script(self.pkgdir, 'f1', '')452        f2 = script_helper.make_script(self.pkgdir, 'f2', '')453        f3 = script_helper.make_script(self.pkgdir, 'f3', '')454        f4 = script_helper.make_script(self.pkgdir, 'f4', '')455        p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))456        p.stdin.write((f3+os.linesep).encode('ascii'))457        script_helper.kill_python(p)458        self.assertNotCompiled(f1)459        self.assertNotCompiled(f2)460        self.assertCompiled(f3)461        self.assertNotCompiled(f4)462    def test_compiles_as_much_as_possible(self):463        bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')464        rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,465                                           bingfn, self.barfn)466        self.assertRegex(out, b'rror')467        self.assertNotCompiled(bingfn)468        self.assertCompiled(self.initfn)469        self.assertCompiled(self.barfn)470    def test_invalid_arg_produces_message(self):471        out = self.assertRunOK('badfilename')472        self.assertRegex(out, b"Can't list 'badfilename'")473    def test_pyc_invalidation_mode(self):474        script_helper.make_script(self.pkgdir, 'f1', '')475        pyc = importlib.util.cache_from_source(476            os.path.join(self.pkgdir, 'f1.py'))477        self.assertRunOK('--invalidation-mode=checked-hash', self.pkgdir)478        with open(pyc, 'rb') as fp:479            data = fp.read()480        self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b11)481        self.assertRunOK('--invalidation-mode=unchecked-hash', self.pkgdir)482        with open(pyc, 'rb') as fp:483            data = fp.read()484        self.assertEqual(int.from_bytes(data[4:8], 'little'), 0b01)485    @skipUnless(_have_multiprocessing, "requires multiprocessing")486    def test_workers(self):487        bar2fn = script_helper.make_script(self.directory, 'bar2', '')488        files = []489        for suffix in range(5):490            pkgdir = os.path.join(self.directory, 'foo{}'.format(suffix))491            os.mkdir(pkgdir)492            fn = script_helper.make_script(pkgdir, '__init__', '')493            files.append(script_helper.make_script(pkgdir, 'bar2', ''))494        self.assertRunOK(self.directory, '-j', '0')495        self.assertCompiled(bar2fn)496        for file in files:497            self.assertCompiled(file)498    @mock.patch('compileall.compile_dir')499    def test_workers_available_cores(self, compile_dir):500        with mock.patch("sys.argv",501                        new=[sys.executable, self.directory, "-j0"]):502            compileall.main()503            self.assertTrue(compile_dir.called)504            self.assertEqual(compile_dir.call_args[-1]['workers'], 0)505    def _test_ddir_only(self, *, ddir, parallel=True):506        """Recursive compile_dir ddir must contain package paths; bpo39769."""507        fullpath = ["test", "foo"]508        path = self.directory509        mods = []510        for subdir in fullpath:511            path = os.path.join(path, subdir)512            os.mkdir(path)513            script_helper.make_script(path, "__init__", "")514            mods.append(script_helper.make_script(path, "mod",515                                                  "def fn(): 1/0\nfn()\n"))516        compileall.compile_dir(517                self.directory, quiet=True, ddir=ddir,518                workers=2 if parallel else 1)519        self.assertTrue(mods)520        for mod in mods:521            self.assertTrue(mod.startswith(self.directory), mod)522            modcode = importlib.util.cache_from_source(mod)523            modpath = mod[len(self.directory+os.sep):]524            _, _, err = script_helper.assert_python_failure(modcode)525            expected_in = os.path.join(ddir, modpath)526            mod_code_obj = test.test_importlib.util._get_code_from_pyc(modcode)527            self.assertEqual(mod_code_obj.co_filename, expected_in)528            self.assertIn(f'"{expected_in}"', os.fsdecode(err))...opaque-origin.https.window.js
Source:opaque-origin.https.window.js  
...19      }20    });21  });22}23function make_script(snippet) {24  return '<script src="/resources/testharness.js"></script>' +25         '<script>' +26         '  window.onmessage = () => {' +27         '    try {' +28         '      (' + snippet + ')' +29         '        .then(' +30         '          result => {' +31         '            window.parent.postMessage({result: "no rejection"}, "*");' +32         '          }, ' +33         '          error => {' +34         '            try {' +35         '              assert_throws_js(TypeError, () => { throw error; });' +36         '              window.parent.postMessage({result: "correct rejection"}, "*");' +37         '            } catch (e) {' +38         '              window.parent.postMessage({result: "incorrect rejection"}, "*");' +39         '            }' +40         '          });' +41         '    } catch (ex) {' +42         // Report if not implemented/exposed, rather than time out.43         '      window.parent.postMessage({result: "API access threw"}, "*");' +44         '    }' +45         '  };' +46         '<\/script>';47}48['navigator.storage.persisted()',49 'navigator.storage.estimate()',50 // persist() can prompt, so make sure we test that last51 'navigator.storage.persist()',52].forEach(snippet => {53  promise_test(t => {54    return load_iframe(make_script(snippet))55      .then(iframe => {56        iframe.contentWindow.postMessage({}, '*');57        return wait_for_message(iframe);58      })59      .then(message => {60        assert_equals(message.result, 'no rejection',61                      `${snippet} should not reject`);62      });63  }, `${snippet} in non-sandboxed iframe should not reject`);64  promise_test(t => {65    return load_iframe(make_script(snippet), 'allow-scripts')66      .then(iframe => {67        iframe.contentWindow.postMessage({}, '*');68        return wait_for_message(iframe);69      })70      .then(message => {71        assert_equals(message.result, 'correct rejection',72                      `${snippet} should reject with TypeError`);73      });74  }, `${snippet} in sandboxed iframe should reject with TypeError`);...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!!
