Best Python code snippet using Airtest
test_functional.py
Source:test_functional.py  
...55        client = WSGIClient("app", environ={"REQUEST_METHOD": "POST"})56        assert "POST" == client.environ["REQUEST_METHOD"]57class WSGIClientTestCase(unittest.TestCase):58    """Test the ``WSGIClient`` class."""59    def setup_client(self, response=None):60        self.mock_middleware = Mock(return_value=response or HTTPResponse())61        return WSGIClient(62            WSGIApplication(63                middleware=[64                    bootstrap_http_defaults,65                    Mock(return_value=self.mock_middleware),66                ],67                options={},68            )69        )70    def test_content(self):71        """content"""72        response = HTTPResponse()73        response.write("te")74        response.write("st")75        client = self.setup_client(response)76        assert 200 == client.get("/abc")77        assert "test" == client.content78    def test_json(self):79        """json response"""80        patcher = patch.object(response, "json_encode")81        mock_json_encode = patcher.start()82        mock_json_encode.return_value = "{}"83        obj = {"a": 1, "b": "x"}84        res = json_response(obj)85        client = self.setup_client(res)86        assert 200 == client.get("/abc")87        patcher.stop()88        patcher = patch.object(functional, "json_loads")89        mock_json_encode = patcher.start()90        mock_json_encode.return_value = obj91        assert obj == client.json92        patcher.stop()93    def test_assert_json(self):94        """Expecting json response but content type is not valid."""95        response = HTTPResponse()96        client = self.setup_client(response)97        assert 200 == client.get("/abc")98        self.assertRaises(AssertionError, lambda: client.json)99    def test_forms(self):100        """forms"""101        response = HTTPResponse()102        response.write(103            """104            <form action='/test' method='POST'>105            </form>106        """107        )108        client = self.setup_client(response)109        assert 200 == client.get("/abc")110        assert 1 == len(client.forms)111    def test_form(self):112        """forms"""113        response = HTTPResponse()114        response.write(115            """116            <form action='/test' method='POST'>117            </form>118        """119        )120        client = self.setup_client(response)121        assert 200 == client.get("/abc")122        form = client.form123        assert "/test" == form.attrs["action"]124        assert "POST" == form.attrs["method"]125    def test_form_by_attribute(self):126        """forms"""127        response = HTTPResponse()128        response.write(129            """130            <form id='test' action='/test1'>131            </form>132            <form action='/test2' method='POST'>133            </form>134        """135        )136        client = self.setup_client(response)137        assert 200 == client.get("/abc")138        form = client.form_by(id="test")139        assert "/test1" == form.attrs["action"]140        form = client.form_by(action="/test1")141        assert "/test1" == form.attrs["action"]142        assert not client.form_by(action="x")143    def test_form_by_predicate(self):144        """forms"""145        response = HTTPResponse()146        response.write(147            """148            <form id='test' action='/test1'>149            </form>150            <form action='/test2' method='POST'>151            </form>152        """153        )154        client = self.setup_client(response)155        assert 200 == client.get("/abc")156        form = client.form_by(lambda attrs: "test2" in attrs.get("action", ""))157        assert "/test2" == form.attrs["action"]158        assert "POST" == form.attrs["method"]159        assert not client.form_by(lambda attrs: "x" in attrs.get("action", ""))160    def test_default_form(self):161        """form"""162        client = self.setup_client()163        assert 200 == client.get("/abc")164        assert client.form165    def test_get(self):166        """get"""167        client = self.setup_client()168        assert 200 == client.get("/abc")169        request, following = self.mock_middleware.call_args[0]170        assert "GET" == request.method171    def test_get_with_query_string(self):172        """get"""173        client = self.setup_client()174        assert 200 == client.get("/abc?x=1")175        request, following = self.mock_middleware.call_args[0]176        assert "/abc" == request.path177        assert {"x": ["1"]} == request.query178    def test_ajax_get(self):179        """ajax get"""180        client = self.setup_client()181        assert 200 == client.ajax_get("/abc")182        request, following = self.mock_middleware.call_args[0]183        assert "GET" == request.method184        assert "XMLHttpRequest" == request.environ["HTTP_X_REQUESTED_WITH"]185    def test_head(self):186        """head"""187        client = self.setup_client()188        assert 200 == client.head("/abc")189        request, following = self.mock_middleware.call_args[0]190        assert "HEAD" == request.method191    def test_post(self):192        """post"""193        client = self.setup_client()194        assert 200 == client.post("/abc")195        request, following = self.mock_middleware.call_args[0]196        assert "POST" == request.method197    def test_ajax_post(self):198        """ajax post"""199        client = self.setup_client()200        assert 200 == client.ajax_post("/abc")201        request, following = self.mock_middleware.call_args[0]202        assert "POST" == request.method203        assert "XMLHttpRequest" == request.environ["HTTP_X_REQUESTED_WITH"]204    def test_post_content(self):205        """post content"""206        patcher = patch.object(request, "json_loads")207        mock_json_encode = patcher.start()208        mock_json_encode.return_value = {"x": 1}209        client = self.setup_client()210        assert 200 == client.post(211            "/abc", content_type="application/json", content='{"x": 1}'212        )213        req, following = self.mock_middleware.call_args[0]214        assert "POST" == req.method215        assert mock_json_encode.return_value == req.form216        patcher.stop()217    def test_post_stream(self):218        """post stream"""219        patcher = patch.object(request, "json_loads")220        mock_json_encode = patcher.start()221        mock_json_encode.return_value = {"x": 1}222        client = self.setup_client()223        assert 200 == client.post(224            "/abc",225            content_type="application/json",226            stream=BytesIO('{"x": 1}'.encode("ascii")),227        )228        req, following = self.mock_middleware.call_args[0]229        assert "POST" == req.method230        assert mock_json_encode.return_value == req.form231        patcher.stop()232    def test_submit_with_get(self):233        """get"""234        client = self.setup_client()235        values = {"a": ["a1", "a2"], "b": ["b1"]}236        form = Form({"action": "/abc", "method": "get"})237        form.update(values)238        assert 200 == client.submit(form)239        request, following = self.mock_middleware.call_args[0]240        assert "/abc" == request.path241        assert "GET" == request.method242        assert values == request.query243    def test_ajax_submit(self):244        """ajax get"""245        client = self.setup_client()246        values = {"a": ["a1", "a2"], "b": ["b1"]}247        form = Form({"action": "/abc", "method": "get"})248        form.update(values)249        assert 200 == client.ajax_submit(form)250        request, following = self.mock_middleware.call_args[0]251        assert "/abc" == request.path252        assert "GET" == request.method253        assert values == request.query254        assert "XMLHttpRequest" == request.environ["HTTP_X_REQUESTED_WITH"]255    def test_submit_with_get_and_path_query(self):256        """get"""257        client = self.setup_client()258        values = {"b": ["b1"]}259        form = Form({"action": "/abc?a=a1&a=a2", "method": "get"})260        form.update(values)261        assert 200 == client.submit(form)262        request, following = self.mock_middleware.call_args[0]263        assert "/abc" == request.path264        assert "GET" == request.method265        assert {"a": ["a1", "a2"], "b": ["b1"]} == request.query266    def test_submit_with_post(self):267        """post"""268        client = self.setup_client()269        values = {"a": ["a1", "a2"], "b": ["b1"]}270        form = Form({"action": "/abc", "method": "post"})271        form.update(values)272        assert 200 == client.submit(form)273        request, following = self.mock_middleware.call_args[0]274        assert "/abc" == request.path275        assert "POST" == request.method276        assert values == request.form277    def test_follow(self):278        """follow"""279        client = self.setup_client(response=found("/http302"))280        assert 302 == client.get("/abc")281        assert "/http302" == client.headers["Location"][0]282        self.mock_middleware.return_value = see_other("/http303")283        assert 303 == client.follow()284        assert "/http303" == client.headers["Location"][0]285        self.mock_middleware.return_value = permanent_redirect("/http301")286        assert 301 == client.follow()287        assert "/http301" == client.headers["Location"][0]288        self.mock_middleware.return_value = temporary_redirect("/http307")289        assert 307 == client.follow()290        assert "/http307" == client.headers["Location"][0]291        self.mock_middleware.return_value = ajax_redirect("/http207")292        assert 207 == client.follow()293        assert "/http207" == client.headers["Location"][0]294    def test_follow_with_query(self):295        """follow when url has query string."""296        client = self.setup_client(response=found("/http302?x=1"))297        assert 302 == client.get("/abc")298        assert "/http302?x=1" == client.headers["Location"][0]299        assert 302 == client.follow()300        request, following = self.mock_middleware.call_args[0]301        assert "/http302" == request.path302        assert {"x": ["1"]} == request.query303    def test_set_cookie(self):304        """process Set-Cookie HTTP response headers."""305        options = {306            "HTTP_COOKIE_DOMAIN": None,307            "HTTP_COOKIE_SECURE": True,308            "HTTP_COOKIE_SAMESITE": None,309            "HTTP_COOKIE_HTTPONLY": True,310        }311        cookie = HTTPCookie("c1", value="12345", options=options)312        response = HTTPResponse()313        response.cookies.append(cookie)314        cookie = HTTPCookie("c2", value="23456", options=options)315        response.cookies.append(cookie)316        client = self.setup_client()317        self.mock_middleware.return_value = response318        assert 200 == client.get("/abc")319        assert 2 == len(client.cookies)320        assert "12345" == client.cookies["c1"]321        assert "23456" == client.cookies["c2"]322        # Cookies remain accross requests.323        response.cookies = []324        assert 200 == client.get("/abc")325        assert 2 == len(client.cookies)326        request, following = self.mock_middleware.call_args[0]327        assert {"c1": "12345", "c2": "23456"} == request.cookies328        # Cookie removed.329        cookie = HTTPCookie.delete("c2", options=options)330        response.cookies.append(cookie)331        assert 200 == client.get("/abc")332        assert 1 == len(client.cookies)333        assert "12345" == client.cookies["c1"]334        # All cookies removed.335        cookie = HTTPCookie.delete("c1", options=options)336        response.cookies.append(cookie)337        assert 200 == client.get("/abc")338        assert 0 == len(client.cookies)339        assert "HTTP_COOKIE" in client.environ340        assert 200 == client.get("/abc")341        assert "HTTP_COOKIE" not in client.environ342    def test_pagemixin_form(self):343        """PageMixin submit"""344        response = HTTPResponse()345        response.write(346            """347            <form action='/test1'>348            </form>349        """350        )351        client = self.setup_client(response)352        assert 200 == client.get("/abc")353        page = PageMixin()354        page.client = client355        form = page.form()356        assert "/test1" == form.attrs["action"]357    def test_pagemixin_submit_form_not_found(self):358        """PageMixin submit, form is not found."""359        response = HTTPResponse()360        client = self.setup_client(response)361        assert 200 == client.get("/abc")362        forms = [None, client.form]363        page = PageMixin()364        page.form = lambda: forms.pop()365        page.client = client366        assert page.submit() is None367        assert not forms368    def test_pagemixin_submit(self):369        """PageMixin submit."""370        response = HTTPResponse()371        client = self.setup_client(response)372        values = {"a": ["a1", "a2"], "b": ["b1"]}373        form = Form({"action": "/abc", "method": "post"})374        assert 200 == client.get("/abc")375        page = PageMixin()376        page.form = lambda: form377        page.client = client378        assert [] == page.submit(**values)379        request, following = self.mock_middleware.call_args[0]380        assert "/abc" == request.path381        assert "POST" == request.method382        assert values == request.form383    def test_pagemixin_ajax_submit(self):384        """PageMixin AJAX submit."""385        response = HTTPResponse()386        client = self.setup_client(response)387        values = {"a": ["a1", "a2"], "b": ["b1"]}388        form = Form({"action": "/abc", "method": "post"})389        assert 200 == client.get("/abc")390        page = PageMixin()391        page.form = lambda: form392        page.client = client393        assert 200 == page.ajax_submit(**values)394        request, following = self.mock_middleware.call_args[0]395        assert "/abc" == request.path396        assert "POST" == request.method397        assert values == request.form398class FormTestCase(unittest.TestCase):399    """Test the ``Form`` class."""400    def test_params(self):...client_test.py
Source:client_test.py  
...25    s.bind(('localhost', 0))26    address, port = s.getsockname()27    s.close()28    return port29def setup_client(handler):30    host = 'localhost'31    port = get_free_port()32    print(port)33    server = HTTPServer((host, port), handler)34    server_thread = Thread(target=server.serve_forever)35    server_thread.setDaemon(True)36    server_thread.start()37    client = alluxio.Client(host, port, timeout=60)38    return client, lambda: server.shutdown39def handle_paths_request(request, path, action, params=None, input=None, output=None):40    # Assert that URL path is expected.41    expected_path = alluxio.client._paths_url_path(path, action)42    if params is not None:43        expected_path += '?'44        for i, (k, v) in enumerate(params.items()):45            if i != 0:46                expected_path += '&'47            try:48                quoted_v = urllib.quote(v, safe='')49            except AttributeError:50                quoted_v = urllib.parse.quote(v, safe='')51            expected_path += '{}={}'.format(k, quoted_v)52    assert request.path == expected_path53    if input is not None:54        # Assert that request body is expected.55        content_len = int(get_http_header(request, 'content-length'))56        body = request.rfile.read(content_len)57        assert json.loads(body) == input.json()58    # Respond.59    request.send_response(200)60    if output is not None:61        request.send_header('Content-Type', 'application/json')62        request.end_headers()63        request.wfile.write(json.dumps(output).encode())64    else:65        request.end_headers()66def paths_handler(path, action, params=None, input=None, output=None):67    class _(BaseHTTPRequestHandler):68        def do_POST(self):69            handle_paths_request(self, path, action,70                                 params=params, input=input, output=output)71    return _72def test_create_directory():73    path = '/foo'74    option = random_create_directory()75    client, cleanup = setup_client(paths_handler(76        path, 'create-directory', input=option))77    client.create_directory(path, option)78    cleanup()79def test_create_file():80    path = '/foo'81    option = random_create_file()82    expected_file_id = 183    client, cleanup = setup_client(paths_handler(84        path, 'create-file', input=option, output=expected_file_id))85    file_id = client.create_file(path, option)86    cleanup()87    assert file_id == expected_file_id88def test_delete():89    path = '/foo'90    option = random_delete()91    client, cleanup = setup_client(paths_handler(path, 'delete', input=option))92    client.delete(path, option)93    cleanup()94def test_exists():95    path = '/foo'96    expected_output = True97    client, cleanup = setup_client(paths_handler(98        path, 'exists', output=expected_output))99    output = client.exists(path)100    cleanup()101    assert output == expected_output102def test_free():103    path = '/foo'104    option = random_free()105    client, cleanup = setup_client(paths_handler(path, 'free', input=option))106    client.free(path, option)107    cleanup()108def test_get_status():109    path = '/foo'110    expected_output = random_file_info()111    client, cleanup = setup_client(paths_handler(112        path, 'get-status', output=expected_output.json()))113    output = client.get_status(path)114    cleanup()115    assert output == expected_output116def test_list_status():117    path = '/foo'118    option = random_list_status()119    expected_file_infos = []120    for _ in range(random.randint(1, 10)):121        expected_file_infos.append(random_file_info())122    expected_output = [info.json() for info in expected_file_infos]123    expected_names = [info.name for info in expected_file_infos]124    client, cleanup = setup_client(paths_handler(125        path, 'list-status', input=option, output=expected_output))126    infos = client.list_status(path, option)127    names = client.ls(path, option)128    cleanup()129    expected_file_infos.sort()130    assert infos == expected_file_infos131    expected_names.sort()132    assert names == expected_names133def test_mount():134    path = '/foo'135    src = random_str()136    option = random_mount()137    client, cleanup = setup_client(paths_handler(138        path, 'mount', params={'src': src}, input=option))139    client.mount(path, src, option)140    cleanup()141def test_open_file():142    path = '/foo'143    expected_file_id = random_int()144    option = random_open_file()145    client, cleanup = setup_client(paths_handler(146        path, 'open-file', input=option, output=expected_file_id))147    file_id = client.open_file(path, option)148    cleanup()149    assert file_id == expected_file_id150def test_rename():151    src = '/foo'152    dst = '/bar'153    client, cleanup = setup_client(154        paths_handler(src, 'rename', params={'dst': dst}))155    client.rename(src, dst)156    cleanup()157def test_set_attribute():158    option = random_set_attribute()159    path = '/foo'160    client, cleanup = setup_client(161        paths_handler(path, 'set-attribute', input=option))162    client.set_attribute(path, option)163    cleanup()164def test_unmount():165    path = '/foo'166    client, cleanup = setup_client(paths_handler(path, 'unmount'))167    client.unmount(path)168    cleanup()169def handle_streams_request(request, file_id, action, input=None, output=None):170    # Assert that URL path is expected.171    expected_path = alluxio.client._streams_url_path(file_id, action)172    assert request.path == expected_path173    content_len = 0174    if input is not None:175        # Assert that request body is expected.176        content_len = int(get_http_header(request, 'content-length'))177        body = request.rfile.read(content_len).decode()178        assert body == input179    # Respond.180    request.send_response(200)181    if output is not None:182        request.send_header('Content-Type', 'application/octet-stream')183        request.end_headers()184        request.wfile.write(output.encode())185    else:186        request.send_header('Content-Type', 'application/json')187        request.end_headers()188        request.wfile.write(json.dumps(content_len).encode())189def streams_handler(file_id, action, input=None, output=None):190    class _(BaseHTTPRequestHandler):191        def do_POST(self):192            handle_streams_request(self, file_id, action,193                                   input=input, output=output)194    return _195def test_close():196    file_id = random_int()197    client, cleanup = setup_client(streams_handler(file_id, 'close'))198    client.close(file_id)199    cleanup()200def test_read():201    file_id = random_int()202    message = random_str()203    client, cleanup = setup_client(204        streams_handler(file_id, 'read', output=message))205    reader = client.read(file_id)206    got = reader.read()207    reader.close()208    assert got.decode() == message209def test_write():210    file_id = random_int()211    message = random_str()212    client, cleanup = setup_client(213        streams_handler(file_id, 'write', input=message))214    writer = client.write(file_id)215    length = writer.write(message)216    writer.close()217    assert length == len(message)218def combined_handler(path, path_action, file_id, stream_action, path_input=None, path_output=None, stream_input=None, stream_output=None):219    class _(BaseHTTPRequestHandler):220        def do_POST(self):221            request_path = urlparse(self.path).path222            paths_path = alluxio.client._paths_url_path(path, path_action)223            streams_path = alluxio.client._streams_url_path(224                file_id, stream_action)225            close_path = alluxio.client._streams_url_path(file_id, 'close')226            if request_path == paths_path:227                handle_paths_request(228                    self, path, path_action, input=path_input, output=path_output)229            elif request_path == streams_path:230                handle_streams_request(231                    self, file_id, stream_action, input=stream_input, output=stream_output)232            elif request_path == close_path:233                self.send_response(200)234                self.end_headers()235    return _236def test_open_read():237    path = '/foo'238    file_id = random_int()239    message = random_str()240    handler = combined_handler(241        path, 'open-file', file_id, 'read', path_output=file_id, stream_output=message)242    client, cleanup = setup_client(handler)243    got = None244    with client.open(path, 'r') as f:245        got = f.read()246    cleanup()247    assert got == message.encode()248def test_open_write():249    path = '/foo'250    file_id = random_int()251    message = random_str()252    handler = combined_handler(path, 'create-file', file_id, 'write',253                               path_output=file_id, stream_input=message)254    client, cleanup = setup_client(handler)255    written_len = None256    with client.open(path, 'w') as f:257        written_len = f.write(message)258    cleanup()...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!!
