Best Python code snippet using pytest-django_python
test_live_server.py
Source:test_live_server.py  
...24            live_server.app.config["SERVER_NAME"]25            == "localhost.localdomain:%d" % live_server.port26        )27    def test_rewrite_application_server_name(self, appdir):28        appdir.create_test_module(29            """30            import pytest31            @pytest.mark.options(server_name='example.com:5000')32            def test_a(live_server):33                assert live_server.app.config['SERVER_NAME'] == \\34                    'example.com:%d' % live_server.port35        """36        )37        result = appdir.runpytest("-v", "-o", "live_server_scope=function")38        result.stdout.fnmatch_lines(["*PASSED*"])39        assert result.ret == 040    def test_prevent_starting_live_server(self, appdir):41        appdir.create_test_module(42            """43            import pytest44            def test_a(live_server):45                assert live_server._process is None46        """47        )48        result = appdir.runpytest("-v", "--no-start-live-server")49        result.stdout.fnmatch_lines(["*passed*"])50        assert result.ret == 051    def test_start_live_server(self, appdir):52        appdir.create_test_module(53            """54            import pytest55            def test_a(live_server):56                assert live_server._process57                assert live_server._process.is_alive()58        """59        )60        result = appdir.runpytest("-v", "--start-live-server")61        result.stdout.fnmatch_lines(["*passed*"])62        assert result.ret == 063    def test_stop_cleanly_join_exception(self, appdir, live_server, caplog):64        # timeout = 'a' here to force an exception when65        # attempting to self._process.join()66        assert not live_server._stop_cleanly(timeout="a")67        assert "Failed to join" in caplog.text68    @pytest.mark.parametrize("clean_stop", [True, False])69    def test_clean_stop_live_server(self, appdir, monkeypatch, clean_stop):70        """Ensure the fixture is trying to cleanly stop the server.71        Because this is tricky to test, we are checking that the _stop_cleanly() internal72        function was called and reported success.73        """74        from pytest_flask.fixtures import LiveServer75        original_stop_cleanly_func = LiveServer._stop_cleanly76        stop_cleanly_result = []77        def mocked_stop_cleanly(*args, **kwargs):78            result = original_stop_cleanly_func(*args, **kwargs)79            stop_cleanly_result.append(result)80            return result81        monkeypatch.setattr(LiveServer, "_stop_cleanly", mocked_stop_cleanly)82        appdir.create_test_module(83            """84            import pytest85            from flask import url_for86            def test_a(live_server, client):87                @live_server.app.route('/')88                def index():89                    return 'got it', 20090                live_server.start()91                res = client.get(url_for('index', _external=True))92                assert res.status_code == 20093                assert b'got it' in res.data94        """95        )96        args = [] if clean_stop else ["--no-live-server-clean-stop"]97        result = appdir.runpytest_inprocess("-v", "--no-start-live-server", *args)98        result.stdout.fnmatch_lines("*1 passed*")99        if clean_stop:100            assert stop_cleanly_result == [True]101        else:102            assert stop_cleanly_result == []103    def test_add_endpoint_to_live_server(self, appdir):104        appdir.create_test_module(105            """106            import pytest107            from flask import url_for108            def test_a(live_server, client):109                @live_server.app.route('/new-endpoint')110                def new_endpoint():111                    return 'got it', 200112                live_server.start()113                res = client.get(url_for('new_endpoint', _external=True))114                assert res.status_code == 200115                assert b'got it' in res.data116        """117        )118        result = appdir.runpytest("-v", "--no-start-live-server")119        result.stdout.fnmatch_lines(["*passed*"])120        assert result.ret == 0121    @pytest.mark.skip("this test hangs in the original code")122    def test_concurrent_requests_to_live_server(self, appdir):123        appdir.create_test_module(124            """125            import pytest126            from flask import url_for127            def test_concurrent_requests(live_server, client):128                @live_server.app.route('/one')129                def one():130                    res = client.get(url_for('two', _external=True))131                    return res.data132                @live_server.app.route('/two')133                def two():134                    return '42'135                live_server.start()136                res = client.get(url_for('one', _external=True))137                assert res.status_code == 200138                assert b'42' in res.data139        """140        )141        result = appdir.runpytest("-v", "--no-start-live-server")142        result.stdout.fnmatch_lines(["*passed*"])143        assert result.ret == 0144    @pytest.mark.parametrize("port", [5000, 5001])145    def test_live_server_fixed_port(self, port, appdir):146        appdir.create_test_module(147            """148            import pytest149            def test_port(live_server):150                assert live_server.port == %d151        """152            % port153        )154        result = appdir.runpytest("-v", "--live-server-port", str(port))155        result.stdout.fnmatch_lines(["*PASSED*"])156        assert result.ret == 0157    @pytest.mark.parametrize("host", ["127.0.0.1", "0.0.0.0"])158    def test_live_server_fixed_host(self, host, appdir):159        appdir.create_test_module(160            """161            import pytest162            def test_port(live_server):163                assert live_server.host == '%s'164        """165            % host166        )167        result = appdir.runpytest("-v", "--live-server-host", str(host))168        result.stdout.fnmatch_lines(["*PASSED*"])169        assert result.ret == 0170    def test_respect_wait_timeout(self, appdir):171        appdir.create_test_module(172            """173            import pytest174            def test_should_fail(live_server):175                assert live_server._process.is_alive()176        """177        )178        result = appdir.runpytest("-v", "--live-server-wait=0.00000001")179        result.stdout.fnmatch_lines(["**ERROR**"])...test_imports.py
Source:test_imports.py  
...5test_frame <- function() {6    return (data.frame(e=c(1, 2, 3)))7}8"""9def create_test_module(tmp_path):10    f = tmp_path / "test_module.r"11    f.write_text(R_MODULE)12    # add to path13    import r14    r.path.append(str(tmp_path))15    return16def test_module_import(tmp_path):17    create_test_module(tmp_path)18    from r import test_module19    assert hasattr(test_module, 'test')20    assert test_module.test(2) == 421def test_package_import():22    from r import base23    assert hasattr(base, 'factor')24def test_pandas_conversion(tmp_path):25    create_test_module(tmp_path)26    from r import test_module27    assert hasattr(test_module, 'test_frame')28    from pandas import DataFrame29    assert type(test_module.test_frame()) is DataFrame30def test_cli(tmp_path):31    import os.path as osp32    import subprocess as sp33    create_test_module(tmp_path)34    rcli = ['rcli', str(tmp_path/'test_module.r')]35    out = sp.check_output(rcli + ['test', '--i=2'])36    assert out.decode().strip() == '[4]'37    csvfile = str(tmp_path/'tmp.csv')38    out = sp.check_output(rcli + ['test_frame', '-', 'to-csv', csvfile])...conftest.py
Source:conftest.py  
...19@pytest.fixture20def appdir(testdir):21    app_root = testdir.tmpdir22    test_root = app_root.mkdir("tests")23    def create_test_module(code, filename="test_app.py"):24        f = test_root.join(filename)25        f.write(dedent(code), ensure=True)26        return f27    testdir.create_test_module = create_test_module28    testdir.create_test_module(29        """30        import pytest31        from flask import Flask32        @pytest.fixture(scope='session')33        def app():34            app = Flask(__name__)35            return app36    """,37        filename="conftest.py",38    )...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!!
