pax_global_header00006660000000000000000000000064147313724650014526gustar00rootroot0000000000000052 comment=a57678cec70daffcf2617d55636af12399304689 librouteros-3.4.1/000077500000000000000000000000001473137246500141045ustar00rootroot00000000000000librouteros-3.4.1/.bumpversion.cfg000066400000000000000000000003211473137246500172100ustar00rootroot00000000000000[bumpversion] current_version = 3.4.1 commit = True tag = True tag_name = {new_version} message = Release {new_version} [bumpversion:file:pyproject.toml] [bumpversion:file:CHANGELOG.rst] search = UNRELEASED librouteros-3.4.1/.github/000077500000000000000000000000001473137246500154445ustar00rootroot00000000000000librouteros-3.4.1/.github/FUNDING.yml000066400000000000000000000000201473137246500172510ustar00rootroot00000000000000patreon: luqasz librouteros-3.4.1/.github/dependabot.yml000066400000000000000000000002171473137246500202740ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: pip directory: "/" schedule: interval: daily time: "04:00" open-pull-requests-limit: 10 librouteros-3.4.1/.github/workflows/000077500000000000000000000000001473137246500175015ustar00rootroot00000000000000librouteros-3.4.1/.github/workflows/dependabot.yml000066400000000000000000000016641473137246500223400ustar00rootroot00000000000000name: Dependabot auto-merge on: pull_request permissions: contents: write pull-requests: write jobs: dependabot: runs-on: ubuntu-latest if: ${{ github.actor == 'dependabot[bot]' }} steps: - name: Dependabot metadata id: metadata uses: dependabot/fetch-metadata@v1 with: github-token: "${{ secrets.GITHUB_TOKEN }}" - name: Merge Dependabot PR if: ${{ steps.metadata.outputs.dependency-type == 'direct:development' }} run: gh pr merge --auto --merge "$PR_URL" env: PR_URL: ${{github.event.pull_request.html_url}} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Approve Dependabot PR if: ${{ steps.metadata.outputs.dependency-type == 'direct:development' }} run: gh pr review $PR_URL --approve env: PR_URL: ${{github.event.pull_request.html_url}} GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} librouteros-3.4.1/.github/workflows/release.yml000066400000000000000000000021521473137246500216440ustar00rootroot00000000000000name: Release on: push: tags: - '[0-9]+.[0-9]+.[0-9]+' jobs: test: name: Test uses: ./.github/workflows/test.yml release: name: Release needs: - test runs-on: ubuntu-20.04 container: image: lukaszkostka/librouteros:3.12 steps: - name: Checkout uses: actions/checkout@v4 with: lfs: false - name: Install Poetry uses: snok/install-poetry@v1 with: virtualenvs-create: true virtualenvs-in-project: true installer-parallel: true - name: Load cached venv id: poerty-cache uses: actions/cache@v3 with: path: .venv key: venv-${{ runner.os }}-3.12-${{ hashFiles('**/poetry.lock') }} - name: Install dependencies if: steps.poerty-cache.outputs.cache-hit != 'true' run: poetry install --no-interaction --no-root - name: Install library run: poetry install --no-interaction - name: Publish env: POETRY_PYPI_TOKEN_PYPI: ${{ secrets.PYPI_PASSWORD }} run: poetry publish --build librouteros-3.4.1/.github/workflows/test.yml000066400000000000000000000032421473137246500212040ustar00rootroot00000000000000name: Run tests on: push: branches: - '**' tags-ignore: - '[0-9]+.[0-9]+.[0-9]+' pull_request: workflow_call: jobs: test: name: Test, lint, format check runs-on: ubuntu-20.04 container: image: lukaszkostka/librouteros:${{ matrix.python-version }} env: CI: yes strategy: matrix: python-version: - "3.8" - "3.9" - "3.10" - "3.11" - "3.12" steps: - name: Checkout uses: actions/checkout@v4 with: lfs: false - name: Move images run: mv /opt/* $GITHUB_WORKSPACE/images/ - name: Install Poetry uses: snok/install-poetry@v1 with: virtualenvs-create: true virtualenvs-in-project: true installer-parallel: true - name: Load cache id: cache uses: actions/cache@v4 with: path: | .venv .mypy_cache key: venv-${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('**/poetry.lock') }} - name: Install dependencies if: steps.cache.outputs.cache-hit != 'true' run: poetry install --no-interaction --no-root - name: Install library run: poetry install --no-interaction - name: Run Ruff run: poetry run ruff check . - name: Type check run: poetry run mypy librouteros - name: Format run: > poetry run ruff format --diff librouteros tests - name: Unit tests run: poetry run pytest tests/unit - name: Integration tests run: poetry run pytest tests/integration librouteros-3.4.1/.gitignore000066400000000000000000000004121473137246500160710ustar00rootroot00000000000000#python compiled files *.py[cod] __pycache__ #virtual env .env #package related files / dirs *.deb dist build sdist MANIFEST .project *.egg-info #pytest cache .cache .pytest_cache .mypy_cache # IDE stuff .idea .pydevproject .settings .vscode Pipfile.lock .venvlibrouteros-3.4.1/.readthedocs.yaml000066400000000000000000000001511473137246500173300ustar00rootroot00000000000000version: 2 build: os: ubuntu-22.04 tools: python: "3.12" sphinx: configuration: docs/conf.py librouteros-3.4.1/CHANGELOG.rst000066400000000000000000000036011473137246500161250ustar00rootroot000000000000003.4.1 ---------- * Revert `SYNC_DEFAULTS` to `DEFAULTS` 3.4.0 ---------- * Add async support 3.3.1 ---------- * Fix empty `select()` `=.proplist=` argument 3.3.0 ---------- * Allow empty `select()` * Drop python 3.7 support (end of life) * Drop python 3.6 support (end of life) 3.2.1 ---------- * Fix non ASCII API word encoding 3.2.0 ---------- * Ignore character decoding errors 3.1.0 ---------- * Add In operator 3.0.2 ---------- - Fix generator yielding #94 3.0.1 __________ - Add typing annotations 3.0.0 ---------- - Introduce query support. - Path object for easy query and common operations. - yield each item instead of returning tuple of items. Greatly reduces memory usage. - Drop pre python 3.6 support. - Replace pylava with pylint. - Add yapf formatter. - Replace py.path with builtin pathlib. - connect() accepts only one login_method parameter. - Drop socker exceptions wrapping. - Remove ConnectionError exception. - Renamed LibError to LibRouterosError. - Changed exceptions inheritance. - Removed joinPath() 2.4.0 ---------- - Add query support. #11 2.3.1 ---------- - Fix raising TrapError when failed to login. #63 2.3.0 ---------- - Add rawCmd() method for passing custom queries. 2.2.0 ---------- - Excplicit login_method parameter for login using new or old auth method. 2.1.1 ---------- - Fix testing with pip >= 18.x 2.1.0 ---------- - Support new auth method introduced in 6.43 2.0.0 ------ - Drop support for python 3.2, 3.3 - Added ssl / apis support 1.0.5 ------ - Fix loop in SocketTransport.read() (pull request #23) 1.0.4 ------ - Fix multiple byte word encoding during reading (issue #12) 1.0.3 ------ - Provide option to use user defined encoding 1.0.2 ------ - Fix E722 do not use bare except [pep8] - Test with python 3.6 - Integration tests with qemu emulated RouterOs image - Pin setuptools to higher version 1.0.1 ------ - First release librouteros-3.4.1/LICENSE000066400000000000000000000432541473137246500151210ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. librouteros-3.4.1/README.rst000066400000000000000000000001611473137246500155710ustar00rootroot00000000000000Documentation ============= Documentation resides over at `readthedocs `_ librouteros-3.4.1/apicli.py000077500000000000000000000036651473137246500157340ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """Command line interface for debugging purpouses.""" import logging import getpass from argparse import ArgumentParser from sys import stdout, stdin from select import select from os import linesep from librouteros import connect from librouteros.exceptions import TrapError, FatalError argParser = ArgumentParser(description="mikrotik api cli interface") argParser.add_argument("host", type=str, help="host to with to connect. may be fqdn, ipv4 or ipv6 address") argParser.add_argument("-u", "--user", type=str, required=True, help="username") argParser.add_argument("-p", "--port", type=int, default=8728, help="port to connect to (default 8728)") args = argParser.parse_args() mainlog = logging.getLogger("librouteros") console = logging.StreamHandler(stdout) mainlog.setLevel(logging.DEBUG) formatter = logging.Formatter(fmt="%(message)s") console.setFormatter(formatter) mainlog.addHandler(console) def selectloop(api): snt = [] while True: proto = api.protocol sk = proto.transport.sock rlist, wlist, errlist = select([sk, stdin], [], [], None) if sk in rlist: proto.readSentence() if stdin in rlist: line = stdin.readline() line = line.split(linesep) line = line[0] if line: snt.append(line) elif not line and snt: proto.writeSentence(snt[0], *snt[1:]) snt = [] def main(): pw = getpass.getpass() try: api = connect(args.host, args.user, pw, logger=mainlog) except (TrapError, ConnectionError) as err: exit(err) except KeyboardInterrupt: pass else: try: selectloop(api) except KeyboardInterrupt: pass except (ConnectionError, FatalError) as e: print(e) finally: api.close() if __name__ == "__main__": main() librouteros-3.4.1/docker/000077500000000000000000000000001473137246500153535ustar00rootroot00000000000000librouteros-3.4.1/docker/3.10.dockerfile000066400000000000000000000006351473137246500177710ustar00rootroot00000000000000FROM python:3.10-slim ENV DEBIAN_FRONTEND noninteractive RUN apt-get update; \ apt-get install -y --no-install-recommends --no-install-suggests \ qemu-system-i386 \ curl \ qemu-utils; \ pip install --no-cache-dir -U setuptools pip twine pipenv; \ apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ rm -rf /var/lib/apt/lists/* COPY images/*.qcow2 /opt/ librouteros-3.4.1/docker/3.11.dockerfile000066400000000000000000000006361473137246500177730ustar00rootroot00000000000000FROM python:3.11-slim ENV DEBIAN_FRONTEND noninteractive RUN apt-get update; \ apt-get install -y --no-install-recommends --no-install-suggests \ qemu-system-i386 \ curl \ qemu-utils; \ pip install --no-cache-dir -U setuptools pip twine pipenv; \ apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ rm -rf /var/lib/apt/lists/* COPY images/*.qcow2 /opt/ librouteros-3.4.1/docker/3.12.dockerfile000066400000000000000000000006371473137246500177750ustar00rootroot00000000000000FROM python:3.12-slim ENV DEBIAN_FRONTEND noninteractive RUN apt-get update; \ apt-get install -y --no-install-recommends --no-install-suggests \ qemu-system-i386 \ curl \ qemu-utils; \ pip install --no-cache-dir -U setuptools pip twine pipenv; \ apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ rm -rf /var/lib/apt/lists/* COPY images/*.qcow2 /opt/ librouteros-3.4.1/docker/3.8.dockerfile000066400000000000000000000006331473137246500177160ustar00rootroot00000000000000FROM python:3.8-slim ENV DEBIAN_FRONTEND noninteractive RUN apt-get update; \ apt-get install -y --no-install-recommends --no-install-suggests \ qemu-system-i386 \ curl \ qemu-utils; \ pip install --no-cache-dir -U setuptools pip twine pipenv; \ apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ rm -rf /var/lib/apt/lists/* COPY images/*.qcow2 /opt/ librouteros-3.4.1/docker/3.9.dockerfile000066400000000000000000000006331473137246500177170ustar00rootroot00000000000000FROM python:3.9-slim ENV DEBIAN_FRONTEND noninteractive RUN apt-get update; \ apt-get install -y --no-install-recommends --no-install-suggests \ qemu-system-i386 \ curl \ qemu-utils; \ pip install --no-cache-dir -U setuptools pip twine pipenv; \ apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ rm -rf /var/lib/apt/lists/* COPY images/*.qcow2 /opt/ librouteros-3.4.1/docker/do.sh000077500000000000000000000002661473137246500163200ustar00rootroot00000000000000#!/bin/sh for ver in 3.8 3.9 3.10 3.11 3.12 do docker buildx build --platform linux/amd64,linux/arm64 --push -t lukaszkostka/librouteros:${ver} -f docker/${ver}.dockerfile . done librouteros-3.4.1/docs/000077500000000000000000000000001473137246500150345ustar00rootroot00000000000000librouteros-3.4.1/docs/.gitignore000066400000000000000000000000071473137246500170210ustar00rootroot00000000000000_build librouteros-3.4.1/docs/Makefile000066400000000000000000000127201473137246500164760ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/librouteros.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/librouteros.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/librouteros" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/librouteros" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." librouteros-3.4.1/docs/_static/000077500000000000000000000000001473137246500164625ustar00rootroot00000000000000librouteros-3.4.1/docs/_static/custom.css000066400000000000000000000002331473137246500205040ustar00rootroot00000000000000div.body p, div.body dd, div.body li, div.body blockquote { -moz-hyphens: none; -ms-hyphens: none; -webkit-hyphens: none; hyphens: none; } librouteros-3.4.1/docs/api_analysis.rst000066400000000000000000000133671473137246500202540ustar00rootroot00000000000000Api analysis ============ This document aims to cover in depth analysis of routeros API. Lines that begin with ``--->`` represent data received from a device. Lines that start with ``<---`` represent data send to a device. End of sentence is marked with ``EOS``. Succesfull login (pre 6.43) --------------------------- .. code-block:: none <--- /login <--- EOS ---> !done ---> =ret=xxxxxxxxxxxxxxxxxxxxx ---> EOS <--- /login <--- =name=admin <--- =response=xxxxxxxxxxxxxxx <--- EOS ---> !done ---> EOS Succesfull login (post 6.42) ---------------------------- .. code-block:: none <--- /login <--- =name=admin <--- =password=xxxxxxxxxxxxxxx <--- EOS ---> !done ---> EOS Failed login attempt (pre 6.43) ------------------------------- .. code-block:: none <--- /login <--- EOS ---> !done ---> =ret=xxxxxxxxxxxxxxxxxxxxx ---> EOS <--- /login <--- =name=admin <--- =response=xxxxxxxxxxxxxxxxxxxxx <--- EOS ---> !trap ---> =message=cannot log in ---> EOS ---> !done ---> EOS Logging off ----------- .. code-block:: none <--- /quit <--- EOS ---> !fatal ---> session terminated on request ---> EOS Multiple empty responses ------------------------ .. code-block:: none <--- /ip/service/print <--- =.proplist=comment <--- EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !re ---> EOS ---> !done ---> EOS Adding element -------------- .. code-block:: none <--- /ip/address/add <--- =address=192.168.1.1/24 <--- =interface=ether1 <--- EOS ---> !done ---> =ret=*3 ---> EOS Canceling ``listen`` -------------------- Command returns ``!trap`` which is not actually any error at all: .. code-block:: none <--- '/ip/address/listen' <--- '.tag=10' <--- EOS ---> '!re' ---> '.tag=10' ---> '=.id=*A' ---> '=address=1.1.1.1/32' ---> '=network=1.1.1.1' ---> '=interface=br-lan' ---> '=actual-interface=br-lan' ---> '=invalid=false' ---> '=dynamic=false' ---> '=disabled=false' ---> EOS ---> '!re' ---> '.tag=10' ---> '=.id=*A' ---> '=.dead=true' ---> EOS <--- '/cancel' <--- '=tag=10' <--- '.tag=20' <--- EOS ---> '!trap' ---> '.tag=10' ---> '=category=2' ---> '=message=interrupted' ---> EOS ---> '!done' ---> '.tag=20' ---> EOS ---> '!done' ---> '.tag=10' ---> EOS Fetching from url ----------------- .. code-block:: none <--- '/tool/fetch' <--- '=url=http://ping.online.net/10Mo.dat' <--- '.tag=1' <--- EOS ---> '!re' ---> '.tag=1' ---> '=status=connecting' ---> '=.section=0' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=731' ---> '=total=9765' ---> '=duration=1s' ---> '=.section=1' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=1579' ---> '=total=9765' ---> '=duration=2s' ---> '=.section=2' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=2427' ---> '=total=9765' ---> '=duration=3s' ---> '=.section=3' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=3275' ---> '=total=9765' ---> '=duration=4s' ---> '=.section=4' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=4139' ---> '=total=9765' ---> '=duration=5s' ---> '=.section=5' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=4987' ---> '=total=9765' ---> '=duration=6s' ---> '=.section=6' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=5839' ---> '=total=9765' ---> '=duration=7s' ---> '=.section=7' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=6687' ---> '=total=9765' ---> '=duration=8s' ---> '=.section=8' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=7551' ---> '=total=9765' ---> '=duration=9s' ---> '=.section=9' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=8415' ---> '=total=9765' ---> '=duration=10s' ---> '=.section=10' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=9279' ---> '=total=9765' ---> '=duration=12s' ---> '=.section=11' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=finished' ---> '=downloaded=9765' ---> '=total=9765' ---> '=duration=13s' ---> '=.section=12' ---> EOS ---> '!done' ---> '.tag=1' ---> EOS Canceling fetch --------------- .. code-block:: none <--- '/tool/fetch' <--- '=url=http://ping.online.net/10Mo.dat' <--- '.tag=1' <--- EOS ---> '!re' ---> '.tag=1' ---> '=status=connecting' ---> '=.section=0' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=18' ---> '=total=9765' ---> '=duration=0s' ---> '=.section=1' ---> EOS ---> '!re' ---> '.tag=1' ---> '=status=downloading' ---> '=downloaded=853' ---> '=total=9765' ---> '=duration=1s' ---> '=.section=2' ---> EOS <--- '/cancel' <--- '=tag=1' <--- EOS ---> '!trap' ---> '.tag=1' ---> '=category=2' ---> '=message=interrupted' ---> EOS ---> '!done' ---> EOS ---> '!done' ---> '.tag=1' ---> EOS librouteros-3.4.1/docs/conf.py000066400000000000000000000041271473137246500163370ustar00rootroot00000000000000# -*- coding: utf-8 -*- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.5' # Add any Sphinx extension module names here, as strings. # They can be extensions coming with Sphinx (named 'sphinx.ext.*') # or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = 'librouteros' copyright = u'Łukasz Kostka' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. language = 'en' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # The theme to use for HTML and HTML Help pages. html_theme = 'alabaster' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If true, links to the reST sources are added to the pages. html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = True # Output file base name for HTML help builder. htmlhelp_basename = 'librouteros' html_theme_options = { 'fixed_sidebar': True, 'github_user': 'luqasz', 'github_repo': 'librouteros', 'page_width': '1000px', } librouteros-3.4.1/docs/connect.rst000066400000000000000000000040561473137246500172240ustar00rootroot00000000000000Connect ======= Unencrypted ----------- .. code-block:: python from librouteros import connect, async_connect api = connect( username='admin', password='abc', host='some.address.com', ) # For async version use async_connect api = await async_connect( username='admin', password='abc', host='some.address.com', ) Encrypted --------- Before connecting, ``api-ssl`` service on routeros must be enabled. For more information on how to generate certificates see `MikroTik wiki `_. After that, create your default `SSLContext `_ and fine tune for your needs. Code below allows connecting to API without ceritficate. .. code-block:: python import ssl from librouteros import connect ctx = ssl.create_default_context() ctx.check_hostname = False ctx.set_ciphers('ADH:@SECLEVEL=0') api = connect( username='admin', password='abc', host='some.address.com', ssl_wrapper=ctx.wrap_socket, port=8729 ) If you need to pass any other parameters like ``server_name``, use `partial `_. .. code-block:: python from functools import partial ssl_wrapper=partial( ctx.wrap_socket, server_hostname='some.address.com', ) Auth methods ------------ Starting from routeros ``6.43``, token auth method was replaced by plain text. By default library will use plain text method. You can force library to use token method: .. code-block:: python from librouteros.login import plain, token # for post 6.42 (plain text password) method = plain # for pre 6.43 (with token) method = token api = connect( username='admin', password='abc', host='some.address.com', login_method=method, ) .. note:: Library will not try different methods untill it will log in. librouteros-3.4.1/docs/contributing.rst000066400000000000000000000002751473137246500203010ustar00rootroot00000000000000Contributing ============ To submit a feature requests or a bug report, please use issues from within github. If you would like to submit a patch please contact author or use pull request. librouteros-3.4.1/docs/index.rst000066400000000000000000000021601473137246500166740ustar00rootroot00000000000000Librouteros - Routeros api implementation ========================================= .. image:: https://travis-ci.org/luqasz/librouteros.svg?branch=master :target: https://travis-ci.org/luqasz/librouteros :alt: Tests .. image:: https://img.shields.io/pypi/v/librouteros.svg :target: https://pypi.python.org/pypi/librouteros/ :alt: Latest PyPI version .. image:: https://img.shields.io/pypi/pyversions/librouteros.svg :target: https://pypi.python.org/pypi/librouteros/ :alt: Supported Python Versions .. image:: https://img.shields.io/pypi/l/librouteros.svg :target: https://pypi.python.org/pypi/librouteros/ :alt: License .. image:: https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg :target: https://saythanks.io/to/luqasz :alt: Say Thanks About _____ Python implementation of `routeros api `_. This library uses `semantic versioning `_. On major version things may break, so pin version in dependencies. .. toctree:: :maxdepth: 2 introduction connect path query api_analysis license contributing librouteros-3.4.1/docs/introduction.rst000066400000000000000000000007331473137246500203120ustar00rootroot00000000000000Introduction ============ Features -------- * Python type casting * Key and values stored in dictionary * Source address, port specification * TLS/SSL socket encryption * Logging support Limitations ----------- * No support for sentence tagging. * No asynchronous support for reading/writing Requirements ------------ * Python 3, with sufficiently recent versions of ``pip`` and ``setuptools`` * Mock (for runing unit tests). * ``qemu`` for running integration tests. librouteros-3.4.1/docs/license.rst000066400000000000000000000000671473137246500172130ustar00rootroot00000000000000License ------- .. include:: ../LICENSE :literal: librouteros-3.4.1/docs/path.rst000066400000000000000000000040331473137246500165220ustar00rootroot00000000000000Path object =========== ``Path`` object represents absolute command path within routeros. e.g. ``/ip/address``. You can traverse down in tree with ``join()`` method. Works same as python `join() `_. .. code-block:: python # First create desired path. interfaces = api.path('interface') # Traverse down into /interfaces/ethernet ethernet = interfaces.join('ethernet') # path() and join() accepts multiple arguments ips = api.path('ip', 'address') Get all ------- .. code-block:: python # Path objects are iterable tuple(interfaces) # This also will work, as well as anything else you can do with iterables for item in interfaces: print(item) # async version async for item in interfaces: print(item) # or you can use list comprehension items = [item async for item in interfaces] Add --- .. code-block:: python # Will return newly created .id path.add(interface='ether1', address='172.31.31.1/24') # async version await path.add(interface='ether1', address='172.31.31.1/24') Remove ------ .. code-block:: python # Pass each .id as an argument. path.remove('*1', '*2') # async version await path.remove('*1', '*2') .. note:: ``.id`` change on reboot. Always read them first. Update ------ .. code-block:: python params = {'disabled': True, '.id' :'*7'} path.update(**params) # async version await path.update(**params) .. note:: ``.id`` change on reboot. Always read them first. Arbitrary command ----------------- For all other commands, call ``Path`` object directly. Remember to consume the result since it returns a generator. As a first argument, pass command that you wish to run without absolute path. .. code-block:: python script = api.path('system', 'script') # Will run /system/script/run with desired .id tuple(script('run', **{'.id': '*1'})) # async version [item async for item in script('run', **{'.id': '*1'})] librouteros-3.4.1/docs/query.rst000066400000000000000000000036761473137246500167470ustar00rootroot00000000000000Query ===== Basic usage ----------- Get only ``name`` and ``disabled`` keys from all interfaces. .. code-block:: python from librouteros.query import Key # Each key must be created first in order to reference it later. name = Key('name') disabled = Key('disabled') for row in api.path('/interface').select(name, disabled): print(row) Advanced Usage -------------- Adding ``where()``, allows to fine tune search criteria. Syntax is very similar to a SQL query. .. code-block:: python name = Key('name') disabled = Key('disabled') query = api.path('/interface').select(name, disabled).where( disabled == False, Or( name == 'ether2', name == 'wlan-lan', ), ) Above code demonstrates how to select ``name``, ``disabled`` fields where each interface is disabled and ``name`` is equal to one of ``ether2``, ``wlan-lan``. If you do not specify any logical operation within ``where()``, them it defaults to `And()`. Above example can be rewritten using ``In`` operator. .. code-block:: python name = Key('name') disabled = Key('disabled') query = api.path('/interface').select(name, disabled).where( disabled == False, name.In('ether2', 'wlan-lan'), ) Select all keys/fields. .. code-block:: python name = Key('name') disabled = Key('disabled') query = api.path('/interface').select().where( disabled == False, name.In('ether2', 'wlan-lan'), ) Usable operators ---------------- ======== ========= operator example ======== ========= ``==`` ``name == 'ether2'`` ``!=`` ``name != 'ether2'`` ``>`` ``mtu > 1500`` ``<`` ``mtu < 1400`` ``In`` ``name.In('ether1', 'ether2', 'wlan1')`` ======== ========= Logical operators ----------------- ``And``, ``Or``. Each operator takes at least two expressions and performs a logical operation translating it to API query equivalents. librouteros-3.4.1/images/000077500000000000000000000000001473137246500153515ustar00rootroot00000000000000librouteros-3.4.1/images/.gitignore000066400000000000000000000000101473137246500173300ustar00rootroot00000000000000*.qcow2 librouteros-3.4.1/images/README.md000066400000000000000000000006001473137246500166240ustar00rootroot00000000000000# How to create qcow2 images. `VERSION` is exact routeros version number. ### Create disk image. ``` qemu-img create -f qcow2 routeros_VERSION.qcow2 64m ``` ### Install routeros. ``` qemu-system-x86_64 \ -m 64 \ -hda routeros_VERSION.qcow2 \ -net nic,model=virtio \ -cdrom ISO_FILE.iso \ ``` * Install every package except `kvm` * Add `dhcp-client` on `ether1` librouteros-3.4.1/librouteros/000077500000000000000000000000001473137246500164555ustar00rootroot00000000000000librouteros-3.4.1/librouteros/__init__.py000066400000000000000000000073001473137246500205660ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import asyncio from socket import create_connection from collections import ChainMap from librouteros.exceptions import ( ConnectionClosed, FatalError, ) from librouteros.connections import SocketTransport, AsyncSocketTransport from librouteros.protocol import ApiProtocol, AsyncApiProtocol from librouteros.login import ( plain, token, # noqa: F401 BACK_COMP async_plain, ) from librouteros.api import Api, AsyncApi DEFAULTS = { "timeout": 10, "port": 8728, "saddr": "", "subclass": Api, "encoding": "ASCII", "ssl_wrapper": lambda sock: sock, "login_method": plain, } ASYNC_DEFAULTS = { "timeout": 10, "port": 8728, "saddr": "", "subclass": AsyncApi, "encoding": "ASCII", "ssl_wrapper": lambda sock: sock, "login_method": async_plain, } def connect(host: str, username: str, password: str, **kwargs) -> Api: """ Connect and login to routeros device. Upon success return a Api class. :param host: Hostname to connecto to. May be ipv4,ipv6,FQDN. :param username: Username to login with. :param password: Password to login with. Only ASCII characters allowed. :param timeout: Socket timeout. Defaults to 10. :param port: Destination port to be used. Defaults to 8728. :param saddr: Source address to bind to. :param subclass: Subclass of Api class. Defaults to Api class from library. :param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with. :param login_method: Callable with login method. """ arguments = ChainMap(kwargs, DEFAULTS) transport = create_transport(host, **arguments) protocol = ApiProtocol(transport=transport, encoding=arguments["encoding"]) api: Api = arguments["subclass"](protocol=protocol) try: arguments["login_method"](api=api, username=username, password=password) return api except (ConnectionClosed, FatalError): transport.close() raise async def async_connect(host: str, username: str, password: str, **kwargs) -> AsyncApi: """ Connect and login to routeros device. Upon success return a Api class. :param host: Hostname to connecto to. May be ipv4,ipv6,FQDN. :param username: Username to login with. :param password: Password to login with. Only ASCII characters allowed. :param timeout: Socket timeout. Defaults to 10. :param port: Destination port to be used. Defaults to 8728. :param saddr: Source address to bind to. :param subclass: Subclass of Api class. Defaults to Api class from library. :param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with. :param login_method: Callable with login method. """ arguments = ChainMap(kwargs, ASYNC_DEFAULTS) transport = await async_create_transport(host, **arguments) protocol = AsyncApiProtocol(transport=transport, encoding=arguments["encoding"], timeout=arguments["timeout"]) api: AsyncApi = arguments["subclass"](protocol=protocol) try: await arguments["login_method"](api=api, username=username, password=password) return api except (ConnectionClosed, FatalError): await transport.close() raise def create_transport(host: str, **kwargs) -> SocketTransport: sock = create_connection((host, kwargs["port"]), kwargs["timeout"], (kwargs["saddr"], 0)) sock = kwargs["ssl_wrapper"](sock) return SocketTransport(sock=sock) async def async_create_transport(host: str, **kwargs) -> AsyncSocketTransport: reader, writer = await asyncio.wait_for( asyncio.open_connection(host=host, port=kwargs["port"]), timeout=kwargs["timeout"], ) return AsyncSocketTransport(reader=reader, writer=writer) librouteros-3.4.1/librouteros/api.py000066400000000000000000000174331473137246500176100ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import typing from posixpath import join as pjoin from librouteros.exceptions import TrapError, MultiTrapError from librouteros.protocol import ( compose_word, parse_word, ApiProtocol, AsyncApiProtocol, ) from librouteros import query from librouteros.types import ( ReplyDict, ResponseIter, AsyncResponseIter, Response, ) class Api: def __init__(self, protocol: ApiProtocol): self.protocol = protocol def __call__(self, cmd: str, **kwargs: typing.Any) -> ResponseIter: """ Call Api with given command. Yield each row. :param cmd: Command word. eg. /ip/address/print :param kwargs: Dictionary with optional arguments. """ words = (compose_word(key, value) for key, value in kwargs.items()) self.protocol.writeSentence(cmd, *words) yield from self.readResponse() def rawCmd(self, cmd: str, *words: str) -> ResponseIter: """ Call Api with given command and raw words. End user is responsible to properly format each api word argument. :param cmd: Command word. eg. /ip/address/print :param args: Iterable with optional plain api arguments. """ self.protocol.writeSentence(cmd, *words) yield from self.readResponse() def readSentence(self) -> typing.Tuple[str, ReplyDict]: """ Read one sentence and parse words. :returns: Reply word, dict with attribute words. """ reply_word, words = self.protocol.readSentence() return reply_word, dict(parse_word(word) for word in words) def readResponse(self) -> Response: """ Yield each sentence untill !done is received. :throws TrapError: If one !trap is received. :throws MultiTrapError: If > 1 !trap is received. """ traps = [] reply_word = None response = [] while reply_word != "!done": reply_word, words = self.readSentence() if reply_word == "!trap": traps.append(TrapError(**words)) elif reply_word in ("!re", "!done") and words: response.append(words) if len(traps) > 1: raise MultiTrapError(*traps) if len(traps) == 1: raise traps[0] return response def close(self) -> None: self.protocol.close() def path(self, *path: str): return Path( path="", api=self, ).join(*path) class Path: """Represents absolute command path.""" def __init__(self, path: str, api: Api): self.path = path self.api = api def select(self, *keys: query.Key) -> query.Query: return query.Query(path=self, keys=keys, api=self.api) def __str__(self) -> str: return self.path def __repr__(self) -> str: return f"<{self.__class__.__name__} {self}>" def __iter__(self) -> ResponseIter: yield from self("print") def __call__(self, cmd: str, **kwargs: typing.Any) -> ResponseIter: yield from self.api( self.join(cmd).path, **kwargs, ) def join(self, *path: str): """Join current path with one or more path strings.""" return Path( api=self.api, path=pjoin("/", self.path, *path).rstrip("/"), ) def remove(self, *ids: str) -> None: joined = ",".join(ids) tuple( self( "remove", **{".id": joined}, ) ) def add(self, **kwargs: typing.Any) -> str: ret = self( "add", **kwargs, ) return tuple(ret)[0]["ret"] def update(self, **kwargs: typing.Any) -> None: tuple( self( "set", **kwargs, ) ) class AsyncApi: def __init__(self, protocol: AsyncApiProtocol): self.protocol = protocol async def __call__(self, cmd: str, **kwargs: typing.Any) -> AsyncResponseIter: """ Call Api with given command. Yield each row. :param cmd: Command word. eg. /ip/address/print :param kwargs: Dictionary with optional arguments. """ words = (compose_word(key, value) for key, value in kwargs.items()) await self.protocol.writeSentence(cmd, *words) response = await self.readResponse() for item in response: yield item async def rawCmd(self, cmd: str, *words: str) -> AsyncResponseIter: """ Call Api with given command and raw words. End user is responsible to properly format each api word argument. :param cmd: Command word. eg. /ip/address/print :param args: Iterable with optional plain api arguments. """ await self.protocol.writeSentence(cmd, *words) response = await self.readResponse() for item in response: yield item async def readSentence(self) -> typing.Tuple[str, ReplyDict]: """ Read one sentence and parse words. """ # Assuming readSentence is also an async method in the protocol reply_word, words = await self.protocol.readSentence() return reply_word, dict(parse_word(word) for word in words) async def readResponse(self) -> Response: """ Yield each sentence untill !done is received. :throws TrapError: If one !trap is received. :throws MultiTrapError: If > 1 !trap is received. """ traps = [] reply_word = None response = [] while reply_word != "!done": reply_word, words = await self.readSentence() if reply_word == "!trap": traps.append(TrapError(**words)) elif reply_word in ("!re", "!done") and words: response.append(words) if len(traps) > 1: raise MultiTrapError(*traps) if len(traps) == 1: raise traps[0] return response async def close(self) -> None: await self.protocol.close() def path(self, *path: str): return AyncPath( path="", api=self, ).join(*path) class AyncPath: """Represents absolute command path.""" def __init__(self, path: str, api: AsyncApi): self.path = path self.api = api def select(self, *keys: query.Key) -> query.AsyncQuery: return query.AsyncQuery(path=self, keys=keys, api=self.api) def __str__(self) -> str: return self.path def __repr__(self) -> str: return f"<{self.__class__.__name__} {self}>" async def __aiter__(self) -> AsyncResponseIter: async for response in self("print"): yield response async def __call__(self, cmd: str, **kwargs: typing.Any) -> AsyncResponseIter: async for response in self.api( self.join(cmd).path, **kwargs, ): yield response def join(self, *path: str): """Join current path with one or more path strings.""" return AyncPath( api=self.api, path=pjoin("/", self.path, *path).rstrip("/"), ) async def remove(self, *ids: str) -> None: joined = ",".join(ids) [ response async for response in self( "remove", **{".id": joined}, ) ] async def add(self, **kwargs: typing.Any) -> str: response = [ response async for response in self( "add", **kwargs, ) ] return response[0]["ret"] async def update(self, **kwargs: typing.Any) -> None: [ response async for response in self( "set", **kwargs, ) ] librouteros-3.4.1/librouteros/connections.py000066400000000000000000000036521473137246500213570ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from socket import socket from librouteros.exceptions import ConnectionClosed from asyncio import StreamReader, StreamWriter class SocketTransport: def __init__(self, sock: socket): self.sock = sock def write(self, data: bytes) -> None: """ Write given bytes to socket. Loop as long as every byte in string is written unless exception is raised. """ self.sock.sendall(data) def read(self, length: int) -> bytes: """ Read as many bytes from socket as specified in length. Loop as long as every byte is read unless exception is raised. """ data = bytearray() while len(data) != length: data += self.sock.recv((length - len(data))) if not data: raise ConnectionClosed("Connection unexpectedly closed.") return data def close(self) -> None: self.sock.close() class AsyncSocketTransport: def __init__(self, reader: StreamReader, writer: StreamWriter): self.reader = reader self.writer = writer async def write(self, data: bytes) -> None: """ Write given bytes to socket. Loop as long as every byte in string is written unless exception is raised. """ self.writer.write(data) await self.writer.drain() async def read(self, length: int) -> bytes: """ Read as many bytes from socket as specified in length. Loop as long as every byte is read unless exception is raised. """ data = bytearray() while len(data) != length: data += await self.reader.read((length - len(data))) if not data: raise ConnectionClosed("Connection unexpectedly closed.") # print data for debugging return data async def close(self) -> None: self.writer.close() await self.writer.wait_closed() librouteros-3.4.1/librouteros/exceptions.py000066400000000000000000000024211473137246500212070ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import typing class LibRouterosError(Exception): """Base exception for all other.""" class ConnectionClosed(LibRouterosError): """Raised when connection have been closed.""" class ProtocolError(LibRouterosError): """Raised when e.g. encoding/decoding fails.""" class FatalError(ProtocolError): """Exception raised when !fatal is received.""" class TrapError(ProtocolError): """ Exception raised when !trap is received. :param int category: Optional integer representing category. :param str message: Error message. """ def __init__(self, message: str, category: typing.Union[None, int] = None): self.category = category self.message = message super().__init__() def __str__(self) -> str: return str(self.message.replace("\r\n", ",")) def __repr__(self) -> str: return f"{self.__class__.__name__}({self})" class MultiTrapError(ProtocolError): """ Exception raised when multiple !trap words have been received in one response. :param traps: TrapError instances. """ def __init__(self, *traps: TrapError): self.traps = traps super().__init__() def __str__(self) -> str: return ", ".join(str(trap) for trap in self.traps) librouteros-3.4.1/librouteros/login.py000066400000000000000000000030641473137246500201420ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import typing from binascii import unhexlify, hexlify # pylint: disable=no-name-in-module from hashlib import md5 def encode_password(token: str, password: str) -> str: # pylint: disable=redefined-outer-name token_bytes = token.encode("ascii", "strict") token_bytes = unhexlify(token) password_bytes = password.encode("ascii", "strict") hasher = md5() hasher.update(b"\x00" + password_bytes + token_bytes) password_bytes = hexlify(hasher.digest()) return "00" + password_bytes.decode("ascii", "strict") def token(api: typing.Any, username: str, password: str) -> None: """Login using pre routeros 6.43 authorization method.""" sentence = api("/login") tok = tuple(sentence)[0]["ret"] encoded = encode_password(tok, password) tuple(api("/login", **{"name": username, "response": encoded})) def plain(api: typing.Any, username: str, password: str) -> None: """Login using post routeros 6.43 authorization method.""" tuple(api("/login", **{"name": username, "password": password})) async def async_plain(api, username, password): [response async for response in api("/login", **{"name": username, "password": password})] async def async_token(api: typing.Any, username: str, password: str) -> None: """Login using pre routeros 6.43 authorization method.""" sentence = [response async for response in api("/login")] tok = sentence[0]["ret"] encoded = encode_password(tok, password) [response async for response in api("/login", **{"name": username, "response": encoded})] librouteros-3.4.1/librouteros/protocol.py000066400000000000000000000201771473137246500206770ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import typing from struct import pack, unpack from logging import getLogger, NullHandler from librouteros.exceptions import ( ProtocolError, FatalError, ) from librouteros.connections import SocketTransport, AsyncSocketTransport import asyncio LOGGER = getLogger("librouteros") LOGGER.addHandler(NullHandler()) def parse_word(word: str) -> typing.Tuple[str, typing.Any]: """ Split given attribute word to key, value pair. Values are casted to python equivalents. :param word: API word. :returns: Key, value pair. """ mapping = {"yes": True, "true": True, "no": False, "false": False} _, key, value = word.split("=", 2) try: value = int(value) # type: ignore except ValueError: value = mapping.get(value, value) # type: ignore return (key, value) def cast_to_api(value: typing.Any) -> str: """Cast python equivalent to API.""" mapping = {True: "yes", False: "no"} # this is necesary because 1 == True, 0 == False if type(value) == int: # noqa: E721 return str(value) return mapping.get(value, str(value)) def compose_word(key: str, value: typing.Any) -> str: """ Create a attribute word from key, value pair. Values are casted to api equivalents. """ return f"={key}={cast_to_api(value)}" class Encoder: def encodeSentence(self, *words: str) -> bytes: """ Encode given sentence in API format. :param words: Words to endoce. :returns: Encoded sentence. """ encoded = b"".join(self.encodeWord(word) for word in words) # append EOS (end of sentence) byte encoded += b"\x00" return encoded def encodeWord(self, word: str) -> bytes: """ Encode word in API format. :param word: Word to encode. :returns: Encoded word. """ # pylint: disable=no-member encoded_word = word.encode(encoding=self.encoding, errors="strict") # type: ignore return Encoder.encodeLength(len(encoded_word)) + encoded_word @staticmethod def encodeLength(length: int) -> bytes: """ Encode given length in mikrotik format. :param length: Integer < 268435456. :returns: Encoded length. """ if length < 128: ored_length = length offset = -1 elif length < 16384: ored_length = length | 0x8000 offset = -2 elif length < 2097152: ored_length = length | 0xC00000 offset = -3 elif length < 268435456: ored_length = length | 0xE0000000 offset = -4 else: raise ProtocolError(f"Unable to encode length of {length}") return pack("!I", ored_length)[offset:] class Decoder: @staticmethod def determineLength(length: bytes) -> int: """ Given first read byte, determine how many more bytes needs to be known in order to get fully encoded length. :param length: First read byte. :return: How many bytes to read. """ integer = ord(length) # pylint: disable=no-else-return if integer < 128: return 0 elif integer < 192: return 1 elif integer < 224: return 2 elif integer < 240: return 3 raise ProtocolError(f"Unknown controll byte {length!r}") @staticmethod def decodeLength(length: bytes) -> int: """ Decode length based on given bytes. :param length: Bytes string to decode. :return: Decoded length. """ bytes_length = len(length) if bytes_length < 2: offset = b"\x00\x00\x00" xor = 0 elif bytes_length < 3: offset = b"\x00\x00" xor = 0x8000 elif bytes_length < 4: offset = b"\x00" xor = 0xC00000 elif bytes_length < 5: offset = b"" xor = 0xE0000000 else: raise ProtocolError(f"Unable to decode length of {length!r}") decoded: int = unpack("!I", (offset + length))[0] decoded ^= xor return decoded class ApiProtocol(Encoder, Decoder): def __init__(self, transport: SocketTransport, encoding: str): self.transport = transport self.encoding = encoding @staticmethod def log(direction_string: str, *sentence: str) -> None: for word in sentence: LOGGER.debug(f"{direction_string} {word!r}") LOGGER.debug(f"{direction_string} EOS") def writeSentence(self, cmd: str, *words: str) -> None: """ Write encoded sentence. :param cmd: Command word. :param words: Aditional words. """ encoded = self.encodeSentence(cmd, *words) self.log("<---", cmd, *words) self.transport.write(encoded) def readSentence(self) -> typing.Tuple[str, typing.Tuple[str, ...]]: """ Read every word untill empty word (NULL byte) is received. :return: Reply word, tuple with read words. """ sentence = tuple(word for word in iter(self.readWord, "")) self.log("--->", *sentence) reply_word, words = sentence[0], sentence[1:] if reply_word == "!fatal": self.transport.close() raise FatalError(words[0]) return reply_word, words def readWord(self) -> str: byte = self.transport.read(1) # Early return check for null byte if byte == b"\x00": return "" to_read = self.determineLength(byte) byte += self.transport.read(to_read) length = self.decodeLength(byte) word = self.transport.read(length) return word.decode(encoding=self.encoding, errors="ignore") def close(self) -> None: self.transport.close() class AsyncApiProtocol(Encoder, Decoder): def __init__(self, transport: AsyncSocketTransport, encoding: str, timeout: typing.Optional[float] = None): self.transport = transport self.encoding = encoding self.timeout = timeout @staticmethod def log(direction_string: str, *sentence: str) -> None: for word in sentence: LOGGER.debug(f"{direction_string} {word!r}") LOGGER.debug(f"{direction_string} EOS") async def writeSentence(self, cmd: str, *words: str) -> None: await asyncio.wait_for(self.__writeSentence(cmd, *words), timeout=self.timeout) async def __writeSentence(self, cmd: str, *words: str) -> None: """ Write encoded sentence. :param cmd: Command word. :param words: Aditional words. """ encoded = self.encodeSentence(cmd, *words) self.log("<---", cmd, *words) await self.transport.write(encoded) async def readSentence(self) -> typing.Tuple[str, typing.Tuple[str, ...]]: return await asyncio.wait_for(self.__readSentence(), timeout=self.timeout) async def __readSentence(self) -> typing.Tuple[str, typing.Tuple[str, ...]]: """ Read every word untill empty word (NULL byte) is received. :return: Reply word, tuple with read words. """ # sentence = tuple(word for word in iter(await self.readWord, "")) temp_sentence = [] while True: word = await self.readWord() if word == "": break temp_sentence.append(word) sentence = tuple(temp_sentence) self.log("--->", *sentence) reply_word, words = sentence[0], sentence[1:] if reply_word == "!fatal": await self.transport.close() raise FatalError(words[0]) return reply_word, words async def readWord(self) -> str: byte = await self.transport.read(1) # Early return check for null byte if byte == b"\x00": return "" to_read = self.determineLength(byte) byte += await self.transport.read(to_read) length = self.decodeLength(byte) word = await self.transport.read(length) return word.decode(encoding=self.encoding, errors="ignore") async def close(self) -> None: await self.transport.close() librouteros-3.4.1/librouteros/query.py000066400000000000000000000052511473137246500201770ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import typing from itertools import chain from librouteros.protocol import ( cast_to_api, ) from librouteros.types import ( QueryGen, ResponseIter, ) class Key: def __init__(self, name: str): self.name = name def __eq__(self, other): yield f"?={self}={cast_to_api(other)}" def __ne__(self, other): yield from self == other yield "?#!" def __lt__(self, other): yield f"?<{self}={cast_to_api(other)}" def __gt__(self, other): yield f"?>{self}={cast_to_api(other)}" def __str__(self) -> str: return str(self.name) # pylint: disable=invalid-name def In(self, one, *elems): yield from self == one yield from chain.from_iterable(self == str(elem) for elem in elems) yield from ("?#|",) * len(elems) class Query: def __init__(self, path, keys: typing.Sequence[Key], api): self.path = path self.keys = keys self.api = api self.query: typing.Tuple[str, ...] = tuple() def where(self, *args: str): self.query = tuple(chain.from_iterable(args)) return self def __iter__(self) -> ResponseIter: cmd = str(self.path.join("print")) words = tuple(self.query) if len(self.keys) > 0: keys = ",".join(str(key) for key in self.keys) keys = f"=.proplist={keys}" words = (keys,) + words return iter(self.api.rawCmd(cmd, *words)) def And(left: QueryGen, right: QueryGen, *rest: QueryGen) -> QueryGen: # pylint: disable=invalid-name yield from left yield from right yield from chain.from_iterable(rest) yield "?#&" yield from ("?#&",) * len(rest) def Or(left: QueryGen, right: QueryGen, *rest: QueryGen) -> QueryGen: # pylint: disable=invalid-name yield from left yield from right yield from chain.from_iterable(rest) yield "?#|" yield from ("?#|",) * len(rest) class AsyncQuery: def __init__(self, path, keys: typing.Sequence[Key], api): self.path = path self.keys = keys self.api = api self.query: typing.Tuple[str, ...] = tuple() def where(self, *args: str): self.query = tuple(chain.from_iterable(args)) return self def __aiter__(self): cmd = str(self.path.join("print")) words = tuple(self.query) if len(self.keys) > 0: keys = ",".join(str(key) for key in self.keys) keys = f"=.proplist={keys}" words = (keys,) + words return self.api.rawCmd(cmd, *words) def __iter__(self): raise AttributeError("Use 'async for' instead of 'for' to iterate over Query results.") librouteros-3.4.1/librouteros/types.py000066400000000000000000000004331473137246500201730ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from typing import ( Dict, Iterator, Any, List, AsyncGenerator, ) ReplyDict = Dict[str, Any] ResponseIter = Iterator[ReplyDict] AsyncResponseIter = AsyncGenerator[ReplyDict, None] QueryGen = Iterator[str] Response = List[Dict[str, Any]] librouteros-3.4.1/poetry.lock000066400000000000000000000466631473137246500163170ustar00rootroot00000000000000# This file is automatically @generated by Poetry 1.8.5 and should not be changed by hand. [[package]] name = "bump2version" version = "1.0.1" description = "Version-bump your software with a single command!" optional = false python-versions = ">=3.5" files = [ {file = "bump2version-1.0.1-py2.py3-none-any.whl", hash = "sha256:37f927ea17cde7ae2d7baf832f8e80ce3777624554a653006c9144f8017fe410"}, {file = "bump2version-1.0.1.tar.gz", hash = "sha256:762cb2bfad61f4ec8e2bdf452c7c267416f8c70dd9ecb1653fd0bbb01fa936e6"}, ] [[package]] name = "colorama" version = "0.4.6" description = "Cross-platform colored terminal text." optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" files = [ {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, ] [[package]] name = "exceptiongroup" version = "1.2.2" description = "Backport of PEP 654 (exception groups)" optional = false python-versions = ">=3.7" files = [ {file = "exceptiongroup-1.2.2-py3-none-any.whl", hash = "sha256:3111b9d131c238bec2f8f516e123e14ba243563fb135d3fe885990585aa7795b"}, {file = "exceptiongroup-1.2.2.tar.gz", hash = "sha256:47c2edf7c6738fafb49fd34290706d1a1a2f4d1c6df275526b62cbb4aa5393cc"}, ] [package.extras] test = ["pytest (>=6)"] [[package]] name = "execnet" version = "2.1.1" description = "execnet: rapid multi-Python deployment" optional = false python-versions = ">=3.8" files = [ {file = "execnet-2.1.1-py3-none-any.whl", hash = "sha256:26dee51f1b80cebd6d0ca8e74dd8745419761d3bef34163928cbebbdc4749fdc"}, {file = "execnet-2.1.1.tar.gz", hash = "sha256:5189b52c6121c24feae288166ab41b32549c7e2348652736540b9e6e7d4e72e3"}, ] [package.extras] testing = ["hatch", "pre-commit", "pytest", "tox"] [[package]] name = "iniconfig" version = "2.0.0" description = "brain-dead simple config-ini parsing" optional = false python-versions = ">=3.7" files = [ {file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"}, {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, ] [[package]] name = "mypy" version = "1.13.0" description = "Optional static typing for Python" optional = false python-versions = ">=3.8" files = [ {file = "mypy-1.13.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6607e0f1dd1fb7f0aca14d936d13fd19eba5e17e1cd2a14f808fa5f8f6d8f60a"}, {file = "mypy-1.13.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8a21be69bd26fa81b1f80a61ee7ab05b076c674d9b18fb56239d72e21d9f4c80"}, {file = "mypy-1.13.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7b2353a44d2179846a096e25691d54d59904559f4232519d420d64da6828a3a7"}, {file = "mypy-1.13.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:0730d1c6a2739d4511dc4253f8274cdd140c55c32dfb0a4cf8b7a43f40abfa6f"}, {file = "mypy-1.13.0-cp310-cp310-win_amd64.whl", hash = "sha256:c5fc54dbb712ff5e5a0fca797e6e0aa25726c7e72c6a5850cfd2adbc1eb0a372"}, {file = "mypy-1.13.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:581665e6f3a8a9078f28d5502f4c334c0c8d802ef55ea0e7276a6e409bc0d82d"}, {file = "mypy-1.13.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3ddb5b9bf82e05cc9a627e84707b528e5c7caaa1c55c69e175abb15a761cec2d"}, {file = "mypy-1.13.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:20c7ee0bc0d5a9595c46f38beb04201f2620065a93755704e141fcac9f59db2b"}, {file = "mypy-1.13.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:3790ded76f0b34bc9c8ba4def8f919dd6a46db0f5a6610fb994fe8efdd447f73"}, {file = "mypy-1.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:51f869f4b6b538229c1d1bcc1dd7d119817206e2bc54e8e374b3dfa202defcca"}, {file = "mypy-1.13.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5c7051a3461ae84dfb5dd15eff5094640c61c5f22257c8b766794e6dd85e72d5"}, {file = "mypy-1.13.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:39bb21c69a5d6342f4ce526e4584bc5c197fd20a60d14a8624d8743fffb9472e"}, {file = "mypy-1.13.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:164f28cb9d6367439031f4c81e84d3ccaa1e19232d9d05d37cb0bd880d3f93c2"}, {file = "mypy-1.13.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:a4c1bfcdbce96ff5d96fc9b08e3831acb30dc44ab02671eca5953eadad07d6d0"}, {file = "mypy-1.13.0-cp312-cp312-win_amd64.whl", hash = "sha256:a0affb3a79a256b4183ba09811e3577c5163ed06685e4d4b46429a271ba174d2"}, {file = "mypy-1.13.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a7b44178c9760ce1a43f544e595d35ed61ac2c3de306599fa59b38a6048e1aa7"}, {file = "mypy-1.13.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:5d5092efb8516d08440e36626f0153b5006d4088c1d663d88bf79625af3d1d62"}, {file = "mypy-1.13.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:de2904956dac40ced10931ac967ae63c5089bd498542194b436eb097a9f77bc8"}, {file = "mypy-1.13.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:7bfd8836970d33c2105562650656b6846149374dc8ed77d98424b40b09340ba7"}, {file = "mypy-1.13.0-cp313-cp313-win_amd64.whl", hash = "sha256:9f73dba9ec77acb86457a8fc04b5239822df0c14a082564737833d2963677dbc"}, {file = "mypy-1.13.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:100fac22ce82925f676a734af0db922ecfea991e1d7ec0ceb1e115ebe501301a"}, {file = "mypy-1.13.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7bcb0bb7f42a978bb323a7c88f1081d1b5dee77ca86f4100735a6f541299d8fb"}, {file = "mypy-1.13.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bde31fc887c213e223bbfc34328070996061b0833b0a4cfec53745ed61f3519b"}, {file = "mypy-1.13.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:07de989f89786f62b937851295ed62e51774722e5444a27cecca993fc3f9cd74"}, {file = "mypy-1.13.0-cp38-cp38-win_amd64.whl", hash = "sha256:4bde84334fbe19bad704b3f5b78c4abd35ff1026f8ba72b29de70dda0916beb6"}, {file = "mypy-1.13.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:0246bcb1b5de7f08f2826451abd947bf656945209b140d16ed317f65a17dc7dc"}, {file = "mypy-1.13.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:7f5b7deae912cf8b77e990b9280f170381fdfbddf61b4ef80927edd813163732"}, {file = "mypy-1.13.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7029881ec6ffb8bc233a4fa364736789582c738217b133f1b55967115288a2bc"}, {file = "mypy-1.13.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:3e38b980e5681f28f033f3be86b099a247b13c491f14bb8b1e1e134d23bb599d"}, {file = "mypy-1.13.0-cp39-cp39-win_amd64.whl", hash = "sha256:a6789be98a2017c912ae6ccb77ea553bbaf13d27605d2ca20a76dfbced631b24"}, {file = "mypy-1.13.0-py3-none-any.whl", hash = "sha256:9c250883f9fd81d212e0952c92dbfcc96fc237f4b7c92f56ac81fd48460b3e5a"}, {file = "mypy-1.13.0.tar.gz", hash = "sha256:0291a61b6fbf3e6673e3405cfcc0e7650bebc7939659fdca2702958038bd835e"}, ] [package.dependencies] mypy-extensions = ">=1.0.0" tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} typing-extensions = ">=4.6.0" [package.extras] dmypy = ["psutil (>=4.0)"] faster-cache = ["orjson"] install-types = ["pip"] mypyc = ["setuptools (>=50)"] reports = ["lxml"] [[package]] name = "mypy-extensions" version = "1.0.0" description = "Type system extensions for programs checked with the mypy type checker." optional = false python-versions = ">=3.5" files = [ {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, ] [[package]] name = "packaging" version = "24.2" description = "Core utilities for Python packages" optional = false python-versions = ">=3.8" files = [ {file = "packaging-24.2-py3-none-any.whl", hash = "sha256:09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759"}, {file = "packaging-24.2.tar.gz", hash = "sha256:c228a6dc5e932d346bc5739379109d49e8853dd8223571c7c5b55260edc0b97f"}, ] [[package]] name = "pluggy" version = "1.5.0" description = "plugin and hook calling mechanisms for python" optional = false python-versions = ">=3.8" files = [ {file = "pluggy-1.5.0-py3-none-any.whl", hash = "sha256:44e1ad92c8ca002de6377e165f3e0f1be63266ab4d554740532335b9d75ea669"}, {file = "pluggy-1.5.0.tar.gz", hash = "sha256:2cffa88e94fdc978c4c574f15f9e59b7f4201d439195c3715ca9e2486f1d0cf1"}, ] [package.extras] dev = ["pre-commit", "tox"] testing = ["pytest", "pytest-benchmark"] [[package]] name = "pytest" version = "8.3.4" description = "pytest: simple powerful testing with Python" optional = false python-versions = ">=3.8" files = [ {file = "pytest-8.3.4-py3-none-any.whl", hash = "sha256:50e16d954148559c9a74109af1eaf0c945ba2d8f30f0a3d3335edde19788b6f6"}, {file = "pytest-8.3.4.tar.gz", hash = "sha256:965370d062bce11e73868e0335abac31b4d3de0e82f4007408d242b4f8610761"}, ] [package.dependencies] colorama = {version = "*", markers = "sys_platform == \"win32\""} exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""} iniconfig = "*" packaging = "*" pluggy = ">=1.5,<2" tomli = {version = ">=1", markers = "python_version < \"3.11\""} [package.extras] dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"] [[package]] name = "pytest-asyncio" version = "0.24.0" description = "Pytest support for asyncio" optional = false python-versions = ">=3.8" files = [ {file = "pytest_asyncio-0.24.0-py3-none-any.whl", hash = "sha256:a811296ed596b69bf0b6f3dc40f83bcaf341b155a269052d82efa2b25ac7037b"}, {file = "pytest_asyncio-0.24.0.tar.gz", hash = "sha256:d081d828e576d85f875399194281e92bf8a68d60d72d1a2faf2feddb6c46b276"}, ] [package.dependencies] pytest = ">=8.2,<9" [package.extras] docs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"] testing = ["coverage (>=6.2)", "hypothesis (>=5.7.1)"] [[package]] name = "pytest-xdist" version = "3.6.1" description = "pytest xdist plugin for distributed testing, most importantly across multiple CPUs" optional = false python-versions = ">=3.8" files = [ {file = "pytest_xdist-3.6.1-py3-none-any.whl", hash = "sha256:9ed4adfb68a016610848639bb7e02c9352d5d9f03d04809919e2dafc3be4cca7"}, {file = "pytest_xdist-3.6.1.tar.gz", hash = "sha256:ead156a4db231eec769737f57668ef58a2084a34b2e55c4a8fa20d861107300d"}, ] [package.dependencies] execnet = ">=2.1" pytest = ">=7.0.0" [package.extras] psutil = ["psutil (>=3.0)"] setproctitle = ["setproctitle"] testing = ["filelock"] [[package]] name = "ruff" version = "0.8.4" description = "An extremely fast Python linter and code formatter, written in Rust." optional = false python-versions = ">=3.7" files = [ {file = "ruff-0.8.4-py3-none-linux_armv6l.whl", hash = "sha256:58072f0c06080276804c6a4e21a9045a706584a958e644353603d36ca1eb8a60"}, {file = "ruff-0.8.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:ffb60904651c00a1e0b8df594591770018a0f04587f7deeb3838344fe3adabac"}, {file = "ruff-0.8.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6ddf5d654ac0d44389f6bf05cee4caeefc3132a64b58ea46738111d687352296"}, {file = "ruff-0.8.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e248b1f0fa2749edd3350a2a342b67b43a2627434c059a063418e3d375cfe643"}, {file = "ruff-0.8.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bf197b98ed86e417412ee3b6c893f44c8864f816451441483253d5ff22c0e81e"}, {file = "ruff-0.8.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c41319b85faa3aadd4d30cb1cffdd9ac6b89704ff79f7664b853785b48eccdf3"}, {file = "ruff-0.8.4-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:9f8402b7c4f96463f135e936d9ab77b65711fcd5d72e5d67597b543bbb43cf3f"}, {file = "ruff-0.8.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e4e56b3baa9c23d324ead112a4fdf20db9a3f8f29eeabff1355114dd96014604"}, {file = "ruff-0.8.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:736272574e97157f7edbbb43b1d046125fce9e7d8d583d5d65d0c9bf2c15addf"}, {file = "ruff-0.8.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e5fe710ab6061592521f902fca7ebcb9fabd27bc7c57c764298b1c1f15fff720"}, {file = "ruff-0.8.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:13e9ec6d6b55f6da412d59953d65d66e760d583dd3c1c72bf1f26435b5bfdbae"}, {file = "ruff-0.8.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:97d9aefef725348ad77d6db98b726cfdb075a40b936c7984088804dfd38268a7"}, {file = "ruff-0.8.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:ab78e33325a6f5374e04c2ab924a3367d69a0da36f8c9cb6b894a62017506111"}, {file = "ruff-0.8.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:8ef06f66f4a05c3ddbc9121a8b0cecccd92c5bf3dd43b5472ffe40b8ca10f0f8"}, {file = "ruff-0.8.4-py3-none-win32.whl", hash = "sha256:552fb6d861320958ca5e15f28b20a3d071aa83b93caee33a87b471f99a6c0835"}, {file = "ruff-0.8.4-py3-none-win_amd64.whl", hash = "sha256:f21a1143776f8656d7f364bd264a9d60f01b7f52243fbe90e7670c0dfe0cf65d"}, {file = "ruff-0.8.4-py3-none-win_arm64.whl", hash = "sha256:9183dd615d8df50defa8b1d9a074053891ba39025cf5ae88e8bcb52edcc4bf08"}, {file = "ruff-0.8.4.tar.gz", hash = "sha256:0d5f89f254836799af1615798caa5f80b7f935d7a670fad66c5007928e57ace8"}, ] [[package]] name = "toml" version = "0.10.2" description = "Python Library for Tom's Obvious, Minimal Language" optional = false python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" files = [ {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, ] [[package]] name = "tomli" version = "2.2.1" description = "A lil' TOML parser" optional = false python-versions = ">=3.8" files = [ {file = "tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249"}, {file = "tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6"}, {file = "tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a"}, {file = "tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee"}, {file = "tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e"}, {file = "tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4"}, {file = "tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106"}, {file = "tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8"}, {file = "tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff"}, {file = "tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b"}, {file = "tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea"}, {file = "tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8"}, {file = "tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192"}, {file = "tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222"}, {file = "tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77"}, {file = "tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6"}, {file = "tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd"}, {file = "tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e"}, {file = "tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98"}, {file = "tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4"}, {file = "tomli-2.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7"}, {file = "tomli-2.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c"}, {file = "tomli-2.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13"}, {file = "tomli-2.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281"}, {file = "tomli-2.2.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272"}, {file = "tomli-2.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140"}, {file = "tomli-2.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2"}, {file = "tomli-2.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744"}, {file = "tomli-2.2.1-cp313-cp313-win32.whl", hash = "sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec"}, {file = "tomli-2.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69"}, {file = "tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc"}, {file = "tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff"}, ] [[package]] name = "typing-extensions" version = "4.12.2" description = "Backported and Experimental Type Hints for Python 3.8+" optional = false python-versions = ">=3.8" files = [ {file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"}, {file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"}, ] [metadata] lock-version = "2.0" python-versions = "^3.8.0" content-hash = "e39c1347ba8d533f63e7c8ac8d65fe36bdfb425944abfd497809cd075277a444" librouteros-3.4.1/pyproject.toml000066400000000000000000000026761473137246500170330ustar00rootroot00000000000000[tool.poetry] name = "librouteros" version = "3.4.1" description = "Python implementation of MikroTik RouterOS API" authors = ["Łukasz Kostka "] license = "GPL-2.0-or-later" readme = "README.rst" documentation="https://librouteros.readthedocs.io" repository="https://github.com/luqasz/librouteros" keywords=[ "mikrotik", "routeros", "api", ] classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", "Operating System :: MacOS", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Software Development :: Libraries" ] [tool.poetry.dependencies] python = "^3.8.0" toml = "^0.10.2" [tool.poetry.group.dev.dependencies] pytest-asyncio = "^0.24.0" pytest = "^8.3.4" pytest-xdist = "^3.5.0" mypy = "^1.13" bump2version = "^1.0.1" ruff = ">=0.7.1" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" [tool.ruff] line-length = 120 [tool.ruff.format] docstring-code-format = true docstring-code-line-length = 80 [tool.pytest.ini_options] addopts = "-ra" asyncio_default_fixture_loop_scope = "function" asyncio_mode = "auto" librouteros-3.4.1/tests/000077500000000000000000000000001473137246500152465ustar00rootroot00000000000000librouteros-3.4.1/tests/integration/000077500000000000000000000000001473137246500175715ustar00rootroot00000000000000librouteros-3.4.1/tests/integration/__init__.py000066400000000000000000000000001473137246500216700ustar00rootroot00000000000000librouteros-3.4.1/tests/integration/conftest.py000066400000000000000000000071451473137246500217770ustar00rootroot00000000000000from time import sleep from os import ( devnull, ) from random import randint from subprocess import Popen, check_call from tempfile import NamedTemporaryFile import socket from pathlib import Path import pytest import pytest_asyncio from librouteros import connect, async_connect from librouteros.exceptions import LibRouterosError from librouteros.login import ( plain, token, async_plain, async_token, ) DEV_NULL = open(devnull, "w") VERSION_LOGIN = { "6.44.5": { "sync": plain, "async": async_plain, }, "6.33.3": { "sync": token, "async": async_token, }, } def api_session(port): last_exc = None for _ in range(30): try: return connect( host="127.0.0.1", port=port, username="admin", password="", timeout=60, ) except (LibRouterosError, socket.error, socket.timeout) as exc: last_exc = exc sleep(1) raise RuntimeError("Could not connect to device. Last exception {}".format(last_exc)) async def api_session_async(port): last_exc = None for _ in range(30): try: return await async_connect( host="127.0.0.1", port=port, username="admin", password="", timeout=60, ) except (LibRouterosError, socket.error, socket.timeout) as exc: last_exc = exc sleep(1) raise RuntimeError("Could not connect to device. Last exception {}".format(last_exc)) def disk_image(version): """Create a temporary disk image backed by original one.""" img = NamedTemporaryFile() # Path to backing image must be absolute or relative to new image backing_img = Path().joinpath("images/routeros_{}.qcow2".format(version)).absolute() cmd = [ "qemu-img", "create", "-f", "qcow2", "-F", "qcow2", "-b", str(backing_img), img.name, ] check_call(cmd, stdout=DEV_NULL) return img def routeros_vm(disk_image): # pylint: disable=redefined-outer-name port = randint(49152, 65535) cmd = [ "qemu-system-x86_64", "-m", "64", "-display", "none", "-hda", disk_image.name, "-net", "user,hostfwd=tcp::{}-:8728".format(port), "-net", "nic,model=virtio", "-cpu", "max", ] proc = Popen(cmd, stdout=DEV_NULL, close_fds=True) return port, proc @pytest.fixture(scope="function", params=VERSION_LOGIN.keys()) def routeros_login(request): # pylint: disable=redefined-outer-name version = request.param image = disk_image(version) port, proc = routeros_vm(image) request.addfinalizer(proc.kill) request.addfinalizer(image.close) def get_login_method(exc_type): return port, VERSION_LOGIN[version][exc_type] return get_login_method @pytest.fixture(scope="function") def routeros_api(request): # pylint: disable=redefined-outer-name version = "6.44.5" image = disk_image(version) port, proc = routeros_vm(image) request.addfinalizer(proc.kill) request.addfinalizer(image.close) return api_session(port=port) @pytest_asyncio.fixture(scope="function") async def routeros_api_async(request): # pylint: disable=redefined-outer-name version = "6.44.5" image = disk_image(version) port, proc = routeros_vm(image) request.addfinalizer(proc.kill) request.addfinalizer(image.close) return await api_session_async(port=port) librouteros-3.4.1/tests/integration/test_general.py000066400000000000000000000122161473137246500226210ustar00rootroot00000000000000import socket import pytest from time import sleep from librouteros.query import Key from librouteros import connect, async_connect from librouteros.exceptions import LibRouterosError def test_login(routeros_login): port, method = routeros_login("sync") api = None for _ in range(30): try: api = connect( host="127.0.0.1", port=port, username="admin", password="", login_method=method, ) break except (LibRouterosError, socket.error, socket.timeout): sleep(1) data = api("/system/identity/print") assert tuple(data)[0]["name"] == "MikroTik" @pytest.mark.asyncio async def test_login_async(routeros_login): port, method = routeros_login("async") api = None for _ in range(30): try: api = await async_connect( host="127.0.0.1", port=port, username="admin", password="", login_method=method, timeout=60, ) break except (LibRouterosError, socket.error, socket.timeout): sleep(1) result = [r async for r in api("/system/identity/print")] assert result[0]["name"] == "MikroTik" def test_query(routeros_api): new_address = "172.16.1.1/24" result = routeros_api( "/ip/address/add", address=new_address, interface="ether1", ) created_id = tuple(result)[0]["ret"] _id = Key(".id") address = Key("address") query = ( routeros_api.path("/ip/address") .select(_id, address) .where( _id == created_id, address == new_address, ) ) selected_data = tuple(query) assert len(selected_data) == 1 assert selected_data[0][".id"] == created_id assert selected_data[0]["address"] == new_address @pytest.mark.asyncio async def test_query_async(routeros_api_async): new_address = "172.16.1.1/24" result = [ r async for r in routeros_api_async( "/ip/address/add", address=new_address, interface="ether1", ) ] created_id = result[0]["ret"] _id = Key(".id") address = Key("address") selected_data = [ r async for r in routeros_api_async.path("/ip/address") .select(_id, address) .where( _id == created_id, address == new_address, ) ] assert len(selected_data) == 1 assert selected_data[0][".id"] == created_id assert selected_data[0]["address"] == new_address @pytest.mark.parametrize( "addresses", ( {"172.16.1.1/24", "172.16.1.2/24"}, {"172.16.1.1/24", "172.16.1.2/24", "1.1.1.1/24"}, {"172.16.1.2/24"}, ), ) def test_query_In_operator(routeros_api, addresses): addr_path = routeros_api.path("/ip/address") for addr in addresses: addr_path.add(interface="ether1", address=addr) address = Key("address") query = addr_path.select(address).where(address.In(*addresses)) assert addresses == set(row["address"] for row in query) @pytest.mark.asyncio @pytest.mark.parametrize( "addresses", ( {"172.16.1.1/24", "172.16.1.2/24"}, {"172.16.1.1/24", "172.16.1.2/24", "1.1.1.1/24"}, {"172.16.1.2/24"}, ), ) async def test_query_In_operator_async(routeros_api_async, addresses): addr_path = routeros_api_async.path("/ip/address") for addr in addresses: await addr_path.add(interface="ether1", address=addr) address = Key("address") result = [r async for r in addr_path.select(address).where(address.In(*addresses))] assert addresses == set(row["address"] for row in result) def test_long_word(routeros_api): r""" Assert that when word length is encoded with \x00 in it, library should decode this without errors. Create a entry with long word length (256) resulting in word encoding of \x81\00. Check if when reading back, comment is same when set. """ long_value = "a" * (256 - len("=comment=")) data = routeros_api( "/ip/address/add", address="172.16.1.1/24", interface="ether1", comment=long_value, ) _id = tuple(data)[0]["ret"] for row in routeros_api("/ip/address/print"): if row[".id"] == _id: assert row["comment"] == long_value @pytest.mark.asyncio async def test_long_word_async(routeros_api_async): r""" Assert that when word length is encoded with \x00 in it, library should decode this without errors. Create a entry with long word length (256) resulting in word encoding of \x81\00. Check if when reading back, comment is same when set. """ long_value = "a" * (256 - len("=comment=")) data = [ r async for r in routeros_api_async( "/ip/address/add", address="172.16.1.1/24", interface="ether1", comment=long_value, ) ] _id = data[0]["ret"] async for row in routeros_api_async("/ip/address/print"): if row[".id"] == _id: assert row["comment"] == long_value librouteros-3.4.1/tests/integration/test_generator.py000066400000000000000000000021011473137246500231620ustar00rootroot00000000000000import pytest def test_generator_ditch(routeros_api): """ Assert that after ditching generator, new one will yield actual results. """ routeros_api( "/ip/address/add", address="1.1.1.1/32", interface="ether1", ) ips = routeros_api.path("ip", "address") for ip in ips: break interfaces = tuple(routeros_api.path("interface")) assert len(interfaces) == 1 assert "mtu" in interfaces[0].keys() assert "mac-address" in interfaces[0].keys() @pytest.mark.asyncio async def test_generator_ditch_async(routeros_api_async): """ Assert that after ditching generator, new one will yield actual results. """ routeros_api_async( "/ip/address/add", address="1.1.1.1/32", interface="ether1", ) ips = routeros_api_async.path("ip", "address") async for ip in ips: break interfaces = [r async for r in routeros_api_async.path("interface")] assert len(interfaces) == 1 assert "mtu" in interfaces[0].keys() assert "mac-address" in interfaces[0].keys() librouteros-3.4.1/tests/integration/test_path.py000066400000000000000000000026011473137246500221350ustar00rootroot00000000000000import pytest from librouteros.query import Key def test_add_then_remove(routeros_api): ips = routeros_api.path("ip", "address") new_id = ips.add(interface="ether1", address="192.168.1.1/24") ips.remove(new_id) _id = Key(".id") assert tuple() == tuple(ips.select(_id).where(_id == new_id)) @pytest.mark.asyncio async def test_add_then_remove_async(routeros_api_async): ips = routeros_api_async.path("ip", "address") new_id = await ips.add(interface="ether1", address="192.168.1.1/24") await ips.remove(new_id) _id = Key(".id") assert tuple() == tuple([r async for r in ips.select(_id).where(_id == new_id)]) def test_add_then_update(routeros_api): ips = routeros_api.path("ip", "address") new_id = ips.add(interface="ether1", address="192.168.1.1/24") ips.update(**{".id": new_id, "address": "172.16.1.1/24"}) address = Key("address") assert tuple(ips.select(address).where(Key(".id") == new_id))[0]["address"] == "172.16.1.1/24" @pytest.mark.asyncio async def test_add_then_update_async(routeros_api_async): ips = routeros_api_async.path("ip", "address") new_id = await ips.add(interface="ether1", address="192.168.1.1/24") await ips.update(**{".id": new_id, "address": "172.16.1.1/24"}) address = Key("address") assert [r async for r in ips.select(address).where(Key(".id") == new_id)][0]["address"] == "172.16.1.1/24" librouteros-3.4.1/tests/requirements/000077500000000000000000000000001473137246500177715ustar00rootroot00000000000000librouteros-3.4.1/tests/requirements/conftest.py000066400000000000000000000006311473137246500221700ustar00rootroot00000000000000import pytest from subprocess import check_output import sys @pytest.fixture def installed_packages(): pkgs = [] pip_executable = [sys.executable, "-m", "pip"] result = check_output(pip_executable + ["freeze", "--local", "--all"]) for line in result.decode().splitlines(): if "==" in line: pkg, version = line.split("==", 1) pkgs.append(pkg) return pkgs librouteros-3.4.1/tests/unit/000077500000000000000000000000001473137246500162255ustar00rootroot00000000000000librouteros-3.4.1/tests/unit/__init__.py000066400000000000000000000000001473137246500203240ustar00rootroot00000000000000librouteros-3.4.1/tests/unit/conftest.py000066400000000000000000000027131473137246500204270ustar00rootroot00000000000000import pytest from collections import namedtuple from struct import pack WordLength = namedtuple("WordLength", ("integer", "encoded")) WordPair = namedtuple("WordPair", ("word", "pair")) @pytest.fixture(scope="function") def bad_length_bytes(): """len(length) must be < 5""" return b"\xff\xff\xff\xff\xff" @pytest.fixture( scope="function", params=( WordLength(integer=0, encoded=b"\x00"), WordLength(integer=127, encoded=b"\x7f"), WordLength(integer=130, encoded=b"\x80\x82"), WordLength(integer=2097140, encoded=b"\xdf\xff\xf4"), WordLength(integer=268435440, encoded=b"\xef\xff\xff\xf0"), ), ) def valid_word_length(request): return request.param @pytest.fixture(scope="function", params=(pack(">B", i) for i in range(240, 256))) def bad_first_length_bytes(request): """First byte of length must be < 240.""" return request.param @pytest.fixture( params=( WordPair(word="=key=yes", pair=("key", True)), WordPair(word="=key=no", pair=("key", False)), WordPair(word="=key=string", pair=("key", "string")), WordPair(word="=key=none", pair=("key", "none")), WordPair(word="=key=22.2", pair=("key", "22.2")), WordPair(word="=key=22", pair=("key", 22)), WordPair(word="=key=0", pair=("key", 0)), ) ) def word_pair(request): """Words and key,value pairs used for casting from/to python/api in both directions.""" return request.param librouteros-3.4.1/tests/unit/test_api.py000066400000000000000000000012461473137246500204120ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from librouteros.protocol import ( parse_word, compose_word, ) @pytest.mark.parametrize( "word,pair", ( ("=dynamic=true", ("dynamic", True)), ("=dynamic=false", ("dynamic", False)), ), ) def test_bool_parse_word(word, pair): """ Test for parsing legacy bool values. Older routeros versions accept yes/true/no/false as values, but only return true/false. """ assert parse_word(word) == pair def test_parse_word(word_pair): assert parse_word(word_pair.word) == word_pair.pair def test_compose_word(word_pair): assert compose_word(*word_pair.pair) == word_pair.word librouteros-3.4.1/tests/unit/test_connections.py000066400000000000000000000062101473137246500221570ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from socket import error as SOCKET_ERROR, timeout as SOCKET_TIMEOUT, socket from unittest.mock import MagicMock from librouteros.connections import SocketTransport, AsyncSocketTransport from librouteros.exceptions import ( ConnectionClosed, ) from asyncio import StreamReader, StreamWriter class Test_SocketTransport: def setup_method(self): self.transport = SocketTransport(sock=MagicMock(spec=socket)) def test_close_shutdown_exception(self): self.transport.sock.shutdown.side_effect = SOCKET_ERROR self.transport.close() self.transport.sock.close.assert_called_once_with() def test_close(self): self.transport.close() self.transport.sock.close.assert_called_once_with() def test_calls_sendall(self): self.transport.write(b"some message") self.transport.sock.sendall.assert_called_once_with(b"some message") def test_read_raises_when_recv_returns_empty_byte_string(self): self.transport.sock.recv.return_value = b"" with pytest.raises(ConnectionClosed): self.transport.read(3) def test_read_reads_full_length(self): """ Check if read() reads all data, even when socket.recv() needs to be called multiple times. """ self.transport.sock.recv.side_effect = (b"retu", b"rne", b"d") assert self.transport.read(8) == b"returned" @pytest.mark.parametrize("exception", (SOCKET_ERROR, SOCKET_TIMEOUT)) def test_recv_raises_socket_errors(self, exception): self.transport.sock.recv.side_effect = exception with pytest.raises(exception): self.transport.read(2) class Test_AsyncSocketTransport: def setup_method(self): self.transport = AsyncSocketTransport( reader=MagicMock(spec=StreamReader), writer=MagicMock(spec=StreamWriter), ) @pytest.mark.asyncio async def test_close(self): await self.transport.close() self.transport.writer.close.assert_called_once_with() @pytest.mark.asyncio async def test_write(self): await self.transport.write(b"some message") self.transport.writer.write.assert_called_once_with(b"some message") self.transport.writer.drain.assert_called_once_with() @pytest.mark.asyncio async def test_read_raises_when_recv_returns_empty_byte_string(self): self.transport.reader.read.return_value = b"" with pytest.raises(ConnectionClosed): await self.transport.read(3) @pytest.mark.asyncio async def test_read_reads_full_length(self): """ Check if read() reads all data, even when socket.recv() needs to be called multiple times. """ self.transport.reader.read.side_effect = (b"retu", b"rne", b"d") assert await self.transport.read(8) == b"returned" @pytest.mark.asyncio @pytest.mark.parametrize("exception", (SOCKET_ERROR, SOCKET_TIMEOUT)) async def test_recv_raises_socket_errors(self, exception): self.transport.reader.read.side_effect = exception with pytest.raises(exception): await self.transport.read(2) librouteros-3.4.1/tests/unit/test_exceptions.py000066400000000000000000000004071473137246500220200ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from librouteros.exceptions import TrapError def test_TrapError_newlines(): r"""Assert that string representation replaces \r\n with comma.""" error = TrapError(message="some\r\n string") assert str(error) == "some, string" librouteros-3.4.1/tests/unit/test_librouteros.py000066400000000000000000000056551473137246500222220ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import socket import pytest from unittest.mock import ( patch, Mock, ) from librouteros import ( DEFAULTS, Api, connect, async_connect, create_transport, ) from librouteros.exceptions import TrapError from librouteros.login import ( encode_password, plain, ) def test_default_ssl_wrapper(): """Assert that wrapper returns same object as it was called with.""" assert DEFAULTS["ssl_wrapper"](int) is int @pytest.mark.parametrize( "key, value", ( ("timeout", 10), ("port", 8728), ("saddr", ""), ("subclass", Api), ("encoding", "ASCII"), ("login_method", plain), ), ) def test_defaults(key, value): assert DEFAULTS[key] == value def test_default_keys(): assert set(DEFAULTS.keys()) == set( ( "timeout", "port", "saddr", "subclass", "encoding", "login_method", "ssl_wrapper", ) ) def test_password_encoding(): result = encode_password("259e0bc05acd6f46926dc2f809ed1bba", "test") assert result == "00c7fd865183a43a772dde231f6d0bff13" def test_non_ascii_password_encoding(): """Only ascii characters are allowed in password.""" with pytest.raises(UnicodeEncodeError): encode_password(token="259e0bc05acd6f46926dc2f809ed1bba", password="łą") @patch("librouteros.create_transport") def test_connect_raises_when_failed_login(transport_mock): failed = Mock(name="failed", side_effect=TrapError(message="failed to login")) with pytest.raises(TrapError): connect(host="127.0.0.1", username="admin", password="", login_method=failed) @pytest.mark.asyncio @patch("librouteros.async_create_transport") async def test_async_connect_raises_when_failed_login(transport_mock): failed = Mock(name="failed", side_effect=TrapError(message="failed to login")) with pytest.raises(TrapError): await async_connect(host="127.0.0.1", username="admin", password="", login_method=failed) @pytest.mark.parametrize("exc", (socket.error, socket.timeout)) @patch("librouteros.create_connection") @patch("librouteros.SocketTransport") def test_create_connection_does_not_wrap_socket_exceptions(create_connection, transport, exc): kwargs = dict( host="127.0.0.1", port=22, timeout=2, saddr="", ) transport.side_effect = exc with pytest.raises(exc): create_transport(**kwargs) @pytest.mark.asyncio @pytest.mark.parametrize("exc", (socket.error, socket.timeout)) @patch("librouteros.create_connection") @patch("librouteros.SocketTransport") async def test_async_create_connection_does_not_wrap_socket_exceptions(create_connection, transport, exc): kwargs = dict( host="127.0.0.1", port=22, timeout=2, saddr="", ) transport.side_effect = exc with pytest.raises(exc): await create_transport(**kwargs) librouteros-3.4.1/tests/unit/test_path.py000066400000000000000000000130471473137246500205770ustar00rootroot00000000000000# -*- coding: UTF-8 -*- from unittest.mock import MagicMock from librouteros.api import Api, Path, AsyncApi, AyncPath from librouteros.query import Query, AsyncQuery import pytest def test_api_path_returns_Path(): api = Api(protocol=MagicMock()) new = api.path("ip", "address") assert new.path == "/ip/address" assert new.api == api assert isinstance(new, Path) def test_async_api_path_returns_AsyncPath(): api = AsyncApi(protocol=MagicMock()) new = api.path("ip", "address") assert new.path == "/ip/address" assert new.api == api assert isinstance(new, AyncPath) class Test_Path: def setup_method(self): self.path = Path( path="/interface", api=MagicMock(), ) self.async_path = AyncPath( path="/interface", api=MagicMock(), ) def test_path_str(self): assert str(self.path) == self.path.path assert str(self.async_path) == self.async_path.path def test_join_single_param(self): assert self.path.join("ethernet").path == self.path.path + "/ethernet" assert self.async_path.join("ethernet").path == self.async_path.path + "/ethernet" def test_join_multi_param(self): assert self.path.join("ethernet", "print").path == self.path.path + "/ethernet/print" assert self.async_path.join("ethernet", "print").path == self.async_path.path + "/ethernet/print" def test_join_rstrips_slash(self): assert self.path.join("ethernet", "print/").path == self.path.path + "/ethernet/print" assert self.async_path.join("ethernet", "print/").path == self.async_path.path + "/ethernet/print" def test_select_returns_Query(self): new = self.path.select("disabled", "name") assert isinstance(new, Query) new = self.async_path.select("disabled", "name") assert isinstance(new, AsyncQuery) def test_select_Query_has_valid_attributes(self): new = self.path.select("disabled", "name") assert new.api == self.path.api assert new.path == self.path assert new.keys == ("disabled", "name") new = self.async_path.select("disabled", "name") assert new.api == self.async_path.api assert new.path == self.async_path assert new.keys == ("disabled", "name") @pytest.mark.asyncio async def test_remove(self): self.path.remove("*1", "*2", "*3") self.path.api.assert_called_once_with("/interface/remove", **{".id": "*1,*2,*3"}) # Check if returned generator was consumed assert self.path.api.return_value.__iter__.call_count == 1 await self.async_path.remove("*1", "*2", "*3") self.async_path.api.assert_called_once_with("/interface/remove", **{".id": "*1,*2,*3"}) # Check if returned generator was consumed assert self.async_path.api.return_value.__aiter__.call_count == 1 @pytest.mark.asyncio async def test_add(self): return_value = ({"ret": "*1"},) self.path.api.return_value = return_value new = {"interface": "ether1", "address": "172.1.1.1/24"} new_id = self.path.add(**new) self.path.api.assert_called_once_with("/interface/add", **new) assert new_id == "*1" # async # mock async iterable async def mock_api(*args, **kwargs): for item in return_value: yield item self.async_path.api.side_effect = mock_api new_id = await self.async_path.add(**new) self.async_path.api.assert_called_once_with("/interface/add", **new) assert new_id == "*1" @pytest.mark.asyncio async def test_update(self): args = {"name": "wan", ".id": "*1"} self.path.update(**args) self.path.api.assert_called_once_with("/interface/set", **args) # Check if returned generator was consumed assert self.path.api.return_value.__iter__.call_count == 1 await self.async_path.update(**args) self.async_path.api.assert_called_once_with("/interface/set", **args) assert self.async_path.api.return_value.__aiter__.call_count == 1 @pytest.mark.asyncio async def test_iter(self): items = ({".id": "*1"}, {".id": "*2"}) self.path.api.return_value = items new_items = tuple(self.path) assert new_items == items self.path.api.assert_called_once_with("/interface/print") # async # mock async iterable async def mock_api(*args, **kwargs): for item in items: yield item self.async_path.api.side_effect = mock_api new_items = tuple([r async for r in self.async_path]) assert new_items == items self.async_path.api.assert_called_once_with("/interface/print") @pytest.mark.asyncio async def test_call(self): self.path.path = "/system/script" tuple(self.path("run")) self.path.api.assert_called_once_with("/system/script/run") # Check if returned generator was consumed assert self.path.api.return_value.__iter__.call_count == 1 # Async self.async_path.path = "/system/script" [r async for r in self.async_path("run")] self.async_path.api.assert_called_once_with("/system/script/run") # Check if returned generator was consumed assert self.async_path.api.return_value.__aiter__.call_count == 1 def test_select_without_keys(self): query = self.path.select() assert isinstance(query, Query) # Async query = self.async_path.select() assert isinstance(query, AsyncQuery) librouteros-3.4.1/tests/unit/test_protocol.py000066400000000000000000000137661473137246500215140ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from unittest.mock import MagicMock, patch from librouteros.protocol import Encoder, Decoder, ApiProtocol, AsyncApiProtocol from librouteros.connections import SocketTransport, AsyncSocketTransport from librouteros.exceptions import ( ProtocolError, FatalError, ) class Test_Decoder: def setup_method(self): self.decoder = Decoder() self.decoder.encoding = "ASCII" @pytest.mark.parametrize( "length,expected", ( (b"x", 0), # 120 (b"\xbf", 1), # 191 (b"\xdf", 2), # 223 (b"\xef", 3), # 239 ), ) def test_determineLength(self, length, expected): assert self.decoder.determineLength(length) == expected def test_determineLength_raises(self, bad_first_length_bytes): with pytest.raises(ProtocolError) as error: self.decoder.determineLength(bad_first_length_bytes) assert str(bad_first_length_bytes) in str(error.value) def test_decodeLength(self, valid_word_length): result = self.decoder.decodeLength(valid_word_length.encoded) assert result == valid_word_length.integer def test_decodeLength_raises(self, bad_length_bytes): with pytest.raises(ProtocolError) as error: self.decoder.decodeLength(bad_length_bytes) assert str(bad_length_bytes) in str(error.value) class Test_Encoder: def setup_method(self): self.encoder = Encoder() self.encoder.encoding = "ASCII" def test_encodeLength(self, valid_word_length): result = self.encoder.encodeLength(valid_word_length.integer) assert result == valid_word_length.encoded def test_encodeLength_raises_if_lenghth_is_too_big(self): """Length must be < 268435456""" invalid = 268435456 with pytest.raises(ProtocolError): self.encoder.encodeLength(invalid) def test_non_ASCII_word_encoding(self): """When encoding is ASCII, word may only contain ASCII characters.""" self.encoder.encoding = "ASCII" with pytest.raises(UnicodeEncodeError): self.encoder.encodeWord("łą") @patch.object(Encoder, "encodeLength", return_value=b"") def test_utf_8_word_encoding(self, enc_len_mock): """ Assert that len is taken from bytes, not utf8 word itself. len('ł') == 1 'ł'.encode(encoding='UTF8') == 2 """ self.encoder.encoding = "utf-8" word = "ł" self.encoder.encodeWord(word) enc_len_mock.assert_called_once_with(len(word.encode(self.encoder.encoding))) @patch.object(Encoder, "encodeWord", return_value=b"") def test_encodeSentence(self, encodeWord_mock): r""" Assert that: \x00 is appended to the sentence encodeWord is called == len(sentence) """ encoded = self.encoder.encodeSentence("first", "second") assert encodeWord_mock.call_count == 2 assert encoded[-1:] == b"\x00" class Test_ApiProtocol: def setup_method(self): self.protocol = ApiProtocol( transport=MagicMock(spec=SocketTransport), encoding="utf-8", ) self.async_protocol = AsyncApiProtocol( transport=MagicMock(spec=AsyncSocketTransport), encoding="utf-8", ) @pytest.mark.asyncio @patch.object(Encoder, "encodeSentence") async def test_writeSentence_calls_encodeSentence(self, encodeSentence_mock): self.protocol.writeSentence("/ip/address/print", "=key=value") encodeSentence_mock.assert_called_once_with("/ip/address/print", "=key=value") # async await self.async_protocol.writeSentence("/ip/address/print", "=key=value") encodeSentence_mock.assert_called_with("/ip/address/print", "=key=value") @pytest.mark.asyncio @patch.object(Encoder, "encodeSentence") async def test_writeSentence_calls_transport_write(self, encodeSentence_mock): """Assert that write is called with encoded sentence.""" self.protocol.writeSentence("/ip/address/print", "=key=value") self.protocol.transport.write.assert_called_once_with(encodeSentence_mock.return_value) # async await self.async_protocol.writeSentence("/ip/address/print", "=key=value") self.async_protocol.transport.write.assert_called_once_with(encodeSentence_mock.return_value) @pytest.mark.asyncio @patch("librouteros.protocol.iter", return_value=("!fatal", "reason")) async def test_readSentence_raises_FatalError(self, iter_mock): """Assert that FatalError is raised with its reason.""" with pytest.raises(FatalError) as error: self.protocol.readSentence() assert str(error.value) == "reason" assert self.protocol.transport.close.call_count == 1 @pytest.mark.asyncio @patch("librouteros.protocol.AsyncApiProtocol.readWord", side_effect=["!fatal", "reason", ""]) async def test_async_readSentence_raises_FatalError(self, readWord_mock): """Assert that FatalError is raised with its reason.""" with pytest.raises(FatalError) as error: await self.async_protocol.readSentence() assert str(error.value) == "reason" assert self.async_protocol.transport.close.call_count == 1 @pytest.mark.asyncio async def test_decoding_ignores_character_errors(self): word = b"\x11\xfb\x95" + "łąć".encode("utf-8") length = Encoder.encodeLength(len(word)) self.protocol.transport.read.side_effect = (length, b"", word) assert self.protocol.readWord() == "\x11łąć" # async self.async_protocol.transport.read.side_effect = (length, b"", word) assert await self.async_protocol.readWord() == "\x11łąć" @pytest.mark.asyncio async def test_close(self): self.protocol.close() self.protocol.transport.close.assert_called_once_with() # async await self.async_protocol.close() self.async_protocol.transport.close.assert_called_once_with() librouteros-3.4.1/tests/unit/test_query.py000066400000000000000000000076751473137246500210220ustar00rootroot00000000000000# -*- coding: UTF-8 -*- import pytest from unittest.mock import MagicMock, patch from librouteros.query import ( Query, Key, And, Or, AsyncQuery, ) class Test_Query: def setup_method(self): self.query = Query( path=MagicMock(), api=MagicMock(), keys=MagicMock(), ) self.async_query = AsyncQuery( path=MagicMock(), api=MagicMock(), keys=MagicMock(), ) def test_after_init_query_is_empty_tuple(self): assert self.query.query == tuple() assert self.async_query.query == tuple() def test_where_returns_self(self): assert self.query.where() == self.query assert self.async_query.where() == self.async_query def test_where_chains_from_args(self): self.query.where((1, 2, 3), (4, 5)) assert self.query.query == (1, 2, 3, 4, 5) self.async_query.where((1, 2, 3), (4, 5)) assert self.async_query.query == (1, 2, 3, 4, 5) @patch("librouteros.query.iter") def test_iter_with_proplist(self, iter_mock): self.query.keys = ("name", "disabled") self.query.query = ("key1", "key2") iter(self.query) self.query.api.rawCmd.assert_called_once_with( str(self.query.path.join.return_value), "=.proplist=name,disabled", "key1", "key2", ) def test_iter_with_proplist_async(self): self.async_query.keys = ("name", "disabled") self.async_query.query = ("key1", "key2") self.async_query.__aiter__() self.async_query.api.rawCmd.assert_called_once_with( str(self.async_query.path.join.return_value), "=.proplist=name,disabled", "key1", "key2", ) @patch("librouteros.query.iter") def test_iter_no_proplist(self, iter_mock): self.query.keys = () self.query.query = ("key1", "key2") iter(self.query) self.query.api.rawCmd.assert_called_once_with( str(self.query.path.join.return_value), "key1", "key2", ) def test_iter_no_proplist_async(self): self.async_query.keys = () self.async_query.query = ("key1", "key2") self.async_query.__aiter__() self.async_query.api.rawCmd.assert_called_once_with( str(self.async_query.path.join.return_value), "key1", "key2", ) class Test_Key: def setup_method(self): self.key = Key( name="key_name", ) @pytest.mark.parametrize( "param, expected", ( (True, "yes"), (False, "no"), ("yes", "yes"), (1, "1"), ), ) def test_eq(self, param, expected): result = tuple(self.key == param)[0] assert result == "?=key_name={}".format(expected) def test_ne(self): assert tuple(self.key != 1) == ("?=key_name=1", "?#!") @pytest.mark.parametrize( "param, expected", ( (True, "yes"), (False, "no"), ("yes", "yes"), (1, "1"), ), ) def test_lt(self, param, expected): result = tuple(self.key < param)[0] assert result == "? param)[0] assert result == "?>key_name={}".format(expected) def test_And(): assert tuple( And( (1,), (2,), (3,), (4,), ) ) == (1, 2, 3, 4, "?#&", "?#&", "?#&") def test_Or(): assert tuple( Or( (1,), (2,), (3,), (4,), ) ) == (1, 2, 3, 4, "?#|", "?#|", "?#|")