Best Python code snippet using avocado_python
theqoo_api_test.py
Source:theqoo_api_test.py  
1import os2import unittest3from pathlib import Path4import requests5import responses6from varname import nameof7import ini8from api import theqoo_api as api9from tests import test_setting10path = Path(test_setting.TEST_FILE_DIR)11path.mkdir(parents=True, exist_ok=True)12# Set True when do you want to 'real' test13# CAUTION !!14# Don't Execute instrumented LoginTestCase Too Often In A Short Time (About 2~3 Times),15# It May Causes Blocking Your IP From Theqoo About 5 Minutes16TEST_INSTRUMENTED = False17class LoginTestCase_Instrumented(unittest.TestCase):18    url = f'{api.INIT_URL}?mid={api.INDEX_PAGE_ID}&act={api.Actions.LOGIN_FORM}'19    testId = 'id'20    testPw = 'pw'21    def tearDown(self) -> None:22        if os.path.exists(test_setting.FILE_GARBAGE):23            os.remove(test_setting.FILE_GARBAGE)24    def do_login_test(self, login_id: str, login_pw: str, session: requests.Session):25        res = api.do_login(session=session,26                           login_id=login_id, login_pw=login_pw,27                           session_file_name=test_setting.FILE_GARBAGE)28        self.assertTrue(res, 'Return value should be True when login success')29    def do_login_test_attribute_error(self, login_id: str, login_pw: str, session: requests.Session):30        with self.assertRaises(AttributeError):31            api.do_login(session=session,32                         login_id=login_id, login_pw=login_pw,33                         session_file_name=test_setting.FILE_GARBAGE)34    def do_login_test_connection_error(self, login_id: str, login_pw: str, session: requests.Session):35        with self.assertRaises(ConnectionError):36            api.do_login(session=session,37                         login_id=login_id, login_pw=login_pw,38                         session_file_name=test_setting.FILE_GARBAGE)39    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')40    def test_login_ok_instrumented(self):41        with requests.session() as s:42            self.do_login_test(session=s, login_id=ini.THEQOO_ID, login_pw=ini.THEQOO_PW)43    @responses.activate44    def test_login_ok(self):45        responses.add(responses.POST, url=self.url, status=200)46        with requests.session() as s:47            self.do_login_test(session=s, login_id=ini.THEQOO_ID, login_pw=ini.THEQOO_PW)48    @responses.activate49    def test_login_failed_with_connection_error(self):50        responses.add(responses.POST, url=self.url, status=404)51        with requests.session() as s:52            self.do_login_test_connection_error(session=s, login_id=ini.THEQOO_ID, login_pw=self.testPw)53    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')54    def test_login_failed_with_id_instrumented(self):55        with requests.session() as s:56            self.do_login_test_attribute_error(session=s, login_id=self.testId, login_pw=ini.THEQOO_PW)57    @responses.activate58    def test_login_failed_with_id(self):59        res = r'<div class="message error"><p>ì¡´ì¬íì§ ìë íì ìì´ëì
ëë¤.</p></div>'60        responses.add(responses.POST, url=self.url, body=res, status=200)61        with requests.session() as s:62            self.do_login_test_attribute_error(session=s, login_id=self.testId, login_pw=ini.THEQOO_PW)63    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')64    def test_login_failed_with_pw_instrumented(self):65        with requests.session() as s:66            self.do_login_test_attribute_error(session=s, login_id=ini.THEQOO_ID, login_pw=self.testPw)67    @responses.activate68    def test_login_failed_with_pw(self):69        res = r'<div class="message error"><p>ì못ë ë¹ë°ë²í¸ì
ëë¤.</p></div>'70        responses.add(responses.POST, url=self.url, body=res, status=200)71        with requests.session() as s:72            self.do_login_test_attribute_error(session=s, login_id=ini.THEQOO_ID, login_pw=self.testPw)73class DeleteCommentTestCase_Instrumented(unittest.TestCase):74    def delete_comment_success(self, session: requests.Session, comment_srl):75        result = api.delete_comment(session, comment_srl)76        self.assertIsInstance(result, str)77    def delete_comment_fail_with_runtime_error(self, session: requests.Session, comment_srl):78        with self.assertRaises(RuntimeError):79            api.delete_comment(session, comment_srl)80    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')81    def test_delete_comment_success_instrumented(self):82        with api.get_former_session(session_file_name=test_setting.FILE_WITH_SESSION) as s:83            self.delete_comment_success(s, 1580192797)84    @responses.activate85    def test_delete_comment_success(self):86        res = '<?xml version="1.0" encoding="UTF-8"?>' \87              '<response>' \88              '<error>0</error>' \89              '<message>ëê¸ì´ ìì ëììµëë¤. </message>' \90              '<message_type></message_type>' \91              '</response>'92        responses.add(responses.POST, api.INIT_URL, body=res, status=200)93        with requests.session() as s:94            self.delete_comment_success(s, 1580192797)95    @responses.activate96    def test_delete_comment_fail_with_connection_error(self):97        # Not Logged In98        responses.add(responses.POST, api.INIT_URL, status=404)99        with requests.session() as s:100            with self.assertRaises(ConnectionError):101                api.delete_comment(s, 1580192797)102    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')103    def test_delete_comment_fail_with_runtime_error_instrumented(self):104        # Not Logged In105        with requests.session() as s:106            self.delete_comment_fail_with_runtime_error(s, 1580192797)107    @responses.activate108    def test_delete_comment_fail_with_runtime_error(self):109        result_xml = f'<?xml version="1.0" encoding="utf-8" ?>' \110                  f'<response>' \111                  f'<error>-1</error>' \112                  f'<message>ì못ë ìì²ì
ëë¤.</message>' \113                  f'<message_type></message_type>' \114                  f'</response>'115        responses.add(responses.POST, api.INIT_URL, body=result_xml, status=200)116        # Not Logged In117        with requests.session() as s:118            self.delete_comment_fail_with_runtime_error(s, 1580192797)119class GetUserCommentsTestCase(unittest.TestCase):120    def get_user_comments_success(self, session: requests.Session):121        result = api.get_user_comments(session)122        self.assertIsInstance(result, list)123        self.assertGreater(len(result), 0)124        for comment in result:125            self.assertRegex(comment, '[0-9]+')126    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')127    def test_get_user_comments_success_instrumented(self):128        with api.get_former_session(session_file_name=test_setting.FILE_WITH_SESSION) as s:129            self.get_user_comments_success(s)130    @responses.activate131    def test_get_user_comments_success(self):132        body = '<tr>' \133               '<td class="no">149</td>' \134               '<td class="title">' \135               '<div class="origin_document">' \136               '<a href="/1585915956" target="_blank">ì§ì¥ì¸ : <span style="">Article Title</span></a>' \137               '</div>' \138               '<a href="/1585915956#comment_1585918700" target="_blank">Comment</a>' \139               '</td>' \140               '<td class="nowr date">2020-08-26 14:16:50</td>' \141               '<td class="nowr action" style="width:40px;text-align:center;">' \142               '</tr>'143        url1 = f'{api.INIT_URL}?act={api.Actions.OWN_COMMENTS}&mid={api.INDEX_PAGE_ID}&page=1'144        responses.add(responses.GET, url1, body=body, status=200)145        url2 = f'{api.INIT_URL}?act={api.Actions.OWN_COMMENTS}&mid={api.INDEX_PAGE_ID}&page=2'146        responses.add(responses.GET, url2, status=200)147        with requests.session() as s:148            self.get_user_comments_success(s)149    @responses.activate150    def test_get_user_comments_fail(self):151        url = f'{api.INIT_URL}?act={api.Actions.OWN_COMMENTS}&mid={api.INDEX_PAGE_ID}&page=1'152        responses.add(responses.GET, url, status=404)153        with requests.session() as s:154            with self.assertRaises(ConnectionError):155                api.get_user_comments(s)156    @responses.activate157    def test_when_not_logged_in(self):158        url = f'{api.INIT_URL}?act={api.Actions.OWN_COMMENTS}&mid={api.INDEX_PAGE_ID}&page=1'159        body = '<div class="login-header">' \160               '<h1><i class="icon-user"></i> ë¡ê·¸ì¸ì íì§ ìììµëë¤.</h1>' \161               '</div>'162        responses.add(responses.GET, url=url, body=body, status=200)163        with requests.session() as s:164            with self.assertRaises(AttributeError):165                api.get_user_comments(s)166class GetFormerSessionTestCase_With_Session(unittest.TestCase):167    @classmethod168    def setUpClass(cls) -> None:169        if not os.path.exists(test_setting.FILE_WITH_SESSION):170            with requests.session() as s:171                api.do_login(s, ini.THEQOO_ID, ini.THEQOO_PW, test_setting.FILE_WITH_SESSION)172    def test_get_former_session_got_session(self):173        res = api.get_former_session(session_file_name=test_setting.FILE_WITH_SESSION)174        self.assertIsNotNone(res)175        self.assertIsInstance(res, requests.Session)176class GetFormerSessionTestCase_With_No_Session(unittest.TestCase):177    @classmethod178    def setUpClass(cls) -> None:179        if not os.path.exists(test_setting.FILE_NO_SESSION):180            try:181                with requests.session() as s:182                    api.do_login(session=s,183                                 login_id='fakeId', login_pw='fakePw',184                                 session_file_name=test_setting.FILE_NO_SESSION)185            except ConnectionError:186                pass187    def test_get_former_session_no_session_file(self):188        # When There's No File189        res = api.get_former_session('File Nothing')190        self.assertIsNone(res, "None should be returned when there's no file")191    def test_get_former_session_no_session(self):192        res = api.get_former_session(session_file_name=test_setting.FILE_NO_SESSION)193        self.assertIsNone(res)194class GetUserDocumentsTestCase(unittest.TestCase):195    url = f'{api.INIT_URL}?act={api.Actions.OWN_DOCUMENTS}&mid={api.INDEX_PAGE_ID}&page=1'196    def test_get_user_documents_ok(self):197        with api.get_former_session(test_setting.FILE_WITH_SESSION) as s:198            res = api.get_user_documents(s)199            self.assertIsInstance(res, list)200            self.assertGreater(len(res), 0)201            for doc in res:202                self.assertIsInstance(doc, api.Document)203                self.assertTrue(doc.category_nm is not None, doc.category_nm)204                self.assertTrue(doc.title is not None, doc.title)205                self.assertTrue(doc.srl is not None, doc.srl)206    @responses.activate207    def test_get_user_documents_connection_error(self):208        responses.add(responses.GET, url=self.url, status=404)209        with requests.session() as s:210            with self.assertRaises(ConnectionError):211                api.get_user_documents(s)212    @responses.activate213    def test_when_not_logged_in(self):214        body = '<div class="login-header">' \215               '<h1><i class="icon-user"></i> ë¡ê·¸ì¸ì íì§ ìììµëë¤.</h1>' \216               '</div>'217        responses.add(responses.GET, url=self.url, body=body, status=200)218        with requests.session() as s:219            with self.assertRaises(AttributeError):220                api.get_user_documents(s)221class DeleteDocumentTestCase_Instrumented(unittest.TestCase):222    document_srl = '1582525827'223    def delete_document_success(self, session: requests.Session, comment_srl):224        result = api.delete_document(session, comment_srl)225        self.assertIsInstance(result, str)226    def delete_document_fail_with_runtime_error(self, session: requests.Session, comment_srl):227        with self.assertRaises(RuntimeError):228            api.delete_document(session, comment_srl)229    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')230    def test_delete_document_success_instrumented(self):231        with api.get_former_session(session_file_name=test_setting.FILE_WITH_SESSION) as s:232            self.delete_document_success(s, self.document_srl)233    @responses.activate234    def test_delete_document_success(self):235        res = '<?xml version="1.0" encoding="UTF-8"?>' \236              '<response>' \237              '<error>0</error>' \238              '<message>success</message>' \239              '</response>'240        responses.add(responses.POST, api.INIT_URL, body=res, status=200)241        with requests.session() as s:242            self.delete_document_success(s, self.document_srl)243    @responses.activate244    def test_delete_document_fail_with_connection_error(self):245        # Not Logged In246        responses.add(responses.POST, api.INIT_URL, status=404)247        with requests.session() as s:248            with self.assertRaises(ConnectionError):249                api.delete_document(s, self.document_srl)250    @unittest.skipUnless(TEST_INSTRUMENTED, f'Test only when {nameof(TEST_INSTRUMENTED)} is True')251    def test_delete_document_fail_with_runtime_error_instrumented(self):252        # Error never occurs on document deletion253        assert True254    @responses.activate255    def test_delete_document_fail_with_runtime_error(self):256        result_xml = '<?xml version="1.0" encoding="UTF-8"?>' \257                     '<response>' \258                     '<error>1</error>' \259                     '<message>fail</message>' \260                     '</response>'261        responses.add(responses.POST, api.INIT_URL, body=result_xml, status=200)262        # Not Logged In263        with requests.session() as s:264            self.delete_document_fail_with_runtime_error(s, 'asdfadsf')265class TestIsLoggedIn(unittest.TestCase):266    target_url = f'{api.INIT_URL}?{api.Actions.MY_PAGE}'267    @responses.activate268    def test_when_logged_in(self):269        responses.add(responses.GET, url=self.target_url, body='', status=200)270        with requests.session().get(url=self.target_url) as res:271            assert api.is_logged_in(res) is True272    @responses.activate273    def test_when_not_logged_in(self):274        body = '<div class="login-header">' \275               '<h1><i class="icon-user"></i> ë¡ê·¸ì¸ì íì§ ìììµëë¤.</h1>' \276               '</div>'277        responses.add(responses.GET, url=self.target_url, body=body, status=200)278        with requests.session().get(url=self.target_url) as res:279            assert api.is_logged_in(res) is False280if __name__ == '__main__':...test_fragment.py
Source:test_fragment.py  
...60def test_empty() -> None:61    assert render_html(empty_fragment()) == ''62def test_nested() -> None:63    assert render_html(nested_fragment()) == '<p>pre<em>infix</em>post</p>'64def test_instrumented() -> None:65    assert render_html(instrumented_fragment('p')) == '<p>OK</p>'66    assert render_html(instrumented_fragment('span')) == '<span>OK</span>'67    assert render_html(instrumented_fragment('title')) == '<title>OK</title>'68def test_id_clashes() -> None:69    assert render_html(clashing_ids()) == '<p class="aclass"><def></def><fake-tag></fake-tag></p>'70def test_void_elems() -> None:71    assert render_html(void_elems()) == '<input type="submit"><link rel="stylesheet" href="/static/style.css"><br><hr>'72def test_escaping() -> None:73    assert render_html(escaping_strings_and_numbers()) == '<p data-id="42"><3</p><textarea><3</textarea>'74def test_nonescaping() -> None:75    assert render_html(nonescaping()) == '<x><script>1 < 2</script><style>p > a { }</style>'76def test_fragment_in_fragment() -> None:77    assert render_html(use_fragment_in_fragment()) == '<p>Hello</p>'78def test_contextmanager() -> None:...test_teststmpdir.py
Source:test_teststmpdir.py  
1import os2import tempfile3import shutil4import unittest5from avocado.core import exit_codes6from avocado.core import test7from avocado.utils import process8from avocado.utils import script9from .. import AVOCADO, BASEDIR10INSTRUMENTED_SCRIPT = """import os11import tempfile12from avocado import Test13class MyTest(Test):14    def test1(self):15        tempfile.mkstemp(dir=self.teststmpdir)16        if len(os.listdir(self.teststmpdir)) != 2:17            self.fail()18"""19SIMPLE_SCRIPT = """#!/bin/bash20mktemp ${{{0}}}/XXXXXX21if [ $(ls ${{{0}}} | wc -l) == 1 ]22then23    exit 024else25    exit 126fi27""".format(test.COMMON_TMPDIR_NAME)28class TestsTmpDirTests(unittest.TestCase):29    def setUp(self):30        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)31        self.simple_test = script.TemporaryScript(32            'test_simple.sh',33            SIMPLE_SCRIPT)34        self.simple_test.save()35        self.instrumented_test = script.TemporaryScript(36            'test_instrumented.py',37            INSTRUMENTED_SCRIPT)38        self.instrumented_test.save()39    def run_and_check(self, cmd_line, expected_rc, env=None):40        os.chdir(BASEDIR)41        result = process.run(cmd_line, ignore_status=True, env=env)42        self.assertEqual(result.exit_status, expected_rc,43                         "Command %s did not return rc "44                         "%d:\n%s" % (cmd_line, expected_rc, result))45        return result46    @unittest.skipIf(test.COMMON_TMPDIR_NAME in os.environ,47                     "%s already set in os.environ"48                     % test.COMMON_TMPDIR_NAME)49    def test_tests_tmp_dir(self):50        """51        Tests whether automatically created teststmpdir is shared across52        all tests.53        """54        cmd_line = ("%s run --sysinfo=off "55                    "--job-results-dir %s %s %s"56                    % (AVOCADO, self.tmpdir, self.simple_test,57                       self.instrumented_test))58        self.run_and_check(cmd_line, exit_codes.AVOCADO_ALL_OK)59    def test_manualy_created(self):60        """61        Tests whether manually set teststmpdir is used and not deleted by62        avocado63        """64        shared_tmp = tempfile.mkdtemp(dir=self.tmpdir)65        cmd = ("%s run --sysinfo=off --job-results-dir %s %%s"66               % (AVOCADO, self.tmpdir))67        self.run_and_check(cmd % self.simple_test, exit_codes.AVOCADO_ALL_OK,68                           {test.COMMON_TMPDIR_NAME: shared_tmp})69        self.run_and_check(cmd % self.instrumented_test,70                           exit_codes.AVOCADO_ALL_OK,71                           {test.COMMON_TMPDIR_NAME: shared_tmp})72        content = os.listdir(shared_tmp)73        self.assertEqual(len(content), 2, "The number of tests in manually "74                         "set teststmpdir is not 2 (%s):\n%s"75                         % (len(content), content))76    def tearDown(self):77        self.instrumented_test.remove()78        self.simple_test.remove()79        shutil.rmtree(self.tmpdir)80if __name__ == '__main__':...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!!
