├── .flake8 ├── .github └── workflows │ └── python-build.yml ├── .gitignore ├── .isort.cfg ├── .travis.yml ├── CONTRIBUTORS.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── README.rst ├── _config.yml ├── codechefcli ├── __init__.py ├── __main__.py ├── auth.py ├── decorators.py ├── helpers.py ├── problems.py ├── teams.py └── users.py ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_auth_entry.py ├── test_helpers.py ├── test_problems.py ├── test_teams.py ├── test_users.py └── utils.py └── tox.ini /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = 3 | venv 4 | __pycache__ 5 | -------------------------------------------------------------------------------- /.github/workflows/python-build.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python build 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | matrix: 18 | os: [ubuntu-16.04, ubuntu-18.04, ubuntu-20.04, macos-latest, windows-latest] 19 | python-version: [3.6, 3.7, 3.8] 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Set up ${{ matrix.python-version }} 24 | uses: actions/setup-python@v2 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Install dependencies 28 | run: | 29 | python -m pip install --upgrade pip 30 | python -m pip install flake8 pytest wheel setuptools 31 | python -m pip install -r requirements.txt 32 | - name: Lint with flake8 33 | run: | 34 | # stop the build if there are Python syntax errors or undefined names 35 | python -m flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 36 | # exit-zero treats all errors as warnings. 37 | python -m flake8 . --count --exit-zero --max-line-length=100 --statistics 38 | - name: Test with pytest 39 | run: | 40 | python -m pytest 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | coverage/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | 86 | # virtualenv 87 | .venv 88 | venv/ 89 | ENV/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | **/.pytest_cache/ 104 | -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | skip_glob=venv/* 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - '3.6' 4 | - '3.7' 5 | - '3.8' 6 | install: pip install -r requirements.txt 7 | script: 8 | - flake8 . --max-line-length=100 9 | - isort -w 100 10 | - pytest -v 11 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | * [Paras Rastogi](https://github.com/parascoder1) 2 | * [@jain-aayush](https://github.com/jain-aayush) 3 | * [@j-tesla](https://github.com/j-tesla) 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include codechefcli * 2 | include LICENSE README.rst requirements.txt 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodeChef CLI [![PyPI version](https://badge.fury.io/py/codechefcli.svg)](https://badge.fury.io/py/codechefcli) [![Build Status](https://travis-ci.org/sk364/codechef-cli.svg?branch=master)](https://travis-ci.org/sk364/codechef-cli) 2 | 3 | A command-line tool for querying and submitting problems on [CodeChef](https://www.codechef.com/). 4 | 5 | # Features 6 | * Search & submit problems 7 | * Search solutions 8 | * Search users, ratings, tags and teams 9 | 10 | # Requirements 11 | * python (>= 3.6) 12 | * [requests_html](https://github.com/psf/requests-html/) (0.10.0) 13 | 14 | # Installation 15 | ``` 16 | pip install codechefcli 17 | ``` 18 | 19 | # Usage 20 | 21 | ``` 22 | # See full list of options: 23 | codechefcli --help 24 | 25 | # Login to CodeChef 26 | codechefcli --login 27 | 28 | # Get problem description: 29 | codechefcli --problem WEICOM 30 | 31 | # Get contests: 32 | codechefcli --contests 33 | 34 | # Submit a problem: 35 | codechefcli --submit WEICOM /path/to/solution/file C++ 36 | ``` 37 | 38 | # Linting & Testing 39 | 40 | ``` 41 | # run tests 42 | pytest -v 43 | 44 | # lint 45 | isort 46 | flake8 . --max-line-length=100 47 | ``` 48 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | CodeChef CLI |PyPI version| |Build Status| 2 | ========================================== 3 | 4 | A command-line tool for querying and submitting problems on `CodeChef`_. 5 | 6 | Features 7 | ======== 8 | 9 | - Get problem description 10 | - Get user information 11 | - Submit problems 12 | - Search problems in contest, by category, or by tags 13 | - Get ratings 14 | - Get problem solutions 15 | - Get contests 16 | 17 | Installation 18 | ============ 19 | 20 | Available on pip. Install using the command: 21 | 22 | pip install codechefcli 23 | 24 | Usage 25 | ===== 26 | 27 | See full list of options: 28 | 29 | codechefcli --help 30 | 31 | Get problem description: 32 | 33 | codechefcli --problem WEICOM 34 | 35 | Get contests: 36 | 37 | codechefcli --contests 38 | 39 | Submit a problem: 40 | 41 | codechefcli --submit WEICOM /path/to/solution/file C++ 42 | 43 | .. _CodeChef: https://www.codechef.com/ 44 | 45 | .. |PyPI version| image:: https://badge.fury.io/py/codechefcli.svg 46 | :target: https://badge.fury.io/py/codechefcli 47 | .. |Build Status| image:: https://api.travis-ci.org/sk364/codechef-cli.svg?branch=master 48 | :target: https://api.travis-ci.org/sk364/codechef-cli -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /codechefcli/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sk364/codechef-cli/fa678861a51ee374029a96ffb15c43dc741f22c4/codechefcli/__init__.py -------------------------------------------------------------------------------- /codechefcli/__main__.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import sys 3 | import bs4 4 | from bs4 import BeautifulSoup 5 | 6 | from rich.console import Console 7 | from rich.style import Style 8 | from rich.theme import Theme 9 | 10 | from codechefcli.auth import login, logout 11 | from codechefcli.helpers import print_response 12 | from problems import (RESULT_CODES, get_contest_problems, get_contests, get_description, 13 | get_ratings, get_solution, get_solutions, get_tags, 14 | search_problems, submit_problem) 15 | from codechefcli.teams import get_team 16 | from codechefcli.users import get_user 17 | 18 | GENERIC_RESP = {"code": 500, "data": "Unexpected stuff is happening here"} 19 | CC_PRACTICE = "PRACTICE" 20 | SEARCH_TYPES = ['school', 'easy', 'medium', 'hard', 'challenge', 'extcontest'] 21 | INSTITUTION_TYPES = ['School', 'Organization', 'College'] 22 | INVALID_USERNAME = '##no_login##' 23 | DEFAULT_PAGE = 1 24 | DEFAULT_NUM_LINES = 20 25 | 26 | #defining custom themes 27 | themes = Theme({"data":"bold #a1065b","error":"bold red"}) 28 | c = Console(theme=themes) 29 | 30 | def create_parser(): 31 | parser = argparse.ArgumentParser() 32 | 33 | # auth 34 | parser.add_argument('--login', '-l', required=False, nargs='?', metavar='username', 35 | default=INVALID_USERNAME) 36 | parser.add_argument('--logout', required=False, action='store_true') 37 | parser.add_argument('--disconnect-sessions', required=False, action='store_true', 38 | default=False, help='Disconnects active sessions, \ 39 | when session limit exceeded.') 40 | 41 | # user & team info 42 | parser.add_argument('--user', '-u', required=False, metavar='', 43 | help='Get user information. This arg can also be used for filtering data.') 44 | parser.add_argument('--team', required=False, metavar='', 45 | help='Get team information.') 46 | 47 | # ratings & its filters 48 | parser.add_argument('--ratings', required=False, action="store_true", help='Displays user \ 49 | ratings. Filters: `--country`, `--institution`, `--institution-type`') 50 | parser.add_argument('--country', required=False, metavar='', 51 | help='Country filter. Eg: India, "United States", etc.') 52 | parser.add_argument('--institution', required=False, metavar='', 53 | help='Institution Filter') 54 | parser.add_argument('--institution-type', required=False, metavar='', 55 | choices=INSTITUTION_TYPES, help='Institution Type Filter') 56 | 57 | # problems: get, submit & search 58 | parser.add_argument('--problem', required=False, metavar='', 59 | help='Get Problem Description.') 60 | parser.add_argument('--submit', nargs=3, required=False, 61 | metavar=('', '', ''), 62 | help='Eg: C++, C, Python, Python3, java, etc. (case-insensitive)') 63 | parser.add_argument('--search', required=False, metavar='', choices=SEARCH_TYPES, 64 | help='Search practice problems filter (case-insensitive)') 65 | 66 | # contests and its filters 67 | parser.add_argument('--contests', required=False, action='store_true', 68 | help='Get All Contests') 69 | parser.add_argument('--contest', required=False, metavar='', 70 | help='Get Contest Problems') 71 | parser.add_argument('--show-past', required=False, action='store_true', 72 | help='Shows only past contests.') 73 | 74 | # solutions & its filters 75 | parser.add_argument('--solutions', required=False, metavar='', 76 | help='Get problem\'s solutions list') 77 | parser.add_argument('--solution', required=False, metavar='', 78 | help='Get specific solution') 79 | parser.add_argument('--language', required=False, 80 | help='Language filter. Eg: C++, C, python3, java. (case-insensitive)') 81 | parser.add_argument('--result', '-r', required=False, choices=RESULT_CODES.keys(), 82 | help='Result type filter (case-insensitive)') 83 | 84 | # tags 85 | parser.add_argument('--tags', required=False, nargs='*', metavar="", 86 | help='No args: get all tags. Add args to get tagged problems') 87 | 88 | # common 89 | parser.add_argument('--lines', required=False, metavar='', default=DEFAULT_NUM_LINES, 90 | type=int, help=f'Limit number of lines. Default: {DEFAULT_NUM_LINES}') 91 | parser.add_argument('--sort', required=False, metavar='', 92 | help='utility argument to sort the results') 93 | parser.add_argument('--order', required=False, metavar='', default='asc', 94 | help='utility argument to specify the sorting order; default: `asc` \ 95 | `asc` for ascending; `desc` for descending') 96 | parser.add_argument('--page', '-p', required=False, metavar='', default=DEFAULT_PAGE, 97 | type=int, help=f'Gets specific page. Default: {DEFAULT_PAGE}') 98 | 99 | return parser 100 | 101 | 102 | def main(argv=None): 103 | if argv is None: 104 | argv = sys.argv 105 | 106 | try: 107 | parser = create_parser() 108 | args = parser.parse_args(argv[1:]) 109 | 110 | username = args.login 111 | is_logout = args.logout 112 | disconnect_sessions = args.disconnect_sessions 113 | 114 | user = args.user 115 | team = args.team 116 | 117 | ratings = args.ratings 118 | country = args.country 119 | institution = args.institution 120 | institution_type = args.institution_type 121 | 122 | problem_code = args.problem 123 | submit = args.submit 124 | search = args.search 125 | 126 | contest = args.contest 127 | contests = args.contests 128 | show_past = args.show_past 129 | 130 | tags = args.tags 131 | 132 | solutions = args.solutions 133 | solution_code = args.solution 134 | language = args.language 135 | result = args.result 136 | 137 | lines = args.lines 138 | sort = args.sort 139 | order = args.order 140 | page = args.page 141 | 142 | resps = [] 143 | 144 | # function stylize to style the output 145 | def stylize(resps) : 146 | theme='data' 147 | if resps.get('code: ')== 404 : 148 | theme='error' 149 | 150 | remain=[] 151 | print() 152 | for ele in resps.keys() : 153 | if len(ele) > 30 or len(str(resps[ele])) > 30 : 154 | remain.append(ele) 155 | else : 156 | c.print(ele.upper(),end="",style=theme) 157 | c.print(resps[ele],end="") 158 | print(" "*10,end="") 159 | print() 160 | print() 161 | for ele in remain : 162 | c.print(ele.upper(),end="",style=theme) 163 | result=resps[ele] 164 | if ele=="Description: ": 165 | result = BeautifulSoup(result,"html.parser") 166 | im_urls = result.find_all('img') 167 | c.print(result.text) 168 | for url in im_urls : 169 | c.print("image: "+url['src']) 170 | continue 171 | c.print(result) 172 | print() 173 | return 174 | 175 | if username != INVALID_USERNAME: 176 | resps = login(username=username, disconnect_sessions=disconnect_sessions) 177 | 178 | elif is_logout: 179 | resps = logout() 180 | 181 | if problem_code: 182 | resps = get_description(problem_code, contest or CC_PRACTICE) 183 | stylize(resps) 184 | return 185 | 186 | elif submit: 187 | resps = submit_problem(*submit) 188 | 189 | elif search: 190 | resps = search_problems(sort, order, search) 191 | 192 | elif contest: 193 | resps = get_contest_problems(sort, order, contest) 194 | 195 | elif contests: 196 | resps = get_contests(show_past) 197 | 198 | elif isinstance(tags, list): 199 | resps = get_tags(sort, order, tags) 200 | 201 | elif solutions: 202 | resps = get_solutions(sort, order, solutions, page, language, result, user) 203 | 204 | elif solution_code: 205 | resps = get_solution(solution_code) 206 | 207 | elif user: 208 | resps = get_user(user) 209 | 210 | elif team: 211 | resps = get_team(team) 212 | 213 | elif ratings: 214 | resps = get_ratings(sort, order, country, institution, institution_type, page, lines) 215 | 216 | else: 217 | parser.print_help() 218 | 219 | if not resps: 220 | resps = [GENERIC_RESP] 221 | 222 | for resp in resps: 223 | print_response(**resp) 224 | 225 | return resps 226 | except KeyboardInterrupt: 227 | print('\nBye.') 228 | return [{"data": "\nBye."}] 229 | return [{"data": "0"}] 230 | 231 | 232 | if __name__ == '__main__': 233 | main(sys.argv) 234 | -------------------------------------------------------------------------------- /codechefcli/auth.py: -------------------------------------------------------------------------------- 1 | import os 2 | from getpass import getpass 3 | 4 | from requests_html import HTMLSession 5 | 6 | from codechefcli.decorators import login_required 7 | from codechefcli.helpers import (COOKIES_FILE_PATH, CSRF_TOKEN_INPUT_ID, get_csrf_token, 8 | init_session_cookie, request, set_session_cookies) 9 | 10 | CSRF_TOKEN_MISSING = 'No CSRF Token found' 11 | SESSION_LIMIT_FORM_ID = '#session-limit-page' 12 | LOGIN_FORM_ID = 'ajax_login_form' 13 | LOGOUT_BUTTON_CLASS = '.logout-link' 14 | EMPTY_AUTH_DATA_MSG = 'Username/Password field cannot be left blank.' 15 | SESSION_LIMIT_MSG = 'Session limit exceeded!' 16 | INCORRECT_CREDS_MSG = 'Incorrect Credentials!' 17 | LOGIN_SUCCESS_MSG = 'Successfully logged in!' 18 | LOGOUT_SUCCESS_MSG = 'Successfully logged out!' 19 | LOGIN_URL = "https://www.codechef.com/api/codechef/login" 20 | 21 | 22 | def is_logged_in(resp): 23 | return not bool(resp.html.find(LOGIN_FORM_ID)) 24 | 25 | 26 | def get_form_url(rhtml): 27 | form = rhtml.find(SESSION_LIMIT_FORM_ID, first=True) 28 | return form and form.element.action 29 | 30 | 31 | def get_other_active_sessions(rhtml): 32 | form = rhtml.find(SESSION_LIMIT_FORM_ID, first=True) 33 | inputs = form.find('input') 34 | inputs = inputs[:-5] + inputs[-4:] 35 | return {inp.element.name: dict(inp.element.items()).get('value', '') for inp in inputs} 36 | 37 | 38 | def disconnect_active_sessions(session, login_resp_html): 39 | token = get_csrf_token(login_resp_html, CSRF_TOKEN_INPUT_ID) 40 | post_url = get_form_url(login_resp_html) 41 | other_active_sessions = get_other_active_sessions(login_resp_html) 42 | 43 | resp = request( 44 | session=session, method='POST', url=post_url, data=other_active_sessions, token=token) 45 | if resp and hasattr(resp, 'status_code') and resp.status_code == 200: 46 | return [{'data': LOGIN_SUCCESS_MSG}] 47 | return [{'code': 503}] 48 | 49 | 50 | def save_session_cookies(session, username): 51 | session.cookies.set_cookie(init_session_cookie("username", username)) 52 | session.cookies.save(ignore_expires=True, ignore_discard=True) 53 | 54 | 55 | def make_login_req(username, password, disconnect_sessions): 56 | with HTMLSession() as session: 57 | set_session_cookies(session) 58 | 59 | data = { 60 | 'name': username, 61 | 'pass': password, 62 | 'form_id': LOGIN_FORM_ID, 63 | } 64 | 65 | resp = request(url=LOGIN_URL, session=session, method='POST', data=data) 66 | resp_json = resp.json() 67 | 68 | if resp.status_code == 200: 69 | if resp_json.get('status') == "success": 70 | save_session_cookies(session, username) 71 | return [{'data': LOGIN_SUCCESS_MSG}] 72 | return [{'data': INCORRECT_CREDS_MSG, 'code': 400}] 73 | return [{'code': 503}] 74 | 75 | 76 | def login(username=None, password=None, disconnect_sessions=False): 77 | if username is None: 78 | username = input('Username: ') 79 | if password is None: 80 | password = getpass() 81 | 82 | if username and password: 83 | return make_login_req(username, password, disconnect_sessions) 84 | return [{'data': EMPTY_AUTH_DATA_MSG, 'code': 400}] 85 | 86 | 87 | @login_required 88 | def logout(session=None): 89 | resp = request(session=session, url='/logout') 90 | if resp.status_code == 200: 91 | if os.path.exists(COOKIES_FILE_PATH): 92 | os.remove(COOKIES_FILE_PATH) 93 | return [{'data': LOGOUT_SUCCESS_MSG}] 94 | return [{'code': 503}] 95 | -------------------------------------------------------------------------------- /codechefcli/decorators.py: -------------------------------------------------------------------------------- 1 | import os 2 | from functools import wraps 3 | from http.cookiejar import LWPCookieJar 4 | 5 | from codechefcli.helpers import COOKIES_FILE_PATH 6 | 7 | 8 | def login_required(func): 9 | @wraps(func) 10 | def wrapper(*args, **kwargs): 11 | is_logged_in = False 12 | if os.path.exists(COOKIES_FILE_PATH): 13 | cookiejar = LWPCookieJar(filename=COOKIES_FILE_PATH) 14 | cookiejar.load() 15 | 16 | if len(cookiejar): 17 | is_logged_in = True 18 | else: 19 | os.remove(COOKIES_FILE_PATH) 20 | if is_logged_in is False: 21 | return [{'code': 401}] 22 | return func(*args, **kwargs) 23 | return wrapper 24 | 25 | 26 | def sort_it(func): 27 | def wrapper(*args, **kwargs): 28 | sort = args[0] and args[0].upper() 29 | order_type = args[1] 30 | 31 | resps = func(*args, **kwargs) 32 | for resp in resps: 33 | if resp.get('code', 200) == 200 and resp.get('data_type') == 'table': 34 | if sort is not None: 35 | all_rows = resp['data'] 36 | heading = all_rows[0] 37 | data_rows = all_rows[1:] 38 | if not data_rows: 39 | continue 40 | if sort in heading: 41 | index = heading.index(sort) 42 | 43 | if order_type in ['asc', 'desc']: 44 | reverse = False 45 | 46 | if order_type == 'desc': 47 | reverse = True 48 | 49 | if data_rows[0][index].isdigit(): 50 | for data_row in data_rows: 51 | if data_row[index].isdigit(): 52 | data_row[index] = int(data_row[index]) 53 | else: 54 | data_row[index] = 0 55 | 56 | data_rows.sort(key=lambda x: x[index], reverse=reverse) 57 | 58 | for data_row in data_rows: 59 | data_row[index] = str(data_row[index]) 60 | else: 61 | data_rows.sort(key=lambda x: x[index], reverse=reverse) 62 | 63 | data_rows.insert(0, heading) 64 | resp['data'] = data_rows 65 | else: 66 | return [{ 67 | 'code': 404, 68 | 'data': 'Wrong order argument entered.', 69 | 'data_type': 'text' 70 | }] 71 | else: 72 | return [{ 73 | 'code': 404, 74 | 'data': 'Wrong sorting argument entered.', 75 | 'data_type': 'text' 76 | }] 77 | return resps 78 | return wraps(func)(wrapper) 79 | -------------------------------------------------------------------------------- /codechefcli/helpers.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | from http.cookiejar import Cookie, LWPCookieJar 4 | from os.path import expanduser 5 | from pydoc import pager 6 | 7 | from requests import ReadTimeout 8 | from requests.exceptions import ConnectionError 9 | from requests_html import HTMLSession 10 | 11 | CSRF_TOKEN_INPUT_ID = 'edit-csrfToken' 12 | MIN_NUM_SPACES = 3 13 | BASE_URL = 'https://www.codechef.com' 14 | SERVER_DOWN_MSG = 'Please try again later. Seems like CodeChef server is down!' 15 | INTERNET_DOWN_MSG = 'Nothing to show. Check your internet connection.' 16 | UNAUTHORIZED_MSG = 'You are not logged in.' 17 | COOKIES_FILE_PATH = expanduser('~') + '/.cookies' 18 | BCOLORS = { 19 | 'HEADER': '\033[95m', 20 | 'BLUE': '\033[94m', 21 | 'GREEN': '\033[92m', 22 | 'WARNING': '\033[93m', 23 | 'FAIL': '\033[91m', 24 | 'ENDC': '\033[0m', 25 | 'BOLD': '\033[1m', 26 | 'UNDERLINE': '\033[4m' 27 | } 28 | 29 | 30 | def set_session_cookies(session): 31 | session.cookies = LWPCookieJar(filename=COOKIES_FILE_PATH) 32 | 33 | 34 | def get_session(): 35 | session = HTMLSession() 36 | 37 | if os.path.exists(COOKIES_FILE_PATH): 38 | set_session_cookies(session) 39 | session.cookies.load(ignore_discard=True, ignore_expires=True) 40 | return session 41 | 42 | 43 | def init_session_cookie(name, value, **kwargs): 44 | return Cookie(version=0, name=name, value=value, port=None, port_specified=False, 45 | domain='www.codechef.com', domain_specified=False, domain_initial_dot=False, 46 | path='/', path_specified=True, secure=False, expires=None, discard=False, 47 | comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False) 48 | 49 | 50 | def get_username(): 51 | session = get_session() 52 | 53 | for index, cookie in enumerate(session.cookies): 54 | if cookie.name == 'username': 55 | return cookie.value 56 | 57 | return None 58 | 59 | 60 | def request(session=None, method="GET", url="", token=None, **kwargs): 61 | if not session: 62 | session = get_session() 63 | if token: 64 | session.headers = getattr(session, 'headers') or {} 65 | session.headers.update({'X-CSRF-Token': token}) 66 | 67 | if BASE_URL not in url: 68 | url = f'{BASE_URL}{url}' 69 | 70 | try: 71 | return session.request(method=method, url=url, timeout=(15, 15), **kwargs) 72 | except (ConnectionError, ReadTimeout): 73 | print(INTERNET_DOWN_MSG) 74 | sys.exit(1) 75 | 76 | 77 | def html_to_list(table): 78 | if not table: 79 | return [] 80 | 81 | rows = table.find('tr') 82 | data_rows = [[header.text.strip().upper() for header in rows[0].find('th, td')]] 83 | for row in rows[1:]: 84 | data_rows.append([col.text.strip() for col in row.find('td')]) 85 | return data_rows 86 | 87 | 88 | def get_col_max_lengths(data_rows, num_cols): 89 | max_len_in_cols = [0] * num_cols 90 | for row in data_rows: 91 | for index, val in enumerate(row): 92 | if len(val) > max_len_in_cols[index]: 93 | max_len_in_cols[index] = len(val) 94 | return max_len_in_cols 95 | 96 | 97 | def print_table(data_rows, min_num_spaces=MIN_NUM_SPACES, is_pager=True): 98 | if len(data_rows) == 0: 99 | return 100 | 101 | max_len_in_cols = get_col_max_lengths(data_rows, len(data_rows[0])) 102 | 103 | table = [] 104 | for row in data_rows: 105 | _row = [] 106 | for index, val in enumerate(row): 107 | num_spaces = max_len_in_cols[index] - len(val) + min_num_spaces 108 | _row.append(val + (num_spaces * ' ')) 109 | table.append("".join(_row)) 110 | 111 | table_str = '\n\n'.join(table) 112 | if is_pager: 113 | pager(table_str) 114 | print(table_str) 115 | return table_str 116 | 117 | 118 | def style_text(text, color=None): 119 | if color is None or BCOLORS.get(color) is None: 120 | return text 121 | 122 | return '{0}{1}{2}'.format(BCOLORS[color], text, BCOLORS['ENDC']) 123 | 124 | 125 | def print_response_util(data, extra, data_type, color, is_pager=True): 126 | if data is None and extra is None: 127 | no_data_msg = style_text('Nothing to show.', 'WARNING') 128 | print(no_data_msg) 129 | return no_data_msg, None 130 | 131 | return_val = None 132 | if data is not None: 133 | if data_type == 'table': 134 | return_val = print_table(data, is_pager=is_pager) 135 | elif data_type == 'text': 136 | if is_pager: 137 | pager(style_text(data, color)) 138 | return_val = style_text(data, color) 139 | print(return_val) 140 | 141 | styled_extra = None 142 | if extra is not None: 143 | styled_extra = style_text(extra, color) 144 | print(styled_extra) 145 | return return_val, styled_extra 146 | 147 | 148 | def print_response(data_type='text', code=200, data=None, extra=None, **kwargs): 149 | color = None 150 | 151 | if code == 503: 152 | if not data: 153 | data = SERVER_DOWN_MSG 154 | color = 'FAIL' 155 | elif code == 404 or code == 400: 156 | color = 'WARNING' 157 | elif code == 401: 158 | if not data: 159 | data = UNAUTHORIZED_MSG 160 | color = 'FAIL' 161 | 162 | is_pager = False 163 | if not hasattr(kwargs, 'is_pager') and data_type == 'table': 164 | is_pager = True 165 | else: 166 | is_pager = kwargs.get('is_pager', False) 167 | 168 | return print_response_util(data, extra, data_type, color, is_pager=is_pager) 169 | 170 | 171 | def get_csrf_token(rhtml, selector): 172 | token = rhtml.find(f"#{selector}", first=True) 173 | return token and hasattr(token.element, 'value') and token.element.value 174 | -------------------------------------------------------------------------------- /codechefcli/problems.py: -------------------------------------------------------------------------------- 1 | import math 2 | import re 3 | 4 | from requests_html import HTML 5 | 6 | from codechefcli.auth import is_logged_in 7 | from codechefcli.decorators import login_required, sort_it 8 | from codechefcli.helpers import (BASE_URL, CSRF_TOKEN_INPUT_ID, SERVER_DOWN_MSG, get_csrf_token, 9 | html_to_list, request, style_text) 10 | 11 | LANGUAGE_SELECTOR = "#language" 12 | INVALID_PROBLEM_CODE_MSG = 'Invalid Problem Code.' 13 | PAGE_INFO_CLASS = '.pageinfo' 14 | PROBLEM_SUBMISSION_FORM_ID = '#problem-submission' 15 | PROBLEM_SUB_DATA_FORM_ID = 'problem_submission' 16 | PROBLEM_SUBMISSION_INPUT_ID = '#edit-problem-submission-form-token' 17 | LANGUAGE_DROPDOWN_ID = '#edit-language' 18 | COMPILATION_ERROR_CLASS = '.cc-error-txt' 19 | PROBLEM_LIST_TABLE_HEADINGS = ['CODE', 'NAME', 'SUBMISSION', 'ACCURACY'] 20 | RESULT_CODES = {'AC': 15, 'WA': 14, 'TLE': 13, 'RTE': 12, 'CTE': 11} 21 | RATINGS_TABLE_HEADINGS = ['GLOBAL(COUNTRY)', 'USER NAME', 'RATING', 'GAIN/LOSS'] 22 | SOLUTION_ERR_MSG_CLASS = '.err-message' 23 | INVALID_SOLUTION_ID_MSG = "Invalid solution ID" 24 | 25 | 26 | def get_description(problem_code, contest_code): 27 | url = f'/api/contests/{contest_code}/problems/{problem_code}' 28 | resp = request(url=url) 29 | 30 | try: 31 | resp_json = resp.json() 32 | except ValueError: 33 | return [{'code': 503}] 34 | 35 | if resp_json["status"] == "success": 36 | problem = { 37 | 'Name: ': resp_json.get('problem_name', ''), 38 | "Author: " : resp_json.get('problem_author', ''), 39 | "Date Added: " : resp_json.get('date_added', ''), 40 | "Max Time Limit: ": f"{resp_json.get('max_timelimit', '')} secs", 41 | "Source Limit: " : f"{resp_json.get('source_sizelimit', '')} Bytes", 42 | "Languages: " : resp_json.get('languages_supported', ''), 43 | "Description: ": resp_json.get("body", ''), #re.sub(r'(<|<\/)\w+>', '', 44 | } 45 | if resp_json.get('tags'): 46 | problem['Tags: ']= " ".join([tag.text for tag in HTML(html=resp_json['tags']).find('a')]) 47 | 48 | if resp_json.get('editorial_url'): 49 | problem['Editorial: '] = resp_json['editorial_url'] 50 | 51 | return problem 52 | elif resp_json["status"] == "error": 53 | problem= { 54 | 'data: ': 'Problem not found. Use `--search` to search in a specific contest', 55 | 'code: ': 404 56 | } 57 | return problem 58 | return [{'code': 503}] 59 | 60 | 61 | def get_form_token(rhtml): 62 | form = rhtml.find(PROBLEM_SUBMISSION_FORM_ID, first=True) 63 | inp = form and form.find(PROBLEM_SUBMISSION_INPUT_ID, first=True) 64 | input_element = inp and hasattr(inp, 'element') and inp.element 65 | return input_element is not None and hasattr(input_element, 'value') and input_element.value 66 | 67 | 68 | def get_status_table(status_code): 69 | resp = request(url=f'/error_status_table/{status_code}') 70 | if resp.status_code != 200 or not resp.text: 71 | return 72 | return resp.html 73 | 74 | 75 | def get_compilation_error(status_code): 76 | resp = request(url=f'/view/error/{status_code}') 77 | if resp.status_code == 200: 78 | return resp.html.find(COMPILATION_ERROR_CLASS, first=True).text 79 | return SERVER_DOWN_MSG 80 | 81 | 82 | def get_language_code(rhtml, language): 83 | form = rhtml.find(PROBLEM_SUBMISSION_FORM_ID, first=True) 84 | languages_dropdown = form.find(LANGUAGE_DROPDOWN_ID, first=True) 85 | for option in languages_dropdown.find('option'): 86 | if language.lower() + '(' in option.text.lower(): 87 | return dict(option.element.items())['value'] 88 | 89 | 90 | @login_required 91 | def submit_problem(problem_code, solution_file, language): 92 | url = f'/submit/{problem_code}' 93 | get_resp = request(url=url) 94 | 95 | if not is_logged_in(get_resp): 96 | return [{"code": 401, "data": "This session has been disconnected. Login again."}] 97 | 98 | if get_resp.status_code == 200: 99 | rhtml = get_resp.html 100 | form_token = get_form_token(rhtml) 101 | language_code = get_language_code(rhtml, language) 102 | csrf_token = get_csrf_token(rhtml, CSRF_TOKEN_INPUT_ID) 103 | 104 | if language_code is None: 105 | return [{'code': 400, 'data': 'Invalid language.'}] 106 | else: 107 | return [{'code': 503}] 108 | 109 | try: 110 | solution_file_obj = open(solution_file) 111 | except IOError: 112 | return [{'data': 'Solution file not found.', 'code': 400}] 113 | 114 | data = { 115 | 'language': language_code, 116 | 'problem_code': problem_code, 117 | 'form_id': PROBLEM_SUB_DATA_FORM_ID, 118 | 'form_token': form_token 119 | } 120 | files = {'files[sourcefile]': solution_file_obj} 121 | 122 | post_resp = request(method='POST', url=url, data=data, files=files) 123 | if post_resp.status_code == 200: 124 | print(style_text('Submitting code...\n', 'BLUE')) 125 | 126 | status_code = post_resp.url.split('/')[-1] 127 | url = f'/get_submission_status/{status_code}' 128 | print(style_text('Fetching results...\n', 'BLUE')) 129 | 130 | max_tries = 3 131 | num_tries = 0 132 | while True: 133 | resp = request(url=url, token=csrf_token) 134 | num_tries += 1 135 | 136 | try: 137 | status_json = resp.json() 138 | except ValueError: 139 | if num_tries == max_tries: 140 | return [{'code': 503}] 141 | continue 142 | 143 | result_code = status_json['result_code'] 144 | 145 | if result_code != 'wait': 146 | data = '' 147 | if result_code == 'compile': 148 | error_msg = get_compilation_error(status_code) 149 | data = style_text(f'Compilation error.\n{error_msg}', 'FAIL') 150 | elif result_code == 'runtime': 151 | data = style_text(f"Runtime error. {status_json.get('signal', '')}\n", 'FAIL') 152 | elif result_code == 'wrong': 153 | data = style_text('Wrong answer\n', 'FAIL') 154 | elif result_code == 'accepted': 155 | data = 'Correct answer\n' 156 | 157 | resps = [{'data': data}] 158 | status_table = get_status_table(status_code) 159 | if status_table: 160 | resps.append({'data_type': 'table', 'data': html_to_list(status_table)}) 161 | return resps 162 | else: 163 | print(style_text('Waiting...\n', 'BLUE')) 164 | return [{'code': 503}] 165 | 166 | 167 | @sort_it 168 | def get_contest_problems(sort, order, contest_code): 169 | url = f'/api/contests/{contest_code}?' 170 | resp = request(url=url) 171 | 172 | try: 173 | resp_json = resp.json() 174 | except ValueError: 175 | return [{"code": 503}] 176 | 177 | if resp_json['status'] == "success": 178 | problems_table = [[ 179 | x.upper() for x in [ 180 | "Name", "Code", "URL", "Successful Submissions", "Accuracy", "Scorable?"] 181 | ]] 182 | for _, problem in resp_json['problems'].items(): 183 | problems_table.append([ 184 | problem['name'], 185 | problem['code'], 186 | f"{BASE_URL}{problem['problem_url']}", 187 | problem['successful_submissions'], 188 | f"{problem['accuracy']} %", 189 | "Yes" if problem['category_name'] == 'main' else "No" 190 | ]) 191 | 192 | return [ 193 | {'data': f"\n{style_text('Name:', 'BOLD')} {resp_json['name']}\n"}, 194 | {'data': problems_table, "data_type": "table"}, 195 | {'data': f'\n{style_text("Announcements", "BOLD")}:\n{resp_json["announcements"]}'} 196 | ] 197 | elif resp_json['status'] == "error": 198 | return [{'data': 'Contest doesn\'t exist.', 'code': 404}] 199 | return [{"code": 503}] 200 | 201 | 202 | @sort_it 203 | def search_problems(sort, order, search_type): 204 | url = f'/problems/{search_type.lower()}' 205 | resp = request(url=url) 206 | if resp.status_code == 200: 207 | return [{'data_type': 'table', 'data': html_to_list(resp.html.find('table')[1])}] 208 | return [{"code": 503}] 209 | 210 | 211 | def get_tags(sort, order, tags): 212 | if len(tags) == 0: 213 | return get_all_tags() 214 | return get_tagged_problems(sort, order, tags) 215 | 216 | 217 | def get_all_tags(): 218 | resp = request(url='/get/tags/problems') 219 | 220 | try: 221 | all_tags = resp.json() 222 | except ValueError: 223 | return [{'code': 503}] 224 | 225 | if resp.status_code == 200: 226 | data_rows = [] 227 | num_cols = 5 228 | row = [] 229 | 230 | for index, tag in enumerate(all_tags): 231 | tag_name = tag.get('tag', '') 232 | if len(row) < num_cols: 233 | row.append(tag_name) 234 | else: 235 | data_rows.append(row) 236 | row = [tag_name] 237 | if len(row): 238 | data_rows.append(row) 239 | 240 | return [{'data': data_rows, 'data_type': 'table'}] 241 | 242 | return [{'code': 503}] 243 | 244 | 245 | @sort_it 246 | def get_tagged_problems(sort, order, tags): 247 | resp = request(url=f'/get/tags/problems/{",".join(tags)}') 248 | 249 | try: 250 | all_tags = resp.json() 251 | except ValueError: 252 | return [{'code': 503}] 253 | 254 | if resp.status_code == 200: 255 | data_rows = [PROBLEM_LIST_TABLE_HEADINGS] 256 | all_tags = all_tags.get('all_problems') 257 | 258 | if not all_tags: 259 | return [{'code': 404, 'extra': "Sorry, there are no problems with the following tags!"}] 260 | 261 | for _, problem in all_tags.items(): 262 | problem_info = [ 263 | problem.get('code', ''), 264 | problem.get('name', ''), 265 | str(problem.get('attempted_by', '')) 266 | ] 267 | try: 268 | accuracy = (problem.get('solved_by') / problem.get('attempted_by')) * 100 269 | problem_info.append(str(math.floor(accuracy))) 270 | except TypeError: 271 | problem_info.append('') 272 | data_rows.append(problem_info) 273 | 274 | return [{'data': data_rows, 'data_type': 'table'}] 275 | 276 | return [{'code': 503}] 277 | 278 | 279 | @sort_it 280 | def get_ratings(sort, order, country, institution, institution_type, page, lines): 281 | csrf_resp = request(url='/ratings/all') 282 | if csrf_resp.status_code == 200: 283 | csrf_token = get_csrf_token(csrf_resp.html, CSRF_TOKEN_INPUT_ID) 284 | else: 285 | return [{'code': 503}] 286 | 287 | url = '/api/ratings/all?sortBy=global_rank&order=asc' 288 | params = {'page': str(page), 'itemsPerPage': str(lines), 'filterBy': ''} 289 | if country: 290 | params['filterBy'] += f'Country={country};' 291 | if institution: 292 | institution = institution.title() 293 | params['filterBy'] += f'Institution={institution};' 294 | if institution_type: 295 | params['filterBy'] += f'Institution type={institution_type};' 296 | 297 | resp = request(url=url, params=params, token=csrf_token) 298 | 299 | if resp.status_code == 200: 300 | try: 301 | ratings = resp.json() 302 | except ValueError: 303 | return [{'code': 503}] 304 | 305 | ratings = ratings.get('list') or [] 306 | if len(ratings) == 0: 307 | return [{'code': 404, 'data': 'No ratings found'}] 308 | 309 | data_rows = [RATINGS_TABLE_HEADINGS] 310 | for user in ratings: 311 | data_rows.append([ 312 | f"{str(user['global_rank'])} ({str(user['country_rank'])})", 313 | user['username'], 314 | str(user['rating']), 315 | str(user['diff']) 316 | ]) 317 | return [{'data': data_rows, 'data_type': 'table'}] 318 | return [{'code': 503}] 319 | 320 | 321 | def get_contests(show_past): 322 | resp = request(url='/contests') 323 | if resp.status_code == 200: 324 | tables = resp.html.find('table') 325 | labels = ['Present', 'Future'] 326 | if show_past: 327 | labels = ['Past'] 328 | tables = [tables[0], tables[-1]] 329 | 330 | resps = [] 331 | for idx, label in enumerate(labels): 332 | resps += [ 333 | {'data': style_text(f'{label} Contests:\n', 'BOLD')}, 334 | {'data': html_to_list(tables[idx + 1]), 'data_type': 'table'} 335 | ] 336 | return resps 337 | return [{'code': 503}] 338 | 339 | 340 | def build_request_params(resp_html, language, result, username, page): 341 | params = {'page': page - 1} if page != 1 else {} 342 | if language: 343 | lang_dropdown = resp_html.find(LANGUAGE_SELECTOR, first=True) 344 | options = lang_dropdown.find('option') 345 | 346 | for option in options: 347 | if language.upper() == option.text.strip().upper(): 348 | params['language'] = dict(option.element.items()).get('value', '') 349 | break 350 | if result: 351 | params['status'] = RESULT_CODES[result.upper()] 352 | if username: 353 | params['handle'] = username 354 | return params 355 | 356 | 357 | @sort_it 358 | def get_solutions(sort, order, problem_code, page, language, result, username): 359 | url = f'/status/{problem_code.upper()}' 360 | resp = request(url=url) 361 | 362 | if resp.status_code != 200: 363 | return [{'code': 503}] 364 | 365 | params = build_request_params(resp.html, language, result, username, page) 366 | resp = request(url=url, params=params) 367 | 368 | if resp.status_code == 200: 369 | if problem_code in resp.url: 370 | resp_html = resp.html 371 | solution_table = resp_html.find('table')[2] 372 | page_info = resp_html.find(PAGE_INFO_CLASS, first=True) 373 | 374 | data_rows = html_to_list(solution_table) 375 | for row in data_rows: 376 | # remove view solution column 377 | del row[-1] 378 | 379 | # format result column 380 | row[3] = ' '.join(row[3].split('\n')) 381 | 382 | resp = {'data_type': 'table', 'data': data_rows} 383 | if page_info: 384 | resp['extra'] = f'\nPage: {page_info.text}' 385 | 386 | return [resp] 387 | else: 388 | return [{'code': 404, 'data': INVALID_PROBLEM_CODE_MSG}] 389 | return [{'code': 503}] 390 | 391 | 392 | def get_solution(solution_code): 393 | resp = request(url=f'/viewplaintext/{solution_code}') 394 | if resp.status_code == 200: 395 | err_msg_element = resp.html.find(SOLUTION_ERR_MSG_CLASS, first=True) 396 | if err_msg_element and err_msg_element.text == INVALID_SOLUTION_ID_MSG: 397 | return [{'code': 404, "data": "Invalid Solution ID"}] 398 | return [{'data': f'\n{resp.html.find("pre", first=True).element.text}\n'}] 399 | return [{'code': 503}] 400 | -------------------------------------------------------------------------------- /codechefcli/teams.py: -------------------------------------------------------------------------------- 1 | from codechefcli.helpers import BASE_URL, html_to_list, request 2 | 3 | 4 | def get_team_url(name): 5 | return f"{BASE_URL}/teams/view/{name}" 6 | 7 | 8 | def format_contest(item): 9 | if item.startswith("Information for"): 10 | return f"\n{item}" 11 | return item 12 | 13 | 14 | def get_team(name): 15 | if not name: 16 | return [] 17 | resp = request(url=get_team_url(name)) 18 | 19 | if resp.status_code == 200: 20 | resp_html = resp.html 21 | tables = resp_html.find('table') 22 | 23 | header = tables[1].text.strip() 24 | team_info = tables[2].text.strip() 25 | team_info = team_info.replace(':\n', ': ') 26 | team_info_list = team_info.split('\n') 27 | 28 | basic_info = "\n".join(team_info_list[:2]) 29 | contests_info = "\n".join([format_contest(item) for item in team_info_list[2:-1]]) 30 | problems_solved_table = html_to_list(tables[-1]) 31 | 32 | team_details = "\n".join([ 33 | '', 34 | header, 35 | '', 36 | basic_info, 37 | contests_info, 38 | '', 39 | 'Problems Successfully Solved:', 40 | '' 41 | ]) 42 | return [ 43 | {'data': team_details}, 44 | {'data': problems_solved_table, "data_type": "table", "is_pager": False} 45 | ] 46 | elif resp.status_code == 404: 47 | return [{'code': 404, 'data': 'Team not found.'}] 48 | return [{'code': 503}] 49 | -------------------------------------------------------------------------------- /codechefcli/users.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from codechefcli.helpers import BASE_URL, request, style_text 4 | from codechefcli.teams import get_team_url 5 | 6 | HEADER = 'header' 7 | RATING_NUMBER_CLASS = '.rating-number' 8 | RATING_RANKS_CLASS = '.rating-ranks' 9 | STAR_RATING_CLASS = '.rating' 10 | USER_DETAILS_CONTAINER_CLASS = '.user-details-container' 11 | USER_DETAILS_CLASS = '.user-details' 12 | 13 | 14 | def get_user_teams_url(username): 15 | return f'{BASE_URL}/users/{username}/teams/' 16 | 17 | 18 | def format_list_item(item): 19 | return ": ".join([i.strip() for i in item.text.split(':')]) 20 | 21 | 22 | def get_user(username): 23 | if not username: 24 | return [] 25 | 26 | resp = request(url=f'/users/{username}') 27 | 28 | if resp.status_code == 200: 29 | team_url = get_team_url(username) 30 | if resp.url == team_url: 31 | return [{ 32 | 'data': f'This is a team handle.' 33 | f'Run `codechefcli --team {username}` to get team info\n', 34 | 'code': 400 35 | }] 36 | elif resp.url.rstrip('/') == BASE_URL: 37 | return [{'code': 404, 'data': 'User not found.'}] 38 | else: 39 | resp_html = resp.html 40 | details_container = resp_html.find(USER_DETAILS_CONTAINER_CLASS, first=True) 41 | 42 | # basic info 43 | header = details_container.find(HEADER, first=True).text.strip() 44 | info_list_items = details_container.find(USER_DETAILS_CLASS, first=True).find('li') 45 | 46 | # ignore first & last item i.e. username item & teams item respectively 47 | info = "\n".join([format_list_item(li) for li in info_list_items[1:-1]]) 48 | 49 | # rating 50 | star_rating = details_container.find(STAR_RATING_CLASS, first=True).text.strip() 51 | rating = resp_html.find(RATING_NUMBER_CLASS, first=True).text.strip() 52 | rank_items = resp_html.find(RATING_RANKS_CLASS, first=True).find('li') 53 | global_rank = rank_items[0].find('a', first=True).text.strip() 54 | country_rank = rank_items[1].find('a', first=True).text.strip() 55 | 56 | user_details = "\n".join([ 57 | '', 58 | style_text(f'User Details for {header} ({username}):', 'BOLD'), 59 | '', 60 | info, 61 | f"User's Teams: {get_user_teams_url(username)}", 62 | '', 63 | f'Rating: {star_rating} {rating}', 64 | f'Global Rank: {global_rank}', 65 | f'Country Rank: {country_rank}', 66 | '', 67 | f'Find more at: {resp.url}', 68 | '' 69 | ]) 70 | return [{'data': user_details}] 71 | return [{'code': 503}] 72 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flake8==3.8.3 2 | isort==4.3.21 3 | pytest==5.4.3 4 | requests_html==0.10.0 5 | coverage==5.1 -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | # This flag says that the code is written to work on both Python 2 and Python 3 | # 3. If at all possible, it is good practice to do this. If you cannot, you 4 | # will need to generate wheels for each Python version that you support. 5 | universal=1 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | from codecs import open 5 | 6 | from setuptools import setup 7 | 8 | if sys.version < '3.8': 9 | print("This version is not supported.") 10 | sys.exit(1) 11 | 12 | with open('README.rst') as f: 13 | longd = f'\n\n{f.read()}' 14 | 15 | setup( 16 | name='codechefcli', 17 | include_package_data=True, 18 | packages=["codechefcli"], 19 | data_files=[('codechefcli', [])], 20 | entry_points={"console_scripts": ['codechefcli = codechefcli.__main__:main']}, 21 | install_requires=['requests_html'], 22 | python_requires='>=3.8', 23 | version='0.5.3', 24 | url='http://www.github.com/sk364/codechef-cli', 25 | keywords="codechefcli codechef cli programming competitive-programming competitive-coding", 26 | license='GNU','MIT', 27 | author='Sachin Kukreja', 28 | author_email='skad5455@gmail.com', 29 | description='CodeChef Command Line Interface', 30 | long_description=longd 31 | ) 32 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sk364/codechef-cli/fa678861a51ee374029a96ffb15c43dc741f22c4/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_auth_entry.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from _pytest.monkeypatch import MonkeyPatch 4 | from requests_html import HTML 5 | 6 | from codechefcli import __main__ as entry_point 7 | from codechefcli import auth 8 | from codechefcli.auth import (CSRF_TOKEN_MISSING, EMPTY_AUTH_DATA_MSG, INCORRECT_CREDS_MSG, 9 | LOGIN_SUCCESS_MSG, LOGOUT_BUTTON_CLASS, SESSION_LIMIT_FORM_ID, 10 | SESSION_LIMIT_MSG, disconnect_active_sessions, login) 11 | from codechefcli.helpers import CSRF_TOKEN_INPUT_ID 12 | from tests.utils import MockHTMLResponse 13 | 14 | 15 | class EntryPointTests(TestCase): 16 | def setUp(self): 17 | self.monkeypatch = MonkeyPatch() 18 | 19 | def test_main_invalid_args(self): 20 | """Should raise SystemExit exception on incorrect number of args for a particular option""" 21 | with self.assertRaises(SystemExit): 22 | entry_point.main(['codechefcli', '--problem']) 23 | 24 | def test_main_valid_args(self): 25 | """Should return responses when valid args are present""" 26 | def mock_get_desc(*args, **kwargs): 27 | return [{"data": "Lots of description. Some math. Some meta info. Done."}] 28 | 29 | self.monkeypatch.setattr(entry_point, "get_description", mock_get_desc) 30 | 31 | resps = entry_point.main(['codechefcli', '--problem', 'CCC']) 32 | self.assertEqual(resps[0]["data"], "Lots of description. Some math. Some meta info. Done.") 33 | 34 | def test_create_parser(self): 35 | """Should not explode when parser is parsing the args""" 36 | 37 | parser = entry_point.create_parser() 38 | args = parser.parse_args(['--problem', 'WEICOM']) 39 | self.assertEqual(args.problem, 'WEICOM') 40 | 41 | 42 | class LoginTests(TestCase): 43 | def setUp(self): 44 | self.monkeypatch = MonkeyPatch() 45 | 46 | def test_empty_auth_data(self): 47 | """Should return empty auth data message""" 48 | resps = login(username='', password='', disconnect_sessions=False) 49 | self.assertEqual(resps[0]['data'], EMPTY_AUTH_DATA_MSG) 50 | self.assertEqual(resps[0]['code'], 400) 51 | 52 | def test_correct_auth_data(self): 53 | """Should login on correct auth data""" 54 | def mock_request(*args, **kwargs): 55 | if kwargs.get('method'): 56 | return MockHTMLResponse( 57 | data=f'') 58 | else: 59 | return MockHTMLResponse(data=f"") 60 | 61 | def mock_save_cookies(*args, **kwargs): 62 | pass 63 | 64 | self.monkeypatch.setattr(auth, 'request', mock_request) 65 | self.monkeypatch.setattr(auth, 'save_session_cookies', mock_save_cookies) 66 | 67 | resps = login(username='cc', password='cc', disconnect_sessions=False) 68 | self.assertEqual(resps[0]['data'], LOGIN_SUCCESS_MSG) 69 | 70 | def test_incorrect_auth_data(self): 71 | """Should return incorrect creds message""" 72 | def mock_request(*args, **kwargs): 73 | if kwargs.get('method'): 74 | return MockHTMLResponse(data='') 75 | else: 76 | return MockHTMLResponse(data=f"") 77 | 78 | self.monkeypatch.setattr(auth, 'request', mock_request) 79 | 80 | resps = login(username='nope', password='nope', disconnect_sessions=False) 81 | self.assertEqual(resps[0]['data'], INCORRECT_CREDS_MSG) 82 | self.assertEqual(resps[0]['code'], 400) 83 | 84 | def test_no_csrf_token(self): 85 | """Should return csrf token missing message when there isn't one in the response html""" 86 | def mock_request(*args, **kwargs): 87 | return MockHTMLResponse(data="") 88 | self.monkeypatch.setattr(auth, 'request', mock_request) 89 | 90 | resps = login(username='cc', password='cc', disconnect_sessions=False) 91 | self.assertEqual(resps[0]['data'], CSRF_TOKEN_MISSING) 92 | self.assertEqual(resps[0]['code'], 500) 93 | 94 | def test_status_code_not_200(self): 95 | """Should return code 503 when status code is not 200""" 96 | def mock_request(*args, **kwargs): 97 | if kwargs.get('method'): 98 | return MockHTMLResponse(status_code=500) 99 | else: 100 | return MockHTMLResponse(data=f"") 101 | 102 | self.monkeypatch.setattr(auth, 'request', mock_request) 103 | 104 | resps = login(username='cc', password='cc', disconnect_sessions=False) 105 | self.assertEqual(resps[0]['code'], 503) 106 | 107 | def test_session_limit_exceeded_no_disconnect(self): 108 | """Should return session limit msg on no disconnect""" 109 | 110 | def mock_request(*args, **kwargs): 111 | if kwargs.get('method'): 112 | return MockHTMLResponse(data=f'') 113 | else: 114 | return MockHTMLResponse(data=f"") 115 | 116 | def mock_logout(*args, **kwargs): 117 | pass 118 | 119 | self.monkeypatch.setattr(auth, 'request', mock_request) 120 | self.monkeypatch.setattr(auth, 'logout', mock_logout) 121 | 122 | resps = login(username='cc', password='cc', disconnect_sessions=False) 123 | self.assertEqual(resps[0]['data'], SESSION_LIMIT_MSG) 124 | self.assertEqual(resps[0]['code'], 400) 125 | 126 | def test_session_limit_exceeded_disconnect(self): 127 | """Should disconnect active sessions and login in the current returning login success msg""" 128 | 129 | def mock_request(*args, **kwargs): 130 | if kwargs.get('method'): 131 | return MockHTMLResponse(data=f'') 132 | else: 133 | return MockHTMLResponse(data=f"") 134 | 135 | def mock_logout(*args, **kwargs): 136 | pass 137 | 138 | def mock_disconnect(*args, **kwargs): 139 | return [{'data': LOGIN_SUCCESS_MSG}] 140 | 141 | def mock_save_cookies(*args, **kwargs): 142 | pass 143 | 144 | self.monkeypatch.setattr(auth, 'request', mock_request) 145 | self.monkeypatch.setattr(auth, 'logout', mock_logout) 146 | self.monkeypatch.setattr(auth, 'disconnect_active_sessions', mock_disconnect) 147 | self.monkeypatch.setattr(auth, 'save_session_cookies', mock_save_cookies) 148 | 149 | resps = login(username='cc', password='cc', disconnect_sessions=True) 150 | self.assertEqual(resps[0]['data'], LOGIN_SUCCESS_MSG) 151 | 152 | def test_disconnect_active_sessions_success(self): 153 | """Should return login success msg on disconnect""" 154 | def mock_request(*args, **kwargs): 155 | return MockHTMLResponse() 156 | 157 | self.monkeypatch.setattr(auth, 'request', mock_request) 158 | 159 | inputs = "".join([f"" for idx in range(6)]) 160 | html = HTML(html=f'' 161 | f'
{inputs}
') 162 | resps = disconnect_active_sessions(None, html) 163 | self.assertEqual(resps[0]['data'], LOGIN_SUCCESS_MSG) 164 | 165 | def test_disconnect_active_sessions_error(self): 166 | """Should return 503 when status code is not 200""" 167 | def mock_request(*args, **kwargs): 168 | return MockHTMLResponse(status_code=500) 169 | 170 | self.monkeypatch.setattr(auth, 'request', mock_request) 171 | 172 | inputs = "".join([f"" for idx in range(6)]) 173 | html = HTML(html=f'' 174 | f'
{inputs}
') 175 | resps = disconnect_active_sessions(None, html) 176 | self.assertEqual(resps[0]['code'], 503) 177 | -------------------------------------------------------------------------------- /tests/test_helpers.py: -------------------------------------------------------------------------------- 1 | from http.cookiejar import Cookie 2 | from unittest import TestCase 3 | 4 | from requests_html import HTML, HTMLSession 5 | 6 | from codechefcli.helpers import (SERVER_DOWN_MSG, UNAUTHORIZED_MSG, get_csrf_token, get_session, 7 | get_username, html_to_list, init_session_cookie, print_response, 8 | print_table) 9 | from tests.utils import fake_login, fake_logout 10 | 11 | 12 | class HelpersTestCase(TestCase): 13 | def test_get_session_cookies(self): 14 | """Should return requests_html.HTMLSession instance preloaded with cookies""" 15 | fake_login() 16 | 17 | session = get_session() 18 | self.assertIsInstance(session, HTMLSession) 19 | self.assertTrue(len(session.cookies) > 0) 20 | 21 | def test_get_session_no_cookies(self): 22 | """Should return requests_html.HTMLSession instance""" 23 | fake_logout() 24 | 25 | session = get_session() 26 | self.assertIsInstance(session, HTMLSession) 27 | self.assertEqual(len(session.cookies), 0) 28 | 29 | def test_init_session_cookie(self): 30 | """Should return cookiejar.Cookie instance with name and value as provided""" 31 | cookie = init_session_cookie("u", "u") 32 | self.assertIsInstance(cookie, Cookie) 33 | self.assertEqual(cookie.name, "u") 34 | self.assertEqual(cookie.value, "u") 35 | 36 | def test_get_username_not_exists(self): 37 | """Should return None when username not found in session cookies""" 38 | fake_logout() 39 | self.assertIsNone(get_username()) 40 | 41 | def test_get_username_exists(self): 42 | """Should return None when username not found in session cookies""" 43 | fake_login(init_cookies=[{"name": "username", "value": "abcd"}]) 44 | self.assertEqual(get_username(), "abcd") 45 | 46 | def test_html_to_list_none_html(self): 47 | """Should return empty list when no html is provided""" 48 | self.assertTrue(len(html_to_list(None)) == 0) 49 | 50 | def test_html_to_list_valid_html(self): 51 | """Should convert requests_html.HTML instance to `list`""" 52 | html = HTML(html=" \ 53 | AV \ 54 | a1v1 \ 55 | a2v2 \ 56 | ") 57 | self.assertEqual(html_to_list(html), [['A', 'V'], ['a1', 'v1'], ['a2', 'v2']]) 58 | 59 | def test_print_table_no_rows(self): 60 | """Should return None when empty list of rows is passed""" 61 | self.assertIsNone(print_table([])) 62 | 63 | def test_print_table(self): 64 | """Should return table string to be printed""" 65 | self.assertEqual( 66 | print_table([['A', 'V'], ['a1', 'v1'], ['a2', 'v2']], is_pager=False), 67 | 'A V \n\na1 v1 \n\na2 v2 ' 68 | ) 69 | 70 | def test_print_response_503(self): 71 | """Should set color 'FAIL' and data when 503 code is provided""" 72 | self.assertEqual(print_response(code=503)[0], f'\x1b[91m{SERVER_DOWN_MSG}\x1b[0m') 73 | 74 | def test_print_response_404_400(self): 75 | """Should set color 'WARNING' when code is 404 / 400""" 76 | self.assertEqual(print_response(code=404, data='a')[0], '\x1b[93ma\x1b[0m') 77 | self.assertEqual(print_response(code=400, data='a')[0], '\x1b[93ma\x1b[0m') 78 | 79 | def test_print_response_401(self): 80 | """Should set color 'FAIL' and data when 401 code is provided""" 81 | self.assertEqual(print_response(code=401)[0], f'\x1b[91m{UNAUTHORIZED_MSG}\x1b[0m') 82 | 83 | def test_print_response_table(self): 84 | """Should set is_pager True when data_type table is provided with no pager in kwargs""" 85 | self.assertEqual(print_response(data_type='table', data=[['1', '2']])[0], '1 2 ') 86 | 87 | def test_print_response_no_data_no_extra(self): 88 | """Should return no data msg""" 89 | self.assertEqual(print_response()[0], '\x1b[93mNothing to show.\x1b[0m') 90 | 91 | def test_print_response_no_data(self): 92 | """Should return no data msg""" 93 | self.assertIsNone(print_response(extra='a')[0]) 94 | 95 | def test_get_csrf_token_no_token(self): 96 | """Should return None when token not found in html""" 97 | html = HTML(html="") 98 | self.assertIsNone(get_csrf_token(html, "a")) 99 | 100 | def test_get_csrf_token_no_value(self): 101 | """Should return None when html element has no value""" 102 | html = HTML(html="") 103 | self.assertIsNone(get_csrf_token(html, "a")) 104 | 105 | def test_get_csrf_token(self): 106 | """Should return token from html element's value""" 107 | html = HTML(html="") 108 | self.assertEqual(get_csrf_token(html, "a"), 'b') 109 | -------------------------------------------------------------------------------- /tests/test_problems.py: -------------------------------------------------------------------------------- 1 | from os import environ 2 | from platform import platform 3 | from unittest import TestCase 4 | 5 | from _pytest.monkeypatch import MonkeyPatch 6 | 7 | from codechefcli import problems 8 | from codechefcli.auth import LOGIN_FORM_ID 9 | from codechefcli.problems import (COMPILATION_ERROR_CLASS, INVALID_SOLUTION_ID_MSG, 10 | LANGUAGE_DROPDOWN_ID, LANGUAGE_SELECTOR, PAGE_INFO_CLASS, 11 | PROBLEM_SUBMISSION_FORM_ID, SOLUTION_ERR_MSG_CLASS, 12 | build_request_params, get_contest_problems, get_contests, 13 | get_description, get_ratings, get_solution, get_solutions, 14 | get_tags, search_problems, submit_problem) 15 | from tests.utils import HTML, MockHTMLResponse, fake_login 16 | 17 | temp_file_a = '/tmp/a' 18 | if 'Windows' in platform(): 19 | temp_file_a = environ['TMP'] + r'\a' 20 | 21 | 22 | class ProblemsTestCase(TestCase): 23 | def setUp(self): 24 | self.monkeypatch = MonkeyPatch() 25 | fake_login() 26 | 27 | def test_get_problem_desc_invalid_json(self): 28 | """Should return 503 when response is not JSON-parsable""" 29 | def mock_req(*args, **kwargs): 30 | return MockHTMLResponse(json="{") 31 | self.monkeypatch.setattr(problems, "request", mock_req) 32 | self.assertEqual(get_description("a", "b")[0]['code'], 503) 33 | 34 | def test_get_problem_desc_err(self): 35 | """Should return 404 when problem api returns error status""" 36 | def mock_req(*args, **kwargs): 37 | return MockHTMLResponse(json='{"status": "error"}') 38 | self.monkeypatch.setattr(problems, "request", mock_req) 39 | resps = get_description("a", "b") 40 | self.assertEqual(resps[0]['code'], 404) 41 | 42 | def test_get_problem_desc_success(self): 43 | """Should return 404 when problem api returns error status""" 44 | def mock_req(*args, **kwargs): 45 | return MockHTMLResponse( 46 | json='{"status": "success", "problem_name": "a a", "body": "vbbv"}') 47 | self.monkeypatch.setattr(problems, "request", mock_req) 48 | resps = get_description("a", "b") 49 | self.assertEqual( 50 | resps[0]['data'], 51 | '\n\x1b[1mName: \x1b[0ma a\n\x1b[1mDescription:\x1b[0m\nvbbv\n\n\x1b[1mAuthor: \x1b[0m' 52 | '\n\x1b[1mDate Added: \x1b[0m\n\x1b[1mMax Time Limit: \x1b[0m secs\n\x1b[1mSource Limit' 53 | ': \x1b[0m Bytes\n\x1b[1mLanguages: \x1b[0m\n' 54 | ) 55 | 56 | def test_submit_problem_no_login(self): 57 | """Should return 401 response when user is not logged in""" 58 | def mock_req(*args, **kwargs): 59 | return MockHTMLResponse(data=f"
Login
") 60 | self.monkeypatch.setattr(problems, "request", mock_req) 61 | self.assertEqual(submit_problem("A", "a/b", "p")[0]['code'], 401) 62 | 63 | def test_submit_problem_invalid_lang(self): 64 | """Should return 400 when invalid language is passed""" 65 | def mock_req(*args, **kwargs): 66 | return MockHTMLResponse(data=f" \ 67 |
\ 68 | \ 71 |
\ 72 | ") 73 | self.monkeypatch.setattr(problems, "request", mock_req) 74 | self.assertEqual(submit_problem("A", "a/b", "p")[0]['code'], 400) 75 | 76 | def test_submit_problem_sol_file_not_found(self): 77 | """Should return 400 response when solution file is not found""" 78 | def mock_req(*args, **kwargs): 79 | return MockHTMLResponse(data=f" \ 80 |
\ 81 | \ 84 |
\ 85 | ") 86 | self.monkeypatch.setattr(problems, "request", mock_req) 87 | self.assertEqual(submit_problem("A", "invalid_path/invalid_path", "a")[0]['code'], 400) 88 | 89 | def test_submit_problem_status_not_200(self): 90 | """Should return 503 response when status code is not 200""" 91 | def mock_req(*args, **kwargs): 92 | return MockHTMLResponse(status_code=400) 93 | self.monkeypatch.setattr(problems, "request", mock_req) 94 | self.assertEqual(submit_problem("A", "a/b", "p")[0]['code'], 503) 95 | 96 | def test_submit_problem_submission_status_not_200(self): 97 | """Should return 503 response when submission req status code is not 200""" 98 | def mock_req(*args, **kwargs): 99 | if kwargs.get('method') != 'POST': 100 | return MockHTMLResponse(data=f" \ 101 |
\ 102 | \ 105 |
\ 106 | ") 107 | return MockHTMLResponse(status_code=500) 108 | self.monkeypatch.setattr(problems, "request", mock_req) 109 | 110 | with open(temp_file_a, 'w') as f: 111 | f.write('a') 112 | self.assertEqual(submit_problem("A", temp_file_a, "a")[0]['code'], 503) 113 | 114 | def test_submit_problem_invalid_status_json(self): 115 | """Should return 503 response when submission status request returns invalid json""" 116 | def mock_req(*args, **kwargs): 117 | return MockHTMLResponse(data=f" \ 118 |
\ 119 | \ 122 |
\ 123 | ", json="{") 124 | self.monkeypatch.setattr(problems, "request", mock_req) 125 | 126 | with open(temp_file_a, 'w') as f: 127 | f.write('a') 128 | self.assertEqual(submit_problem("A", temp_file_a, "a")[0]['code'], 503) 129 | 130 | def test_submit_problem_compile_err(self): 131 | """Should return compilation error message when result code of submission is compile""" 132 | def mock_req(*args, **kwargs): 133 | return MockHTMLResponse( 134 | data=f" \ 135 |
\ 136 | \ 139 |
\ 140 |
Comp Err
", 141 | json='{"result_code": "compile"}' 142 | ) 143 | 144 | def mock_get_status_table(*args, **kwargs): 145 | return 146 | self.monkeypatch.setattr(problems, "request", mock_req) 147 | self.monkeypatch.setattr(problems, "get_status_table", mock_get_status_table) 148 | 149 | with open(temp_file_a, 'w') as f: 150 | f.write('a') 151 | self.assertEqual( 152 | submit_problem("A", temp_file_a, "a")[0]['data'], 153 | '\x1b[91mCompilation error.\nComp Err\x1b[0m') 154 | 155 | def test_submit_problem_runtime_err(self): 156 | """Should return runtime error message when result code of submission is runtime""" 157 | def mock_req(*args, **kwargs): 158 | return MockHTMLResponse(data=f" \ 159 |
\ 160 | \ 163 |
\ 164 | ", json='{"result_code": "runtime", "signal": "abcd"}') 165 | 166 | def mock_get_status_table(*args, **kwargs): 167 | return 168 | self.monkeypatch.setattr(problems, "request", mock_req) 169 | self.monkeypatch.setattr(problems, "get_status_table", mock_get_status_table) 170 | 171 | with open(temp_file_a, 'w') as f: 172 | f.write('a') 173 | self.assertEqual( 174 | submit_problem( 175 | "A", temp_file_a, "a")[0]['data'], '\x1b[91mRuntime error. abcd\n\x1b[0m') 176 | 177 | def test_submit_problem_wrong_ans(self): 178 | """Should return wrong answer message when result code of submission is wrong""" 179 | def mock_req(*args, **kwargs): 180 | return MockHTMLResponse(data=f" \ 181 |
\ 182 | \ 185 |
\ 186 | ", json='{"result_code": "wrong"}') 187 | 188 | def mock_get_status_table(*args, **kwargs): 189 | return 190 | self.monkeypatch.setattr(problems, "request", mock_req) 191 | self.monkeypatch.setattr(problems, "get_status_table", mock_get_status_table) 192 | 193 | with open(temp_file_a, 'w') as f: 194 | f.write('a') 195 | self.assertEqual( 196 | submit_problem("A", temp_file_a, "a")[0]['data'], '\x1b[91mWrong answer\n\x1b[0m') 197 | 198 | def test_submit_problem_accepted_ans(self): 199 | """Should return accepted message when result code of submission is accepted""" 200 | def mock_req(*args, **kwargs): 201 | return MockHTMLResponse(data=f" \ 202 |
\ 203 | \ 206 |
\ 207 | ", json='{"result_code": "accepted"}') 208 | 209 | def mock_get_status_table(*args, **kwargs): 210 | return 211 | self.monkeypatch.setattr(problems, "request", mock_req) 212 | self.monkeypatch.setattr(problems, "get_status_table", mock_get_status_table) 213 | 214 | with open(temp_file_a, 'w') as f: 215 | f.write('a') 216 | self.assertEqual(submit_problem("A", temp_file_a, "a")[0]['data'], 'Correct answer\n') 217 | 218 | 219 | class SearchTestCase(TestCase): 220 | def setUp(self): 221 | self.monkeypatch = MonkeyPatch() 222 | 223 | def test_search_problems_status_not_200(self): 224 | """Should return 503 response code when req status is not 200""" 225 | def mock_req(*args, **kwargs): 226 | return MockHTMLResponse(status_code=400) 227 | self.monkeypatch.setattr(problems, 'request', mock_req) 228 | self.assertEqual(search_problems("Name", "asc", "easy")[0]['code'], 503) 229 | 230 | def test_search_problems_success(self): 231 | """Should return tabular response when status code 200""" 232 | def mock_req(*args, **kwargs): 233 | return MockHTMLResponse(data='
\ 234 | \ 235 | \ 236 | \ 237 |
AABB
a1b1
a2b2
') 238 | self.monkeypatch.setattr(problems, 'request', mock_req) 239 | self.assertEqual( 240 | search_problems("AA", "asc", "easy")[0]['data'], 241 | [['AA', 'BB', 'A1', 'B1', 'A2', 'B2'], ['a1', 'b1', 'a2', 'b2'], ['a2', 'b2']] 242 | ) 243 | 244 | def test_contest_problems_invalid_json(self): 245 | """Should return 503 response when invalid json is received""" 246 | def mock_req(*args, **kwargs): 247 | return MockHTMLResponse(json="{") 248 | self.monkeypatch.setattr(problems, "request", mock_req) 249 | self.assertEqual(get_contest_problems("AA", "asc", "CC1")[0]['code'], 503) 250 | 251 | def test_contest_problems_api_error(self): 252 | """Should return 404 response when api response status is error""" 253 | def mock_req(*args, **kwargs): 254 | return MockHTMLResponse(json='{"status": "error"}') 255 | self.monkeypatch.setattr(problems, "request", mock_req) 256 | self.assertEqual(get_contest_problems("AA", "asc", "CC1")[0]['code'], 404) 257 | 258 | def test_contest_problems(self): 259 | """Should return contest problems info and table when status is success""" 260 | def mock_req(*args, **kwargs): 261 | return MockHTMLResponse(json='{ \ 262 | "status": "success", \ 263 | "name": "P1", \ 264 | "announcements": "---", \ 265 | "problems": { \ 266 | "p1": { \ 267 | "name": "P1", \ 268 | "code": "p1", \ 269 | "problem_url": "/p1", \ 270 | "successful_submissions": 12, \ 271 | "accuracy": "11", \ 272 | "category_name": "main" \ 273 | }, \ 274 | "p2": { \ 275 | "name": "P2", \ 276 | "code": "p2", \ 277 | "problem_url": "/p2", \ 278 | "successful_submissions": 14, \ 279 | "accuracy": "1", \ 280 | "category_name": "" \ 281 | } \ 282 | } \ 283 | }') 284 | self.monkeypatch.setattr(problems, "request", mock_req) 285 | resps = get_contest_problems("Name", "asc", "CC1") 286 | self.assertEqual(resps[0]['data'], '\n\x1b[1mName:\x1b[0m P1\n') 287 | self.assertEqual( 288 | resps[1]['data'], [ 289 | ['NAME', 'CODE', 'URL', 'SUCCESSFUL SUBMISSIONS', 'ACCURACY', 'SCORABLE?'], 290 | ['P1', 'p1', 'https://www.codechef.com/p1', 12, '11 %', 'Yes'], 291 | ['P2', 'p2', 'https://www.codechef.com/p2', 14, '1 %', 'No'] 292 | ] 293 | ) 294 | self.assertEqual(resps[1]['data_type'], "table") 295 | self.assertEqual(resps[2]['data'], "\n\x1b[1mAnnouncements\x1b[0m:\n---") 296 | 297 | 298 | class TagsTestCase(TestCase): 299 | def setUp(self): 300 | self.monkeypatch = MonkeyPatch() 301 | 302 | def test_get_tags_invalid_json(self): 303 | """Should return 503 response when invalid json is received""" 304 | def mock_req(*args, **kwargs): 305 | return MockHTMLResponse(json='{') 306 | self.monkeypatch.setattr(problems, "request", mock_req) 307 | self.assertEqual(get_tags("a", "asc", [])[0]['code'], 503) 308 | 309 | def test_get_tags_status_not_200(self): 310 | """Should return 503 response when status code is not 200""" 311 | def mock_req(*args, **kwargs): 312 | return MockHTMLResponse(json='{"a": "A"}', status_code=400) 313 | self.monkeypatch.setattr(problems, "request", mock_req) 314 | self.assertEqual(get_tags("a", "asc", [])[0]['code'], 503) 315 | 316 | def test_get_tags(self): 317 | """Should return tags matrix""" 318 | def mock_req(*args, **kwargs): 319 | return MockHTMLResponse( 320 | json='[{"tag": "t1"}, {"tag": "t2"}, \ 321 | {"tag": "t3"}, {"tag": "t4"}, {"tag": "t5"}, {"tag": "t6"}]') 322 | self.monkeypatch.setattr(problems, "request", mock_req) 323 | self.assertEqual( 324 | get_tags("a", "asc", [])[0]['data'], [['t1', 't2', 't3', 't4', 't5'], ['t6']]) 325 | 326 | def test_get_tagged_problems_invalid_json(self): 327 | """Should return 503 response when invalid json is received""" 328 | def mock_req(*args, **kwargs): 329 | return MockHTMLResponse(json='{') 330 | self.monkeypatch.setattr(problems, "request", mock_req) 331 | self.assertEqual(get_tags("a", "asc", ["t1"])[0]['code'], 503) 332 | 333 | def test_get_tagged_problems_status_not_200(self): 334 | """Should return 503 response when status code is not 200""" 335 | def mock_req(*args, **kwargs): 336 | return MockHTMLResponse(json='{"a": "A"}', status_code=400) 337 | self.monkeypatch.setattr(problems, "request", mock_req) 338 | self.assertEqual(get_tags("a", "asc", ["t1"])[0]['code'], 503) 339 | 340 | def test_get_tagged_problems_no_data(self): 341 | """Should return table with tagged problems""" 342 | def mock_req(*args, **kwargs): 343 | return MockHTMLResponse(json='{"all_problems": null}') 344 | self.monkeypatch.setattr(problems, "request", mock_req) 345 | self.assertEqual(get_tags("a", "asc", ["t1"])[0]['code'], 404) 346 | 347 | def test_get_tagged_problems(self): 348 | """Should return table with tagged problems""" 349 | def mock_req(*args, **kwargs): 350 | return MockHTMLResponse(json='{ \ 351 | "all_problems": { \ 352 | "p1": {"code": "p1", "name": "P1", "attempted_by": 3, "solved_by": 2}, \ 353 | "p2": {"code": "p2", "name": "P2", "attempted_by": 4, "solved_by": 4} \ 354 | } \ 355 | }') 356 | self.monkeypatch.setattr(problems, "request", mock_req) 357 | resps = get_tags("Name", "asc", ["t1"]) 358 | self.assertEqual(resps[0]['data_type'], "table") 359 | self.assertEqual( 360 | resps[0]['data'], [ 361 | ['CODE', 'NAME', 'SUBMISSION', 'ACCURACY'], 362 | ['p1', 'P1', '3', '66'], 363 | ['p2', 'P2', '4', '100'] 364 | ] 365 | ) 366 | 367 | 368 | class RatingsTestCase(TestCase): 369 | def setUp(self): 370 | self.monkeypatch = MonkeyPatch() 371 | 372 | def test_get_ratings_status_not_200(self): 373 | """Should return 503 response when status code is not 200""" 374 | def mock_req(*args, **kwargs): 375 | return MockHTMLResponse(status_code=400) 376 | self.monkeypatch.setattr(problems, "request", mock_req) 377 | self.assertEqual(get_ratings("a", "a", "a", "a", "a", "a", "a")[0]['code'], 503) 378 | 379 | def test_get_ratings_invalid_json(self): 380 | """Should return 503 response when invalid json is received""" 381 | def mock_req(*args, **kwargs): 382 | return MockHTMLResponse(json='{') 383 | self.monkeypatch.setattr(problems, "request", mock_req) 384 | self.assertEqual(get_ratings("a", "a", "a", "a", "a", "a", "a")[0]['code'], 503) 385 | 386 | def test_get_ratings_null_list(self): 387 | """Should return 404 response code when `list` key value has no elements""" 388 | def mock_req(*args, **kwargs): 389 | return MockHTMLResponse(json='{"list": null}') 390 | self.monkeypatch.setattr(problems, "request", mock_req) 391 | self.assertEqual(get_ratings("a", "a", "a", "a", "a", "a", "a")[0]['code'], 404) 392 | 393 | def test_get_ratings(self): 394 | """Should return table containing ratings""" 395 | def mock_req(*args, **kwargs): 396 | return MockHTMLResponse(json='{ \ 397 | "list": [{ \ 398 | "global_rank": 1, \ 399 | "country_rank": 1, \ 400 | "username": "u1", \ 401 | "rating": 1, \ 402 | "diff": 2 \ 403 | }] \ 404 | }') 405 | self.monkeypatch.setattr(problems, "request", mock_req) 406 | resps = get_ratings("RATING", "asc", "a", "a", "a", "a", "a") 407 | self.assertEqual(resps[0]['data_type'], "table") 408 | self.assertEqual(resps[0]['data'], [ 409 | ['GLOBAL(COUNTRY)', 'USER NAME', 'RATING', 'GAIN/LOSS'], ['1 (1)', 'u1', '1', '2']]) 410 | 411 | 412 | class ContestsTestCase(TestCase): 413 | def setUp(self): 414 | self.monkeypatch = MonkeyPatch() 415 | 416 | def test_get_contests_status_not_200(self): 417 | """Should return 503 response when status code is not 200""" 418 | def mock_req(*args, **kwargs): 419 | return MockHTMLResponse(status_code=400) 420 | self.monkeypatch.setattr(problems, "request", mock_req) 421 | self.assertEqual(get_contests(False)[0]['code'], 503) 422 | 423 | def test_get_contests_no_past(self): 424 | """Should return present & future contests""" 425 | def mock_req(*args, **kwargs): 426 | return MockHTMLResponse(data="
\ 427 | \ 428 | \ 429 | \ 430 |
AB
a1b1
\ 431 | \ 432 | \ 433 | \ 434 |
AfBf
af1bf1
\ 435 | ") 436 | self.monkeypatch.setattr(problems, "request", mock_req) 437 | resps = get_contests(False) 438 | self.assertEqual(resps[0]['data'], "\x1b[1mPresent Contests:\n\x1b[0m") 439 | self.assertEqual(resps[1]['data_type'], "table") 440 | self.assertEqual(resps[1]['data'], [['A', 'B'], ['a1', 'b1']]) 441 | self.assertEqual(resps[2]['data'], "\x1b[1mFuture Contests:\n\x1b[0m") 442 | self.assertEqual(resps[3]['data_type'], "table") 443 | self.assertEqual(resps[3]['data'], [['AF', 'BF'], ['af1', 'bf1']]) 444 | 445 | def test_get_contests_show_past(self): 446 | """Should return past contests""" 447 | def mock_req(*args, **kwargs): 448 | return MockHTMLResponse(data="
\ 449 | \ 450 | \ 451 | \ 452 |
AB
a1b1
\ 453 | ") 454 | self.monkeypatch.setattr(problems, "request", mock_req) 455 | resps = get_contests(True) 456 | self.assertEqual(resps[0]['data'], '\x1b[1mPast Contests:\n\x1b[0m') 457 | self.assertEqual(resps[1]['data_type'], "table") 458 | self.assertEqual(resps[1]['data'], [['A', 'B'], ['a1', 'b1']]) 459 | 460 | 461 | class SolutionsTestCase(TestCase): 462 | def setUp(self): 463 | self.monkeypatch = MonkeyPatch() 464 | 465 | def test_get_solutions_status_not_200(self): 466 | """Should return 503 response when status code is not 200""" 467 | def mock_req(*args, **kwargs): 468 | return MockHTMLResponse(status_code=400) 469 | self.monkeypatch.setattr(problems, "request", mock_req) 470 | self.assertEqual(get_solutions("a", "a", "a", "a", "a", "a", "a")[0]['code'], 503) 471 | 472 | def test_get_solutions_invalid_problem(self): 473 | """Should return 404 response when problem code is invalid""" 474 | def mock_req(*args, **kwargs): 475 | return MockHTMLResponse(url='/p2') 476 | self.monkeypatch.setattr(problems, "request", mock_req) 477 | self.assertEqual(get_solutions("A", "asc", "p1", 1, None, None, None)[0]['code'], 404) 478 | 479 | def test_get_solutions_no_filters(self): 480 | """Should return solutions of the problem (no filters)""" 481 | def mock_req(*args, **kwargs): 482 | return MockHTMLResponse(url='/p1', data='
\ 483 | \ 484 | \ 485 |
ABCDE
a1b1c1d1e1
') 486 | self.monkeypatch.setattr(problems, "request", mock_req) 487 | resps = get_solutions("A", "asc", "p1", 1, None, None, None) 488 | self.assertEqual(resps[0]['data_type'], "table") 489 | self.assertEqual(resps[0]['data'], [['A', 'B', 'C', 'D'], ['a1', 'b1', 'c1', 'd1']]) 490 | 491 | def test_get_solutions_no_filters_with_page_info(self): 492 | """Should return solutions of the problem with page info (no filters)""" 493 | def mock_req(*args, **kwargs): 494 | return MockHTMLResponse(url='/p1', data=f'
\ 495 | \ 496 | \ 497 |
ABCDE
a1b1c1d1e1
111
') 498 | self.monkeypatch.setattr(problems, "request", mock_req) 499 | resps = get_solutions("A", "asc", "p1", 1, None, None, None) 500 | self.assertEqual(resps[0]['data_type'], "table") 501 | self.assertEqual(resps[0]['data'], [['A', 'B', 'C', 'D'], ['a1', 'b1', 'c1', 'd1']]) 502 | self.assertEqual(resps[0]['extra'], '\nPage: 111') 503 | 504 | def test_build_solution_filters(self): 505 | """Should return params dict containing solution filters""" 506 | params = build_request_params( 507 | HTML(html=f"'"), "a", "WA", "abcd", 2 512 | ) 513 | self.assertEqual( 514 | params, {'language': 'a', 'page': 1, 'status': 14, 'handle': 'abcd'}) 515 | 516 | def test_get_solution_status_not_200(self): 517 | """Should return 503 response when status code is not 200""" 518 | def mock_req(*args, **kwargs): 519 | return MockHTMLResponse(status_code=400) 520 | self.monkeypatch.setattr(problems, "request", mock_req) 521 | self.assertEqual(get_solution("a")[0]['code'], 503) 522 | 523 | def test_get_solution_not_found(self): 524 | """Should return 404 response when solution not found""" 525 | def mock_req(*args, **kwargs): 526 | return MockHTMLResponse( 527 | data=f'
{INVALID_SOLUTION_ID_MSG}
') 528 | self.monkeypatch.setattr(problems, "request", mock_req) 529 | self.assertEqual(get_solution("a")[0]['code'], 404) 530 | 531 | def test_get_solution(self): 532 | """Should return solution text""" 533 | def mock_req(*args, **kwargs): 534 | return MockHTMLResponse(data='
print("hello cc")
') 535 | self.monkeypatch.setattr(problems, "request", mock_req) 536 | self.assertEqual(get_solution("a")[0]['data'], '\nprint("hello cc")\n') 537 | -------------------------------------------------------------------------------- /tests/test_teams.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from _pytest.monkeypatch import MonkeyPatch 4 | 5 | from codechefcli import teams 6 | from tests.utils import MockHTMLResponse 7 | 8 | 9 | class TeamsTestCase(TestCase): 10 | def setUp(self): 11 | self.monkeypatch = MonkeyPatch() 12 | 13 | def test_get_team_no_name(self): 14 | """Should return empty list response when empty name is given""" 15 | self.assertEqual(teams.get_team(None), []) 16 | 17 | def test_get_team_status_not_200(self): 18 | """Should return 503 response code on any other status than 200 and 404""" 19 | def mock_req_team(*args, **kwargs): 20 | return MockHTMLResponse(status_code=500) 21 | self.monkeypatch.setattr(teams, "request", mock_req_team) 22 | self.assertEqual(teams.get_team("abcd")[0]["code"], 503) 23 | 24 | def test_get_team_status_404(self): 25 | """Should return 404 response code on 404 status code""" 26 | def mock_req_team(*args, **kwargs): 27 | return MockHTMLResponse(status_code=404) 28 | self.monkeypatch.setattr(teams, "request", mock_req_team) 29 | resps = teams.get_team("abcd") 30 | self.assertEqual(resps[0]["code"], 404) 31 | self.assertEqual(resps[0]["data"], "Team not found.") 32 | 33 | def test_get_team(self): 34 | """Should return team info""" 35 | def mock_req_team(*args, **kwargs): 36 | return MockHTMLResponse(data="

ABCD

\ 37 | \ 38 | \ 39 | \ 40 | \ 41 | \ 42 |
A:C
B:D
E:F
Information for G:G
xx
\ 43 | \ 44 | \ 45 | \ 46 |
TU
t1u1
t2u2
") 47 | self.monkeypatch.setattr(teams, "request", mock_req_team) 48 | resps = teams.get_team("abcd") 49 | self.assertEqual( 50 | resps[0]["data"], 51 | '\nABCD\n\nA: C\nB: D\nE: F\n\nInformation for G: G\n\nProblems Successfully Solved:\n' 52 | ) 53 | self.assertListEqual(resps[1]["data"], [['T', 'U'], ['t1', 'u1'], ['t2', 'u2']]) 54 | -------------------------------------------------------------------------------- /tests/test_users.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from _pytest.monkeypatch import MonkeyPatch 4 | 5 | from codechefcli import users 6 | from codechefcli.users import (HEADER, RATING_NUMBER_CLASS, RATING_RANKS_CLASS, STAR_RATING_CLASS, 7 | USER_DETAILS_CLASS, USER_DETAILS_CONTAINER_CLASS, get_user) 8 | from tests.utils import MockHTMLResponse 9 | 10 | 11 | class UsersTestCase(TestCase): 12 | def setUp(self): 13 | self.monkeypatch = MonkeyPatch() 14 | 15 | def test_get_user_empty_username(self): 16 | """Should return empty list response""" 17 | self.assertEqual(get_user(None), []) 18 | 19 | def test_get_user_status_not_200(self): 20 | """Should return 503 response on any status code other than 200""" 21 | def mock_req_user(*args, **kwargs): 22 | return MockHTMLResponse(status_code=403) 23 | self.monkeypatch.setattr(users, "request", mock_req_user) 24 | 25 | resps = get_user("abc") 26 | self.assertEqual(resps[0]["code"], 503) 27 | 28 | def test_get_user_team_name(self): 29 | """Should return 400 response when username is of a team name""" 30 | def mock_req_user(*args, **kwargs): 31 | return MockHTMLResponse(url="/teams/view/abcd") 32 | self.monkeypatch.setattr(users, "request", mock_req_user) 33 | 34 | name = "abcd" 35 | resps = get_user(name) 36 | 37 | self.assertEqual(resps[0]["code"], 400) 38 | self.assertTrue(f'--team {name}' in resps[0]["data"]) 39 | 40 | def test_get_user_not_found(self): 41 | """Should return 404 when the user is not found i.e. resp url is base url""" 42 | def mock_req_user(*args, **kwargs): 43 | return MockHTMLResponse() 44 | self.monkeypatch.setattr(users, "request", mock_req_user) 45 | 46 | resps = get_user("abcd") 47 | self.assertEqual(resps[0]["code"], 404) 48 | self.assertEqual(resps[0]["data"], "User not found.") 49 | 50 | def test_get_user(self): 51 | """Should return user info""" 52 | def mock_req_user(*args, **kwargs): 53 | return MockHTMLResponse(data=f"
\ 54 | <{HEADER}>ABCD's Profile \ 55 |
\ 56 |
  • aa: 1
  • \ 57 |
  • bb: 2
  • \ 58 |
  • cc: 3
  • \ 59 |
  • dd: 4
  • \ 60 |
    \ 61 |
    3star
    \ 62 |
    \ 63 |
    1111
    \ 64 |
    \ 65 |
  • 123
  • \ 66 |
  • 11
  • \ 67 |
    ", url="/users/abcd/") 68 | self.monkeypatch.setattr(users, "request", mock_req_user) 69 | 70 | resps = get_user("abcd") 71 | self.assertEqual( 72 | resps[0]["data"], 73 | "\n\x1b[1mUser Details for ABCD's Profile (abcd):\x1b[0m\n\nbb: 2\ncc: 3\n" 74 | "User's Teams: https://www.codechef.com/users/abcd/teams/\n\nRating: 3star 1111\nGlobal" 75 | " Rank: 123\nCountry Rank: 11\n\nFind more at: https://www.codechef.com/users/abcd/\n" 76 | ) 77 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | from requests_html import HTML 5 | 6 | from codechefcli.helpers import BASE_URL, COOKIES_FILE_PATH 7 | 8 | 9 | class MockHTMLResponse: 10 | def __init__(self, data='', status_code=200, url='', json=""): 11 | self.html = HTML(html=data) 12 | self.status_code = status_code 13 | self.url = f'{BASE_URL}{url}' 14 | self.text = json 15 | 16 | def json(self, **kwargs): 17 | return json.loads(self.text) 18 | 19 | 20 | def fake_login(init_cookies=[]): 21 | """Fake login by creating cookies file having a fake cookie""" 22 | cookies = '' 23 | if init_cookies: 24 | cookies = "\n".join([ 25 | f"Set-Cookie3: {cookie['name']}={cookie['value']}; path='/'; domain=localhost; \ 26 | port=80000; expires='2120-05-05 23:40:21Z'; version=0" for cookie in init_cookies 27 | ]) 28 | with open(COOKIES_FILE_PATH, 'w') as f: 29 | f.write(f'#LWP-Cookies-1.0\nSet-Cookie3: mykey=myvalue; path="/"; domain=localhost; port=80000; \ 30 | expires="2120-05-05 23:40:21Z"; version=0\n{cookies}') 31 | 32 | 33 | def fake_logout(): 34 | """Fake logout by deleting the cookies""" 35 | if os.path.exists(COOKIES_FILE_PATH): 36 | os.remove(COOKIES_FILE_PATH) 37 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [pep8] 2 | max-line-length = 120 --------------------------------------------------------------------------------