Best Python code snippet using testcontainers-python_python
test_roadster.py
Source:test_roadster.py  
...131    assert minus_percent(1, json.loads(setup_module)["LCL_period"]) <= \132        json.loads(setup_module)["API_period"] <= \133        plus_percent(1, json.loads(setup_module)["LCL_period"])134@pytest.fixture(scope='module')135def setup_module():136    CDATA = ""137    roadster_data = ''138    try:139        roadster_data = alphaOrder(spacexpython.roadster.roadster())140    except spacexpython.utils.SpaceXReadTimeOut:141        pytest.xfail("Space/X API Read Timed Out")142        print("Failure on info.roadster")143    CDATA = CDATA + '{"API_name":"' \144        + (json.loads(roadster_data)["name"]) + '",'145    CDATA = CDATA + '"API_launch_date_utc":"' \146        + str((json.loads(roadster_data)["launch_date_utc"])) + '",'147    CDATA = CDATA + '"API_launch_date_unix":' \148        + str((json.loads(roadster_data)["launch_date_unix"])) + ','149    CDATA = CDATA + '"API_launch_mass_kg":' \...test_runner_xunit.py
Source:test_runner_xunit.py  
...6import pytest7def test_module_and_function_setup(testdir):8    reprec = testdir.inline_runsource("""9        modlevel = []10        def setup_module(module):11            assert not modlevel12            module.modlevel.append(42)13        def teardown_module(module):14            modlevel.pop()15        def setup_function(function):16            function.answer = 1717        def teardown_function(function):18            del function.answer19        def test_modlevel():20            assert modlevel[0] == 4221            assert test_modlevel.answer == 1722        class TestFromClass(object):23            def test_module(self):24                assert modlevel[0] == 4225                assert not hasattr(test_modlevel, 'answer')26    """)27    rep = reprec.matchreport("test_modlevel")28    assert rep.passed29    rep = reprec.matchreport("test_module")30    assert rep.passed31def test_module_setup_failure_no_teardown(testdir):32    reprec = testdir.inline_runsource("""33        values = []34        def setup_module(module):35            values.append(1)36            0/037        def test_nothing():38            pass39        def teardown_module(module):40            values.append(2)41    """)42    reprec.assertoutcome(failed=1)43    calls = reprec.getcalls("pytest_runtest_setup")44    assert calls[0].item.module.values == [1]45def test_setup_function_failure_no_teardown(testdir):46    reprec = testdir.inline_runsource("""47        modlevel = []48        def setup_function(function):49            modlevel.append(1)50            0/051        def teardown_function(module):52            modlevel.append(2)53        def test_func():54            pass55    """)56    calls = reprec.getcalls("pytest_runtest_setup")57    assert calls[0].item.module.modlevel == [1]58def test_class_setup(testdir):59    reprec = testdir.inline_runsource("""60        class TestSimpleClassSetup(object):61            clslevel = []62            def setup_class(cls):63                cls.clslevel.append(23)64            def teardown_class(cls):65                cls.clslevel.pop()66            def test_classlevel(self):67                assert self.clslevel[0] == 2368        class TestInheritedClassSetupStillWorks(TestSimpleClassSetup):69            def test_classlevel_anothertime(self):70                assert self.clslevel == [23]71        def test_cleanup():72            assert not TestSimpleClassSetup.clslevel73            assert not TestInheritedClassSetupStillWorks.clslevel74    """)75    reprec.assertoutcome(passed=1 + 2 + 1)76def test_class_setup_failure_no_teardown(testdir):77    reprec = testdir.inline_runsource("""78        class TestSimpleClassSetup(object):79            clslevel = []80            def setup_class(cls):81                0/082            def teardown_class(cls):83                cls.clslevel.append(1)84            def test_classlevel(self):85                pass86        def test_cleanup():87            assert not TestSimpleClassSetup.clslevel88    """)89    reprec.assertoutcome(failed=1, passed=1)90def test_method_setup(testdir):91    reprec = testdir.inline_runsource("""92        class TestSetupMethod(object):93            def setup_method(self, meth):94                self.methsetup = meth95            def teardown_method(self, meth):96                del self.methsetup97            def test_some(self):98                assert self.methsetup == self.test_some99            def test_other(self):100                assert self.methsetup == self.test_other101    """)102    reprec.assertoutcome(passed=2)103def test_method_setup_failure_no_teardown(testdir):104    reprec = testdir.inline_runsource("""105        class TestMethodSetup(object):106            clslevel = []107            def setup_method(self, method):108                self.clslevel.append(1)109                0/0110            def teardown_method(self, method):111                self.clslevel.append(2)112            def test_method(self):113                pass114        def test_cleanup():115            assert TestMethodSetup.clslevel == [1]116    """)117    reprec.assertoutcome(failed=1, passed=1)118def test_method_generator_setup(testdir):119    reprec = testdir.inline_runsource("""120        class TestSetupTeardownOnInstance(object):121            def setup_class(cls):122                cls.classsetup = True123            def setup_method(self, method):124                self.methsetup = method125            def test_generate(self):126                assert self.classsetup127                assert self.methsetup == self.test_generate128                yield self.generated, 5129                yield self.generated, 2130            def generated(self, value):131                assert self.classsetup132                assert self.methsetup == self.test_generate133                assert value == 5134    """)135    reprec.assertoutcome(passed=1, failed=1)136def test_func_generator_setup(testdir):137    reprec = testdir.inline_runsource("""138        import sys139        def setup_module(mod):140            print ("setup_module")141            mod.x = []142        def setup_function(fun):143            print ("setup_function")144            x.append(1)145        def teardown_function(fun):146            print ("teardown_function")147            x.pop()148        def test_one():149            assert x == [1]150            def check():151                print ("check")152                sys.stderr.write("e\\n")153                assert x == [1]154            yield check155            assert x == [1]156    """)157    rep = reprec.matchreport("test_one", names="pytest_runtest_logreport")158    assert rep.passed159def test_method_setup_uses_fresh_instances(testdir):160    reprec = testdir.inline_runsource("""161        class TestSelfState1(object):162            memory = []163            def test_hello(self):164                self.memory.append(self)165            def test_afterhello(self):166                assert self != self.memory[0]167    """)168    reprec.assertoutcome(passed=2, failed=0)169def test_setup_that_skips_calledagain(testdir):170    p = testdir.makepyfile("""171        import pytest172        def setup_module(mod):173            pytest.skip("x")174        def test_function1():175            pass176        def test_function2():177            pass178    """)179    reprec = testdir.inline_run(p)180    reprec.assertoutcome(skipped=2)181def test_setup_fails_again_on_all_tests(testdir):182    p = testdir.makepyfile("""183        import pytest184        def setup_module(mod):185            raise ValueError(42)186        def test_function1():187            pass188        def test_function2():189            pass190    """)191    reprec = testdir.inline_run(p)192    reprec.assertoutcome(failed=2)193def test_setup_funcarg_setup_when_outer_scope_fails(testdir):194    p = testdir.makepyfile("""195        import pytest196        def setup_module(mod):197            raise ValueError(42)198        @pytest.fixture199        def hello(request):200            raise ValueError("xyz43")201        def test_function1(hello):202            pass203        def test_function2(hello):204            pass205    """)206    result = testdir.runpytest(p)207    result.stdout.fnmatch_lines([208        "*function1*",209        "*ValueError*42*",210        "*function2*",211        "*ValueError*42*",212        "*2 error*"213    ])214    assert "xyz43" not in result.stdout.str()215@pytest.mark.parametrize('arg', ['', 'arg'])216def test_setup_teardown_function_level_with_optional_argument(testdir, monkeypatch, arg):217    """parameter to setup/teardown xunit-style functions parameter is now optional (#1728)."""218    import sys219    trace_setups_teardowns = []220    monkeypatch.setattr(sys, 'trace_setups_teardowns', trace_setups_teardowns, raising=False)221    p = testdir.makepyfile("""222        import pytest223        import sys224        trace = sys.trace_setups_teardowns.append225        def setup_module({arg}): trace('setup_module')226        def teardown_module({arg}): trace('teardown_module')227        def setup_function({arg}): trace('setup_function')228        def teardown_function({arg}): trace('teardown_function')229        def test_function_1(): pass230        def test_function_2(): pass231        class Test(object):232            def setup_method(self, {arg}): trace('setup_method')233            def teardown_method(self, {arg}): trace('teardown_method')234            def test_method_1(self): pass235            def test_method_2(self): pass236    """.format(arg=arg))237    result = testdir.inline_run(p)238    result.assertoutcome(passed=4)239    expected = [...model_setup.py
Source:model_setup.py  
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import sys, os, getopt, json, warnings4from copy import deepcopy5import numpy as np6from . import parameters7from ..utils.obsutils import fix_obs8"""This module has methods to take a .py file containing run parameters, model9parameters and other info and return a run_params dictionary, an obs10dictionary, and a model.  It also has methods to parse command line options and11return an sps object and noise objects.12Most of the load_<x> methods are just really shallow wrappers on13```import_module_from_file(param_file).load_<x>(**kwargs)``` and could probably14be done away with at this point, as they add a mostly useless layer of15abstraction.  Kept here for future flexibility.16"""17__all__ = ["parse_args", "import_module_from_file", "get_run_params",18           "load_model", "load_obs", "load_sps", "load_gp", "show_syntax"]19deprecation_msg = ("Use argparse based operation; usage via prospector_*.py "20                   "scripts will be disabled in the future.")21def parse_args(argv, argdict={}):22    """Parse command line arguments, allowing for optional arguments.23    Simple/Fragile.24    """25    warnings.warn(deprecation_msg, FutureWarning)26    args = [sub for arg in argv[1:] for sub in arg.split('=')]27    for i, a in enumerate(args):28        if (a[:2] == '--'):29            abare = a[2:]30            if abare == 'help':31                show_syntax(argv, argdict)32                sys.exit()33        else:34            continue35        if abare in argdict.keys():36            apo = deepcopy(args[i+1])37            func = type(argdict[abare])38            try:39                argdict[abare] = func(apo)40                if func is bool:41                    argdict[abare] = apo in ['True', 'true', 'T', 't', 'yes']42            except TypeError:43                argdict[abare] = apo44    return argdict45def get_run_params(param_file=None, argv=None, **kwargs):46    """Get a run_params dictionary from the param_file (if passed) otherwise47    return the kwargs dictionary.48    The order of precedence of parameter specification locations is:49        * 1. param_file (lowest)50        * 2. kwargs passsed to this function51        * 3. command line arguments52    """53    warnings.warn(deprecation_msg, FutureWarning)54    rp = {}55    if param_file is None:56        ext = ""57    else:58        ext = param_file.split('.')[-1]59    if ext == 'py':60        setup_module = import_module_from_file(param_file)61        rp = deepcopy(setup_module.run_params)62    elif ext == 'json':63        rp, mp = parameters.read_plist(param_file)64    if kwargs is not None:65        kwargs.update(rp)66        rp = kwargs67    if argv is not None:68        rp = parse_args(argv, argdict=rp)69    rp['param_file'] = param_file70    return rp71def load_sps(param_file=None, **kwargs):72    """Return an ``sps`` object which is used to hold spectral libraries,73    perform interpolations, convolutions, etc.74    """75    warnings.warn(deprecation_msg, FutureWarning)76    ext = param_file.split('.')[-1]77    assert ext == 'py'78    setup_module = import_module_from_file(param_file)79    if hasattr(setup_module, 'load_sps'):80        builder = setup_module.load_sps81    elif hasattr(setup_module, 'build_sps'):82        builder = setup_module.build_sps83    else:84        warnings.warn("Could not find load_sps or build_sps methods in param_file")85        return None86    sps = builder(**kwargs)87    return sps88def load_gp(param_file=None, **kwargs):89    """Return two Gaussian Processes objects, either using BSFH's internal GP90    objects or George.91    :returns gp_spec:92        The gaussian process object to use for the spectroscopy.93    :returns gp_phot:94        The gaussian process object to use for the photometry.95    """96    warnings.warn(deprecation_msg, FutureWarning)97    ext = param_file.split('.')[-1]98    assert ext == "py"99    setup_module = import_module_from_file(param_file)100    if hasattr(setup_module, 'load_gp'):101        builder = setup_module.load_gp102    elif hasattr(setup_module, 'build_noise'):103        builder = setup_module.build_noise104    else:105        warnings.warn("Could not find load_gp or build_noise methods in param_file")106        return None, None107    spec_noise, phot_noise = builder(**kwargs)108    return spec_noise, phot_noise109def load_model(param_file=None, **kwargs):110    """Load the model object from a model config list given in the config file.111    :returns model:112        An instance of the parameters.ProspectorParams object which has113        been configured114    """115    warnings.warn(deprecation_msg, FutureWarning)116    ext = param_file.split('.')[-1]117    assert ext == 'py'118    setup_module = import_module_from_file(param_file)119        #mp = deepcopy(setup_module.model_params)120    if hasattr(setup_module, 'load_model'):121        builder = setup_module.load_model122    elif hasattr(setup_module, 'build_model'):123        builder = setup_module.build_model124    else:125        warnings.warn("Could not find load_model or build_model methods in param_file")126        return None127    model = builder(**kwargs)128    return model129def load_obs(param_file=None, **kwargs):130    """Load the obs dictionary using the `obs` attribute or methods in131    ``param_file``.  kwargs are passed to these methods and ``fix_obs()``132    :returns obs:133        A dictionary of observational data.134    """135    warnings.warn(deprecation_msg, FutureWarning)136    ext = param_file.split('.')[-1]137    obs = None138    assert ext == 'py'139    print('reading py script {}'.format(param_file))140    setup_module = import_module_from_file(param_file)141    if hasattr(setup_module, 'obs'):142        return fix_obs(deepcopy(setup_module.obs))143    if hasattr(setup_module, 'load_obs'):144        builder = setup_module.load_obs145    elif hasattr(setup_module, 'build_obs'):146        builder = setup_module.build_obs147    else:148        warnings.warn("Could not find load_obs or build_obs methods in param_file")149        return None150    obs = builder(**kwargs)151    obs = fix_obs(obs, **kwargs)152    return obs153def import_module_from_file(path_to_file):154    """This has to break everything ever, right?155    """156    from importlib import import_module157    path, filename = os.path.split(path_to_file)158    modname = filename.replace('.py', '')159    sys.path.insert(0, path)160    user_module = import_module(modname)161    sys.path.remove(path)162    return user_module163def import_module_from_string(source, name, add_to_sys_modules=True):164    """Well this seems dangerous.165    """166    import imp167    user_module = imp.new_module(name)168    exec(source, user_module.__dict__)169    if add_to_sys_modules:170        sys.modules[name] = user_module171    return user_module172def show_syntax(args, ad):173    """Show command line syntax corresponding to the provided arg dictionary174    `ad`.175    """176    print('Usage:\n {0} '.format(args[0]) +177          ' '.join(['--{0}=<value>'.format(k) for k in ad.keys()]))178class Bunch(object):179    """ Simple storage.180    """181    def __init__(self, **kwargs):182        self.__dict__.update(kwargs)183def custom_filter_dict(filename):184    filter_dict = {}185    with open(filename, 'r') as f:186        for line in f:187            ind, name = line.split()188            filter_dict[name.lower()] = Bunch(index=int(ind)-1)...test_stanford.py
Source:test_stanford.py  
...10from nose.tools import with_setup11# Project imports12from lexnlp import is_stanford_enabled13from lexnlp.tests import lexnlp_tests14def setup_module():15    """16    Setup environment pre-tests17    :return:18    """19    # enable_stanford()20def teardown_module():21    """22    Setup environment post-tests.23    :return:24    """25    # disable_stanford()26@with_setup(setup_module, teardown_module)27@pytest.mark.skipif(not is_stanford_enabled(), reason="Stanford is disabled.")28def test_stanford_tokens():...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!!
