Best Python code snippet using lisa_python
core.py
Source:core.py  
...26    """Provides quick and easy access to Grustnogram API"""27    _token = None28    def __init__(self) -> None:29        ...30    async def _validate_result(self, result: dict) -> None:31        if "err" not in result or not result["err"]:32            return33        if 100 in result["err"]:34            raise EmailExistsError("Specified email already exists")35        if 101 in result["err"]:36            raise LoginExistsError("Specified login already exists")37        if 102 in result["err"]:38            raise UserNotFoundError("Specified user not found")39        if 103 in result["err"]:40            raise BadCredentialsError("Specified password is invalid")41        if any(result["err"]):42            raise UnknownError(json.dumps(result, indent=4))43    async def login(self, login: str, password: str) -> bool:44        """45        Authentificate in Grustnogram46        :param login: Grustnogram login47        :param password: Grustnogram password48        """49        result = (50            await run_sync(51                requests.post,52                "https://api.grustnogram.ru/sessions",53                headers={54                    "accept": "application/json",55                    "content-type": "application/x-www-form-urlencoded",56                    "user-agent": "Python SDK",57                },58                data=json.dumps({"email": login, "password": password}).encode(),59            )60        ).json()61        self._validate_result(result)62        self._token = result["data"]["access_token"]63        return True64    async def register(65        self,66        nickname: str,67        email: str,68        password: str,69        phone: str,70        code_handler: Callable = lambda: input(71            "Our sad bot is calling you, enter 4 last digits: "72        ),73    ) -> bool:74        """75        Register a new account76        :param nickname: Nickname77        :param email: Email78        :param password: Password79        :param phone: Phone (will be checked btw)80        :param code_handler: Callable, used to get a code81        """82        result = (83            await run_sync(84                requests.post,85                "https://api.grustnogram.ru/users",86                headers={87                    "accept": "application/json",88                    "content-type": "application/x-www-form-urlencoded",89                    "user-agent": "Python SDK",90                },91                data=json.dumps(92                    {93                        "nickname": nickname,94                        "email": email,95                        "password": password,96                        "password_confirm": password,97                    }98                ).encode(),99            )100        ).json()101        self._validate_result(result)102        phone_key = result["data"]["phone_key"]103        result = (104            await run_sync(105                requests.post,106                "https://api.grustnogram.ru/callme",107                headers={108                    "accept": "application/json",109                    "content-type": "application/x-www-form-urlencoded",110                    "user-agent": "Python SDK",111                },112                data=json.dumps(113                    {114                        "phone_key": phone_key,115                        "phone": phone,116                    }117                ).encode(),118            )119        ).json()120        self._validate_result(result)121        code = code_handler()122        result = (123            await run_sync(124                requests.post,125                "https://api.grustnogram.ru/phoneactivate",126                headers={127                    "accept": "application/json",128                    "content-type": "application/x-www-form-urlencoded",129                    "user-agent": "Python SDK",130                },131                data=json.dumps(132                    {133                        "code": code,134                        "phone": phone,135                    }136                ).encode(),137            )138        ).json()139        self._validate_result(result)140        self._token = result["data"]["access_token"]141        return True142    async def like_post(self, post_id: int) -> bool:143        """144        Like a post145        :param post_id: Post ID146        """147        result = (148            await run_sync(149                requests.post,150                f"https://api.grustnogram.ru/posts/{post_id}/like",151                headers={152                    "accept": "application/json",153                    "content-type": "application/x-www-form-urlencoded",154                    "user-agent": "Python SDK",155                    "access-token": self._token,156                },157            )158        ).json()159        self._validate_result(result)160        return True161    async def dislike_post(self, post_id: int) -> bool:162        """163        Dislike a post164        :param post_id: Post ID165        """166        result = (167            await run_sync(168                requests.delete,169                f"https://api.grustnogram.ru/posts/{post_id}/like",170                headers={171                    "accept": "application/json",172                    "content-type": "application/x-www-form-urlencoded",173                    "user-agent": "Python SDK",174                    "access-token": self._token,175                },176            )177        ).json()178        self._validate_result(result)179        return True180    async def like_comment(self, comment_id: int) -> bool:181        """182        Like a comment183        :param comment_id: Comment ID184        """185        result = (186            await run_sync(187                requests.post,188                f"https://api.grustnogram.ru/comments/{comment_id}/like",189                headers={190                    "accept": "application/json",191                    "content-type": "application/x-www-form-urlencoded",192                    "user-agent": "Python SDK",193                    "access-token": self._token,194                },195            )196        ).json()197        self._validate_result(result)198        return True199    async def dislike_comment(self, comment_id: int) -> bool:200        """201        Dislike a comment202        :param comment_id: Comment ID203        """204        result = (205            await run_sync(206                requests.delete,207                f"https://api.grustnogram.ru/comments/{comment_id}/like",208                headers={209                    "accept": "application/json",210                    "content-type": "application/x-www-form-urlencoded",211                    "user-agent": "Python SDK",212                    "access-token": self._token,213                },214            )215        ).json()216        self._validate_result(result)217        return True218    async def comment_post(self, post_id: int, comment: str) -> Comment:219        """220        Leave a comment to post221        :param post_id: Post ID222        :param comment: Comment text223        """224        result = (225            await run_sync(226                requests.post,227                f"https://api.grustnogram.ru/posts/{post_id}/comments",228                headers={229                    "accept": "application/json",230                    "content-type": "application/x-www-form-urlencoded",231                    "user-agent": "Python SDK",232                    "access-token": self._token,233                },234                data=json.dumps({"comment": comment}).encode(),235            )236        ).json()237        self._validate_result(result)238        return Comment(239            result["data"]["id"],240            result["data"]["nickname"],241            result["data"]["comment"],242            result["data"]["created_at"],243        )244    async def delete_comment(self, comment_id: int) -> bool:245        """246        Leave a comment to post247        :param post_id: Post ID248        :param comment: Comment text249        """250        result = (251            await run_sync(252                requests.delete,253                f"https://api.grustnogram.ru/posts/comment/{comment_id}",254                headers={255                    "accept": "application/json",256                    "content-type": "application/x-www-form-urlencoded",257                    "user-agent": "Python SDK",258                    "access-token": self._token,259                },260            )261        ).json()262        self._validate_result(result)263        return True264    async def get_comments(265        self,266        post_id: int,267        limit: int = 10,268        offset: int = 0,269    ) -> List[Comment]:270        """271        Get comments of post272        :param post_id: Post ID273        """274        result = (275            await run_sync(276                requests.get,277                f"https://api.grustnogram.ru/posts/{post_id}/comments",278                headers={279                    "accept": "application/json",280                    "content-type": "application/x-www-form-urlencoded",281                    "user-agent": "Python SDK",282                    "access-token": self._token,283                },284                data=json.dumps({"limit": limit, "offset": offset}).encode(),285            )286        ).json()287        self._validate_result(result)288        return [289            Comment(290                comment["id"],291                comment["nickname"],292                comment["comment"],293                comment["created_at"],294            )295            for comment in result["data"]296        ]297    async def complaint(298        self,299        post_id: int,300        complaint_type: int,301        text: Optional[str] = None,302    ) -> bool:303        """304        Leave a complaint to the post305        :param post_id: Post ID306        :param type: Complaint type:307            1 - Unacceptable materials308            2 - Insults me309            3 - Insults Russia310        :param text: Optional: Complaint text311        """312        result = (313            await run_sync(314                requests.post,315                f"https://api.grustnogram.ru/posts/{post_id}/complaint",316                headers={317                    "accept": "application/json",318                    "content-type": "application/x-www-form-urlencoded",319                    "user-agent": "Python SDK",320                    "access-token": self._token,321                },322                data=json.dumps({"type": complaint_type, "text": text}).encode(),323            )324        ).json()325        self._validate_result(result)326        return True327    async def delete_post(328        self,329        post_id: int,330    ) -> bool:331        """332        Delete post333        :param post_id: Post ID334        """335        result = (336            await run_sync(337                requests.delete,338                f"https://api.grustnogram.ru/posts/{post_id}",339                headers={340                    "accept": "application/json",341                    "content-type": "application/x-www-form-urlencoded",342                    "user-agent": "Python SDK",343                    "access-token": self._token,344                },345            )346        ).json()347        self._validate_result(result)...closeness_centrality_test.py
Source:closeness_centrality_test.py  
...43            3: 0.75,44            4: 1.0,45            5: 0.0,46            6: 0.0}47        self._validate_result(result, expected_values)48    def test_weights_single_shortest_path(self):49        """Tests weighted closeness when only one shortest path present"""50        edges = self.context.frame.create(51            [(0, 1, 3), (0, 2, 2),52             (0, 3, 6), (0, 4, 4),53             (1, 3, 5), (1, 5, 5),54             (2, 4, 1), (3, 4, 2),55             (3, 5, 1), (4, 5, 4)],56            ["src", "dst", "weights"])57        vertices = self.context.frame.create(58            [[0], [1], [2], [3], [4], [5]], ["id"])59        graph = self.context.graph.create(vertices, edges)60        # validate centrality values61        result_frame = graph.closeness_centrality("weights", False)62        result = result_frame.to_pandas()63        expected_values = {64            0: 0.238,65            1: 0.176,66            2: 0.333,67            3: 0.667,68            4: 0.25,69            5: 0.0}70        self._validate_result(result, expected_values)71    def test_weights_multiple_shortest_paths(self):72        """Test centrality when multiple shortest paths exist"""73        result_frame = self.graph.closeness_centrality("weights", False)74        # validate centrality values75        expected_values = {76            0: 0.261,77            1: 0.0,78            2: 0.235,79            3: 0.333,80            4: 0.667,81            5: 0.0,82            6: 0.0}83        result = result_frame.to_pandas()84        self._validate_result(result, expected_values)85    def test_disconnected_edges(self):86        """Test closeness on graph with disconnected edges"""87        edges = self.context.frame.create(88            [['a', 'b'], ['a', 'c'],89             ['c', 'd'], ['c', 'e'],90             ['f', 'g'], ['g', 'h']],91            ['src', 'dst'])92        vertices = self.context.frame.create(93            [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h']], ['id'])94        graph = self.context.graph.create(vertices, edges)95        result_frame = graph.closeness_centrality(normalize=False)96        # validate centrality values97        expected_values = {98            'a': 0.667,99            'b': 0.0, 'c': 1.0, 'd': 0.0,100            'e': 0.0, 'f': 0.667, 'g': 1.0, 'h': 0.0}101        result = result_frame.to_pandas()102        self._validate_result(result, expected_values)103    def test_normalize(self):104        """Test normalized centrality"""105        result_frame = self.graph.closeness_centrality(normalize=True)106        result = result_frame.to_pandas()107        # validate centrality values108        expected_values = {109            0: 0.5,110            1: 0.0,111            2: 0.444,112            3: 0.375,113            4: 0.333,114            5: 0.0,115            6: 0.0}116        self._validate_result(result, expected_values)117    def test_negative_edges(self):118        """Test closeness on graph with disconnected edges"""119        edges = self.context.frame.create(120            [['a', 'b', 10], ['a', 'c', 12],121             ['c', 'd', -1], ['c', 'e', 5]],122            ['src', 'dst', 'weight'])123        vertices = self.context.frame.create(124            [['a'], ['b'], ['c'], ['d'], ['e']], ['id'])125        graph = self.context.graph.create(vertices, edges)126        with self.assertRaisesRegexp(127                Exception, "edge weight cannot be negative"):128            graph.closeness_centrality(edge_weight='weight', normalize=False)129    def test_bad_weights_column_name(self):130        """Should throw exception when bad weights column name given"""131        with self.assertRaisesRegexp(132                Exception, "Field \"BAD\" does not exist"):133            self.graph.closeness_centrality("BAD")134    def _validate_result(self, result, expected_values):135        for i, row in result.iterrows():136            id = row['id']137            self.assertAlmostEqual(138                row["closeness_centrality"], expected_values[id], delta=0.1)139if __name__ == "__main__":...test_match.py
Source:test_match.py  
2from dgcastle.data import match3from dgcastle.exceptions import ValidationException4class TestResultValidation(unittest.TestCase):5    def test_tie(self):6        self.assertEqual(match._validate_result('tie'), 'tie')7        self.assertEqual(match._validate_result('as'), 'as')8    def test_XupFormat(self):9        self.assertEqual(match._validate_result('1up'), '1up')10        self.assertEqual(match._validate_result('2up'), '2up')11        self.assertRaises(ValidationException, match._validate_result, '0up')12        self.assertRaises(ValidationException, match._validate_result, '3up')13        self.assertRaises(ValidationException, match._validate_result, '10up')14        self.assertRaises(ValidationException, match._validate_result, '-1up')15        self.assertRaises(ValidationException, match._validate_result, 'twoup')16        self.assertRaises(ValidationException, match._validate_result, 'up')17        self.assertRaises(ValidationException, match._validate_result, '1up2')18        self.assertRaises(ValidationException, match._validate_result, '1')19    def test_XandYFormat(self):20        self.assertEqual(match._validate_result('2&1'), '2&1')21        self.assertEqual(match._validate_result('3&1'), '3&1')22        self.assertRaises(ValidationException, match._validate_result, '4&1')23        self.assertEqual(match._validate_result('4&2'), '4&2')24        self.assertEqual(match._validate_result('10&8'), '10&8')25        self.assertEqual(match._validate_result('2+1'), '2+1')26        self.assertRaises(ValidationException, match._validate_result, '10&7')27        self.assertRaises(ValidationException, match._validate_result, '4&')28        self.assertRaises(ValidationException, match._validate_result, '&1')29        self.assertRaises(ValidationException, match._validate_result, '&')30        self.assertRaises(ValidationException, match._validate_result, '4')31        self.assertRaises(ValidationException, match._validate_result, '1')32        self.assertRaises(ValidationException, match._validate_result, '1&-1')33        self.assertRaises(ValidationException, match._validate_result, '4.1&1')34        self.assertRaises(ValidationException, match._validate_result, '4&1.1')35        self.assertRaises(ValidationException, match._validate_result, '3&2&1')36        self.assertRaises(ValidationException, match._validate_result, '2&+1')37        self.assertRaises(ValidationException, match._validate_result, '2+&1')38    def test_challongeFormatting(self):39        self.assertEqual(match._validate_result('2-1'), '2&1')40        self.assertEqual(match._validate_result('1-2'), '2&1')41        self.assertEqual(match._validate_result('2-0'), '2up')42        self.assertEqual(match._validate_result('0-2'), '2up')43        self.assertRaises(ValidationException, match._validate_result, '0-0')44        self.assertRaises(ValidationException, match._validate_result, '0-')45        self.assertRaises(ValidationException, match._validate_result, '-0')46        self.assertRaises(ValidationException, match._validate_result, '5-1')47        self.assertRaises(ValidationException, match._validate_result, '0--0')...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!!
