diff --git a/.circleci/config.yml b/.circleci/config.yml index 4518d46..54392e5 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -109,7 +109,7 @@ jobs: key: v1-repo-{{ .Environment.CIRCLE_SHA1 }} - run: shell: /bin/bash - name: "setup depends" + name: "set up depends" command: | python3 -m pip install --upgrade --user -r ./requirements.txt || : ; when: on_success diff --git a/.github/workflows/Tests.yml b/.github/workflows/Tests.yml index 67163d5..1dea0dc 100644 --- a/.github/workflows/Tests.yml +++ b/.github/workflows/Tests.yml @@ -87,11 +87,11 @@ jobs: LANG: ${{ matrix.lang-var }} steps: - uses: actions/checkout@v4 - - name: Setup Python + - name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - - name: Setup dependencies + - name: Set up dependencies run: | pip install --upgrade "pip>=21.0" "setuptools>=45.0" "wheel>=0.37" "build>=1.0.1"; pip install -r ./requirements.txt ; @@ -145,7 +145,7 @@ jobs: LANG: "en_US.utf-8" steps: - uses: actions/checkout@v4 - - name: Setup Python ${{ matrix.python-version }} + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} @@ -154,6 +154,7 @@ jobs: pip install --upgrade "pip>=21.0" "setuptools>=45.0" "wheel>=0.37" "build>=1.0.1"; pip install -r ./requirements.txt ; pip install -r ./tests/requirements.txt || true ; + pip install --upgrade -r ./docs/requirements.txt || true ; - name: Pre-Clean id: clean run: make -j1 -f Makefile clean || true ; @@ -191,9 +192,10 @@ jobs: COV_CORE_DATAFILE: ./coverage.xml CODECLIMATE_REPO_TOKEN: ${{ secrets.CODECLIMATE_TOKEN }} CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }} + DEEPSOURCE_DSN: ${{ secrets.DEEPSOURCE_DSN }} steps: - uses: actions/checkout@v4 - - name: Setup Python ${{ matrix.python-version }} + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} @@ -202,6 +204,7 @@ jobs: pip install --upgrade "pip>=21.0" "setuptools>=45.0" "wheel>=0.37" "build>=1.0.1"; pip install -r ./requirements.txt ; pip install -r ./tests/requirements.txt || true ; + pip install --upgrade -r ./docs/requirements.txt || true ; - name: Install code-climate tools for ${{ matrix.python-version }} if: ${{ runner.os }} == "Linux" shell: bash @@ -273,9 +276,10 @@ jobs: COV_CORE_DATAFILE: ./coverage.xml CODECLIMATE_REPO_TOKEN: ${{ secrets.CODECLIMATE_TOKEN }} CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }} + DEEPSOURCE_DSN: ${{ secrets.DEEPSOURCE_DSN }} steps: - uses: actions/checkout@v4 - - name: Setup Python ${{ matrix.python-version }} + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} @@ -284,6 +288,7 @@ jobs: pip install --upgrade "pip>=21.0" "setuptools>=45.0" "wheel>=0.37" "build>=1.0.1"; pip install --upgrade -r ./requirements.txt ; pip install --upgrade -r ./tests/requirements.txt || true ; + pip install --upgrade -r ./docs/requirements.txt || true ; - name: Install code-climate tools for ${{ matrix.python-version }} if: ${{ runner.os }} == "Linux" shell: bash @@ -349,7 +354,7 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Setup Python + - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.10" @@ -358,6 +363,7 @@ jobs: pip install --upgrade "pip>=21.0" "setuptools>=45.0" "wheel>=0.37" "build>=1.0.1"; pip install --upgrade -r ./requirements.txt ; pip install --upgrade -r ./tests/requirements.txt || true ; + pip install --upgrade -r ./docs/requirements.txt || true ; - name: Pre-Clean id: clean run: make -j1 -f Makefile clean || true ; @@ -393,7 +399,7 @@ jobs: CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }} steps: - uses: actions/checkout@v4 - - name: Setup Python ${{ matrix.python-version }} + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} @@ -402,6 +408,7 @@ jobs: pip install --upgrade "pip>=21.0" "setuptools>=45.0" "wheel>=0.37" "build>=1.0.1"; pip install --upgrade -r ./requirements.txt ; pip install --upgrade -r ./tests/requirements.txt || true ; + pip install --upgrade -r ./docs/requirements.txt || true ; - name: Install code-climate tools for ${{ matrix.python-version }} if: ${{ runner.os }} != "Linux" run: | @@ -490,7 +497,7 @@ jobs: CODECLIMATE_REPO_TOKEN: ${{ secrets.CODECLIMATE_TOKEN }} steps: - uses: actions/checkout@v4 - - name: Setup Python ${{ matrix.python-version }} + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} @@ -551,7 +558,7 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Setup Python + - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.12" @@ -564,6 +571,7 @@ jobs: pip install --upgrade "pip>=21.0" "setuptools>=45.0" "wheel>=0.37" "build>=1.0.1"; pip install --upgrade -r ./requirements.txt ; pip install --upgrade -r ./tests/requirements.txt || true ; + pip install --upgrade -r ./docs/requirements.txt || true ; - name: Pre-Clean id: clean run: make -j1 -f Makefile clean || true ; diff --git a/.gitignore b/.gitignore index 7df3751..d560915 100644 --- a/.gitignore +++ b/.gitignore @@ -109,3 +109,10 @@ ENV/ *.xcodeproj *.xcodeproj/* +# Project Specific +_build/ +docs/_build/ +docs/www/ +docs/make.bat +multicast/multicast/** +tests/tests/** diff --git a/LICENSE.md b/LICENSE.md index dcb6199..b7b1278 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,4 +1,4 @@ -License - MIT +# MIT License Copyright (c) 2017-2024, Mr. Walls @@ -22,39 +22,49 @@ copies or substantial portions of the Software. -END MIT License +*** -Included Licenses and additional Acknowledgments included with package: +## Included Licenses and additional Acknowledgments included with package -Files: `tests/context.py`, `tests/test_basic.py`, and `tests/test_usage.py` -.......................................... +* Files: `tests/context.py`, `tests/test_basic.py`, and `tests/test_usage.py` +*** Copyright (c) 2017-2022, Python Test Repo Template ALSO Licensed under MIT You may obtain a copy of the License at -http://www.github.com/reactive-firewall/python-repo/LICENSE.md -.......................................... +[MIT License](http://www.github.com/reactive-firewall/python-repo/LICENSE.md) +*** -Third-party Acknowledgments: +## Third-party Acknowledgments -Files: `multicast/send.py` and `multicast/recv.py` -.......................................... -Some code (namely: run, and parseArgs) was modified/derived from: -https://stackoverflow.com/a/52791404 -Copyright (c) 2019, "pterodragon" (https://stackoverflow.com/users/5256940/pterodragon) +* Files: `multicast/send.py` and `multicast/recv.py` +*** +Some code (namely: run, and parseArgs) was modified/derived from +[This answer on stackoverflow](https://stackoverflow.com/a/52791404) +Copyright (c) 2019, ["pterodragon"](https://stackoverflow.com/users/5256940/pterodragon) which was under CC-by-sa-4 license. -see https://creativecommons.org/licenses/by-sa/4.0/ for details +See [CC-by-sa-4](https://creativecommons.org/licenses/by-sa/4.0/) for details. The code in `parseArgs`, `run`, and `main` are thus also under CC-by-sa-4 -see https://creativecommons.org/licenses/by-sa/4.0/ for details -.......................................... +See [CC-by-sa-4](https://creativecommons.org/licenses/by-sa/4.0/) for details. +*** NO ASSOCIATION -Files: `tests/profiling.py` -.......................................... -Some code (namely: class timewith, @do_cprofile, @do_line_profile) was modified/derived from: -https://github.com/zapier/profiling-python-like-a-boss/tree/1ab93a1154 +* Files: `tests/profiling.py` +*** +Some code (namely: class timewith, @do_cprofile, @do_line_profile) was modified/derived from +[profiling-python-like-a-boss](https://github.com/zapier/profiling-python-like-a-boss/tree/1ab93a1154) Copyright (c) 2013, Zapier Inc. All rights reserved. which was under BSD-3 Clause license. -see https://github.com/zapier/profiling-python-like-a-boss/blob/1ab93a1154/LICENSE.md for details -.......................................... +See [BSD-3 Clause license](https://github.com/zapier/profiling-python-like-a-boss/blob/1ab93a1154/LICENSE.md) for details. +*** +NO ASSOCIATION + +* Files: `docs/config.py` +*** +Some code (namely: Sphinx setup output config) was modified/derived from +[Sphinx documentation](https://github.com/sphinx-doc/sphinx/blob/569fde84d49c984282355c768c16426af83132e2/doc/conf.py) +Copyright (c) 2007-2024 by the Sphinx team. All rights reserved. +which was under BSD-2 Clause license. +See [BSD License](https://github.com/sphinx-doc/sphinx/blob/569fde84d49c984282355c768c16426af83132e2/LICENSE.rst) for details. +*** NO ASSOCIATION diff --git a/Makefile b/Makefile index 0cf0d91..f890e5d 100644 --- a/Makefile +++ b/Makefile @@ -92,7 +92,7 @@ endif ifndef PIP_COMMON_FLAGS # Define common pip install flags - PIP_COMMON_FLAGS := --use-pep517 --upgrade --upgrade-strategy eager + PIP_COMMON_FLAGS := --use-pep517 --exists-action s --upgrade --upgrade-strategy eager endif # Define environment-specific pip install flags @@ -139,7 +139,7 @@ ifeq "$(RMDIR)" "" RMDIR=$(RM)Rd endif -PHONY: cleanup init must_be_root must_have_flake must_have_pytest uninstall +.PHONY: cleanup init clean-docs must_be_root must_have_flake must_have_pytest uninstall build: init ./setup.py $(QUIET)$(PYTHON) -W ignore -m build --sdist --wheel --no-isolation ./ || $(QUIET)$(PYTHON) -W ignore -m build ./ ; @@ -173,6 +173,7 @@ purge: clean uninstall test: cleanup $(QUIET)$(COVERAGE) run -p --source=multicast -m unittest discover --verbose --buffer -s ./tests -t $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) || $(PYTHON) -m unittest discover --verbose --buffer -s ./tests -t ./ || DO_FAIL="exit 2" ; + $(QUITE)$(WAIT) ; $(QUIET)$(DO_FAIL) ; $(QUIET)$(COVERAGE) combine 2>$(ERROR_LOG_PATH) || : ; $(QUIET)$(COVERAGE) report -m --include=* 2>$(ERROR_LOG_PATH) || : ; @@ -190,14 +191,20 @@ test-reports: test-reqs: test-reports init $(QUIET)$(PYTHON) -m pip install $(PIP_COMMON_FLAGS) $(PIP_ENV_FLAGS) -r tests/requirements.txt 2>$(ERROR_LOG_PATH) || true +docs-reqs: ./docs/ ./docs/requirements.txt init + $(QUIET)$(PYTHON) -m pip install $(PIP_COMMON_FLAGS) $(PIP_ENV_FLAGS) -r docs/requirements.txt 2>$(ERROR_LOG_PATH) || : ; + $(QUIET)$(WAIT) ; test-pytest: cleanup must_have_pytest test-reports $(QUIET)$(PYTHON) -m pytest --cache-clear --doctest-glob=multicast/*.py,tests/*.py --doctest-modules --cov=. --cov-append --cov-report=xml --junitxml=test-reports/junit.xml -v --rootdir=. || DO_FAIL="exit 2" ; + $(QUITE)$(WAIT) ; $(QUIET)$(DO_FAIL) ; $(QUIET)$(ECHO) "$@: Done." test-style: cleanup must_have_flake - $(QUIET)$(PYTHON) -m flake8 --ignore=W191,W391 --max-line-length=100 --verbose --count --config=.flake8.ini --show-source || true + $(QUIET)$(PYTHON) -m flake8 --ignore=W191,W391 --max-line-length=100 --verbose --count --config=.flake8.ini --show-source || DO_FAIL="exit 2" ; + $(QUITE)$(WAIT) ; + $(QUIET)$(DO_FAIL) ; $(QUIET)tests/check_spelling || true $(QUIET)tests/check_cc_lines || true $(QUIET)$(ECHO) "$@: Done." @@ -254,12 +261,27 @@ cleanup: $(QUIET)$(RMDIR) ./.tox/ 2>$(ERROR_LOG_PATH) || true $(QUIET)$(WAIT) ; +build-docs: ./docs/ ./docs/Makefile docs-reqs + $(QUIET)$(MAKE) -s -C ./docs/ -f Makefile html 2>$(ERROR_LOG_PATH) || DO_FAIL="exit 2" ; + $(QUIET)$(WAIT) ; + $(QUIET)mkdir $(INST_OPTS) ./docs/www 2>$(ERROR_LOG_PATH) >$(ERROR_LOG_PATH) || : ; + $(QUIET)$(BSMARK) ./docs/www 2>$(ERROR_LOG_PATH) >$(ERROR_LOG_PATH) || : ; + $(QUIET)$(WAIT) ; + $(QUIET)cp -fRp ./docs/_build/ ./docs/www/ 2>$(ERROR_LOG_PATH) || DO_FAIL="exit 35" ; + $(QUIET)$(WAIT) ; + $(QUIET)$(MAKE) -s -C ./docs/ -f Makefile clean 2>$(ERROR_LOG_PATH) || : ; + $(QUIET)$(WAIT) ; + $(QUIET)$(ECHO) "Documentation should be in docs/www/html/" + $(QUIET)$(DO_FAIL) ; + clean-docs: ./docs/ ./docs/Makefile - $(QUIET)$(MAKE) -s -C ./docs/ -f Makefile clean 2>$(ERROR_LOG_PATH) || true + $(QUIET)$(RM) ./docs/www/* 2>$(ERROR_LOG_PATH) || : ; + $(QUIET)$(RMDIR) ./docs/www/ 2>$(ERROR_LOG_PATH) || : ; + $(QUIET)$(MAKE) -s -C ./docs/ -f Makefile clean 2>$(ERROR_LOG_PATH) || : ; $(QUIET)$(WAIT) ; ./docs/: - $(QUIET)$(WAIT) ; + $(QUIET) : ; ./docs/Makefile: ./docs/ $(QUIET)$(WAIT) ; diff --git a/docs/CI.md b/docs/CI.md new file mode 100644 index 0000000..3428174 --- /dev/null +++ b/docs/CI.md @@ -0,0 +1,98 @@ +# CI + +## Service providers +*** + +Continuous integration testing is handled by GitHub Actions and the generous CircleCI service. + +[![CircleCI](https://dl.circleci.com/insights-snapshot/gh/reactive-firewall/multicast/master/workflow/badge.svg?window=30d)](https://app.circleci.com/insights/github/reactive-firewall/multicast/workflows/workflow/overview?branch=master&reporting-window=last-90-days&insights-snapshot=true) +[![DeepSource](https://app.deepsource.com/gh/reactive-firewall/multicast.svg/?label=active+issues&show_trend=true&token=SZUDMH7AtX399xLmONFAkiD6)](https://app.deepsource.com/gh/reactive-firewall/multicast/) + + +## MATs +*** + +Minimal acceptance testing is run across multiple versions of Python to ensure stable behavior +across a wide range of environments. Feature development and non-security related bug fixes are +done on development branches and then merged into the +[default branch (master)](https://github.com/reactive-firewall/multicast/blob/master/) for further +integration testing. This ensures the [stable](https://github.com/reactive-firewall/multicast/blob/stable/) +branch remains acceptable for production use. + +```mermaid +gitGraph + commit id:start + branch master + checkout master + commit + commit + branch stable + commit + checkout stable + merge master + checkout master + branch develop + checkout develop + commit + branch develop-nest + checkout develop-nest + commit + commit + checkout master + branch develop-B + checkout develop-B + commit + checkout master + branch develop-C + checkout develop-C + commit + commit + checkout develop + merge develop-nest + checkout develop-C + commit + checkout master + merge develop + merge develop-B + merge develop-C + commit + checkout stable + merge master + checkout master + commit +``` + + +## Testing +*** + +You can find all the testing code in the aptly named `tests/` directory. +* Unit-testing is primarily done with the `unittest` framework. +* Functional testing is done via additional checks, including an end-to-end check invoking an + actual pair of processes to test that `SAY` and `RECV` indeed work together. + + +## Dev Dependency Testing +*** + +### In a rush to get this module working? Then try using this in your own test workflow + +```bash +#cd /MY-AWESOME-DEV-PATH/multicast || git clone ... +make clean ; # cleans up from any previous tests hopefully +make test ; # runs the tests +make clean ; # cleans up for next test +``` + +#### Use PEP8 to check python code style? Great! Try this + +```bash +make clean ; # cleans up from any previous tests hopefully +make test-style ; # runs the tests for style +make clean ; # cleans up for next test +``` + + +*** +#### Copyright (c) 2021-2024, Mr. Walls +[MIT License](https://github.com/reactive-firewall/multicast/blob/stable/LICENSE.md) diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..80861c3 --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,183 @@ +# FAQ + +## Frequently Asked Questions + +```{toctree} +:maxdepth: 3 + +https://github.com/reactive-firewall/multicast/.github/CODE_OF_CONDUCT.md +https://github.com/reactive-firewall/multicast/.github/CONTRIBUTING.md +``` + +### How do I get this running? + +(assuming python3 is set up and installed) + +```bash +# cd /MY-AWESOME-DEV-PATH +git clone https://github.com/reactive-firewall/multicast.git multicast +cd ./multicast +git checkout stable +# make clean ; make test ; make clean ; +make install ; +python3 -m multicast --help ; +``` +#### DONE + +If all went well, `multicast` is now installed and working :tada: + + +### How do I use this to receive some UDP Multicast? + +(assuming project is set up, installed and you want to listen on 0.0.0.0) + +```bash +# cd /MY-AWESOME-DEV-PATH +python3 -m multicast HEAR --use-std --port 59595 --join-mcast-groups 224.0.0.1 --bind-group 224.0.0.1 +``` + +Caveat: `RECV` is much more useful if actually used in a loop like: + +```bash +# cd /MY-AWESOME-DEV-PATH +while true ; do # until user Ctrl+C interrupts +python3 -m multicast RECV --use-std --port 59595 --join-mcast-groups 224.0.0.1 --bind-group 224.0.0.1 +done +``` + + +### How do I use this to send UDP Multicast? + +(assuming `multicast` is set up and installed) + +```bash +# cd /MY-AWESOME-DEV-PATH +python3 -m multicast SAY --mcast-group 224.1.1.2 --port 59595 --message "Hello World!" +``` + + +### What is the basic API via python (instead of bash like above)? + +#### Caveat: this module is still a BETA +[Here is how it is tested right now](https://github.com/reactive-firewall/multicast/blob/cdd577549c0bf7c2bcf85d1b857c86135778a9ed/tests/test_usage.py#L251-L554) + +```python3 +import multicast as multicast +from multiprocessing import Process as Process + +# set up some stuff +_fixture_PORT_arg = int(59595) +_fixture_mcast_GRP_arg = """224.0.0.1""" # only use dotted notation for multicast group addresses +_fixture_host_BIND_arg = """224.0.0.1""" +_fixture_HEAR_args = [ + """--port""", _fixture_PORT_arg, + """--join-mcast-groups""", _fixture_mcast_GRP_arg, + """--bind-group""", _fixture_host_BIND_arg +] + +# spawn a listening proc + +def inputHandler(): + test_RCEV = multicast.recv.McastRECV() + buffer_string = str("""""") + buffer_string += test_RCEV._hearstep([_fixture_mcast_GRP_arg], _fixture_PORT_arg, _fixture_host_BIND_arg, _fixture_mcast_GRP_arg) + return buffer_string + +def printLoopStub(func): + for i in range( 0, 5 ): + print( str( func() ) ) + +p = Process( + target=multicast.__main__.McastDispatch().doStep, + name="HEAR", args=("HEAR", _fixture_HEAR_args,) + ) +p.start() + +# ... probably will return with nothing outside a handler function in a loop +``` +and elsewhere (like another function or even module) for the sender: +```python3 + +# assuming already did 'import multicast as multicast' + +_fixture_SAY_args = [ + """--port""", _fixture_PORT_arg, + """--mcast-group""", _fixture_mcast_GRP_arg, + """--message""", """'test message'""" +] +try: + multicast.__main__.McastDispatch().doStep("SAY", _fixture_SAY_args) + # Hint: use a loop to repeat or different arguments to vary message. +except Exception: + p.join() + raise RuntimeError("multicast seems to have failed.") + +# clean up some stuff +p.join() # if not already handled don't forget to join the process and other overhead +didWork = (int(p.exitcode) <= int(0)) # if you use a loop and need to know the exit code + +``` +#### Caveat: the above examples assume the reader is knowledgeable about general `IPC` theory and the standard python `multiprocessing` module and its use. + + +### What are the defaults? + +#### The default multicast group address is 224.0.0.1 + +From the [documentation](https://github.com/reactive-firewall/multicast/blob/v1.4/multicast/__init__.py#L185-L187): +> The Value of "224.0.0.1" is chosen as a default multicast group as per RFC-5771 +> on the rational that this group address will be treated as a local-net multicast +> (caveat: one should use link-local for ipv6) + +#### The default multicast Time-to-Live (TTL) is 1 + +From [RFC-1112 §6.1](https://www.rfc-editor.org/rfc/rfc1112#section-6.1) +> ... If the +> upper-layer protocol chooses not to specify a time-to-live, it should +> default to 1 for all multicast IP datagrams, so that an explicit +> choice is required to multicast beyond a single network. + +From the [documentation](https://github.com/reactive-firewall/multicast/blob/v1.4/multicast/__init__.py#L214-L217): +> A Value of 1 (one TTL) is chosen as per [RFC-1112 §6.1](https://www.rfc-editor.org/rfc/rfc1112#section-6.1) on the rational that an +> explicit value that could traverse beyond the local connected network should be +> chosen by the caller rather than the default value. This is in line with the principle +> of none, one or many. + +#### The default multicast destination port is 59559 + +From the [documentation](https://github.com/reactive-firewall/multicast/blob/v1.4/multicast/__init__.py#L155): +> Arbitrary port to use by default, though any dynamic and free port would work. + +> :exclamation: Caution: it is best to specify the port in use at this time as the default has yet to be properly assigned ( see related reactive-firewall/multicast#62 ) + + +### What does exit code _x_ mean? + +#### Python function return code meanings + +`0` is the default and implies *success*, and means the process has essentially (or actually) returned nothing (or `None`) + +`1` is used when a *single* result is returned (caveat: functions may return a single `tuple` instead of `None` to indicate exit code `1` by returning a `boolean` success value, and result (which may also be encapsulated as an iterable if needed) ) + +`2` is used to indicate a *value and reason* are returned (caveat: functions may return a single `tuple` with a single value and reason and the value can be a `tuple`) + +`-1` is used to mean *many* of unspecified length and otherwise functions as `1` + +#### CLI exit code meanings + +`0` *success* + +`1` *non-success* - and is often accompanied by warnings or errors + +`2 >` *failure* of specific reason + + +#### Everything Else +_(extra exit code meanings)_ + +Other codes (such as `126`) may or may not have meanings (such as skip) but are not handled within the scope of the Multicast Project at this time. + + +*** +#### Copyright (c) 2021-2024, Mr. Walls +[MIT License](https://github.com/reactive-firewall/multicast/blob/stable/LICENSE.md) diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..1c7aa1a --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,183 @@ +#!/usr/bin/env make -f + +# Makefile for Sphinx documentation +# .................................. +# Copyright (c) 2024, Mr. Walls +# .................................. +# Licensed under MIT (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# .......................................... +# http://www.github.com/reactive-firewall/multicast/LICENSE.md +# .......................................... +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# You can set these variables from the command line. +SPHINXOPTS = -c ../docs/ -v +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build +SRCDIR = . +# change this to the directory you store python code in +PROJECT_DOC_SRC_DIR = multicast + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(SRCDIR) +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(SRCDIR) + +.PHONY: help init 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)" + +init: ../docs/ + @ln -sf ../"$(PROJECT_DOC_SRC_DIR)" $(SRCDIR)/"$(PROJECT_DOC_SRC_DIR)" + @ln -sf ../tests $(SRCDIR)/tests 2>/dev/null || true + @ln -sf ../README.md $(SRCDIR)/README.md + @ln -sf ../LICENSE.md $(SRCDIR)/LICENSE.md + +clean: + @-rm -rf $(BUILDDIR)/* 2>/dev/null || true + @-rm -rfRd $(SRCDIR)/apidocs/* 2>/dev/null || true + @-unlink $(SRCDIR)/README.md 2>/dev/null || true + @-unlink $(SRCDIR)/tests 2>/dev/null || true + @-unlink $(SRCDIR)/LICENSE.md 2>/dev/null || true + @-unlink $(SRCDIR)/"$(PROJECT_DOC_SRC_DIR)" 2>/dev/null || true + +html: init + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: init + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: init + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: init + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: init + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: init + $(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: init + $(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/sample.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/sample.qhc" + +devhelp: init + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/sample" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/sample" + @echo "# devhelp" + +epub: init + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: init + $(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: init + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: init + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: init + $(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: init + $(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: init + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: init + $(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: init + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/USAGE.md b/docs/USAGE.md new file mode 100644 index 0000000..aa71910 --- /dev/null +++ b/docs/USAGE.md @@ -0,0 +1,113 @@ +# Usage + + +## Basic library usage +*** + +The API is in late alpha testing, and has not yet reached a beta (pre-release) stage. + +Here is an example of usage (circa v1.4) + +```python3 +import multicast +from multiprocessing import Process + +# set up some stuff +_fixture_PORT_arg = int(59595) +_fixture_mcast_GRP_arg = """224.0.0.1""" # only use dotted notation for multicast group addresses +_fixture_host_BIND_arg = None # Assuming this variable needs an initial value +_fixture_HEAR_args = [ + "--port", _fixture_PORT_arg, + "--join-mcast-groups", _fixture_mcast_GRP_arg, + "--bind-group", _fixture_mcast_GRP_arg +] + +# spawn a listening proc + +def inputHandle(): + test_RCEV = multicast.recv.McastRECV() + buffer_string = str("""""") + (didWork, result) = test_RCEV.doStep( + groups=[_fixture_mcast_GRP_arg], + port=_fixture_PORT_arg, + iface=_fixture_host_BIND_arg, + group=_fixture_mcast_GRP_arg, + ) + if didWork: + buffer_string += result + return buffer_string +def print_loop_stub(func): + for _ in range(5): + print(str(func())) + +p = Process( + target=multicast.__main__.McastDispatch().doStep, + name="HEAR", args=("HEAR", _fixture_HEAR_args,) + ) +p.start() + +# ... probably will return with nothing outside a handler function in a loop +``` +and elsewhere (like another function or even module) for the sender: +```python3 + +# assuming already did 'import multicast as multicast' + +_fixture_SAY_args = [ + """--port""", _fixture_PORT_arg, + """--mcast-group""", _fixture_mcast_GRP_arg, + """--message""", """'test message'""" +] +try: + multicast.__main__.McastDispatch().doStep("SAY", _fixture_SAY_args) + # Hint: use a loop to repeat or different arguments to vary message. +except Exception: + p.join() + raise RuntimeError("Multicast operation failed.") + +# clean up some stuff +p.join() # if not already handled don't forget to join the process and other overhead +didWork = (int(p.exitcode) <= int(0)) # if you use a loop and need to know the exit code + +``` +### Caveat +The above examples assume the reader is knowledgeable about general `IPC` theory and the standard Python `multiprocessing` module and its use. + + + +## CLI Usage +*** + +The CLI is actually not the best way to use this kind of library, so it should not be considered the full implementation. For testing and prototyping, though, it is quite convenient; therefore, I begin with it. + +CLI should work like so: + +```plain +multicast (SAY|RECV|HEAR) [-h|--help] [--use-std] [--daemon] [--port PORT] [--iface IFACE] [--pipe|-m MESSAGE|--message MESSAGE] [--group BIND_GROUP] [--groups [JOIN_MCAST_GROUPS ...]] +``` + +The commands are `SAY`, `RECV`, and `HEAR` for the CLI and are analogous to `send` listen/accept and echo functions of a 1-to-1 connection. + +### `SAY` + +The `SAY` command is used to send data messages via multicast datagrams. +* Note: the `--daemon` flag has no effect on the `SAY` command. + +### `RECV` + +The `RECV` command is used to receive multicast datagrams by listening or "joining" a multicast group. +* If the `--use-std` flag is set, the output is printed to the standard-output +* This command is purely for testing or interfacing with external components and not intended as a first-class API +* Note: If the `--daemon` flag is used the process will loop after reporting each datagrams until canceled, it has no effect on the `RECV` command. + +### `HEAR` + +The `HEAR` command is used to send data acknowledged messages via "HEAR" messages echoing select received multicast datagrams. +* While mostly a testing function, it is possible to use `HEAR` as a proxy for other send/recv instances by using the `--daemon` flag +* Note: this will use the same port for sends and receives and can lead to data loss if less than two groups are used. +* If more than one group is used via the `--groups` flag, then all but the bind group (via `--group`) will be echoed to the bind group. + + +*** +#### Copyright (c) 2021-2024, Mr. Walls +[MIT License](https://github.com/reactive-firewall/multicast/blob/stable/LICENSE.md) diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..c244972 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- + +# sample documentation build configuration file, created by +# sphinx-quickstart on Mon Apr 16 21:22:43 2012. + +# Copyright (c) 2012-2024, Mr. Walls + +# This file is execfile()d with the current directory set to its containing dir. + +# Note that not all possible configuration values are present in this +# autogenerated file. + +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("""..""")) +sys.path.insert(1, os.path.abspath("""multicast""")) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "5.2" + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +# for md us 'autodoc2' (pip install sphinx-autodoc2) +# for rst use 'sphinx.ext.autodoc' +extensions = [ + """sphinx.ext.napoleon""", """autodoc2""", """sphinx.ext.autosectionlabel""", + """sphinx.ext.githubpages""", """myst_parser""", + """sphinx.ext.autosummary""", """sphinx.ext.doctest""", """sphinx.ext.todo""", + """sphinx.ext.linkcode""", """sphinx.ext.viewcode""", """sphinx.ext.intersphinx""", +] + +# for md auto-docs +autodoc2_packages = [ + "multicast", + "tests", +] + +autodoc2_render_plugin = "myst" + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix of source filenames. +source_suffix = { + ".md": "markdown", + ".txt": "markdown", + ".rst": "restructuredtext", + ".yml": "yaml", + "Makefile": "makefile", +} + +# The encoding of source files. Official sphinx docs recommend utf-8-sig. +source_encoding = "utf-8-sig" + +# The master toctree document. +master_doc = "toc" + +# General information about the project. +project = "multicast" +copyright = "2017-2024, reactive-firewall" + +# The version info for the project yo"re documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = "v1.5" +# The full version, including alpha/beta/rc tags. +release = "v1.5.0-rc" + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' +today_fmt = "%Y.%B.%d" + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", ".github", ".circleci", "codecov_env", ".DS_Store", "**/.git", "dist", + "../tests/tests/**", "www", "**/docs", "../multicast/multicast/**", "*~" +] + +# The reST default role (used for this markup: `text`) to use for all documents. +# default_role = None + +# 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 + +# sigs should not have backslashes +strip_signature_backslash = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +show_authors = True + +# The name of the Pygments (syntax highlighting) style to use. +# pygments_style = "default" +pygments_style = "xcode" + +# and for dark-mode +# pygments_style_dark ="monokai" +pygments_style_dark = "github-dark" + + +pygments_options = { + """tabsize""": 4, + """stripall""": False, + """encoding""": "utf-8", +} + +pygments_yaml_options = { + """tabsize""": 2, + """stripall""": True, + """encoding""": "utf-8", +} + +highlight_options = { + "default": pygments_options, + "python": pygments_options, + "yaml": pygments_yaml_options, + "makefile": pygments_options, +} + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# Create table of contents entries for domain objects (e.g. functions, classes, attributes, etc.). +toc_object_entries = True + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "sphinxawesome_theme" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +html_short_title = "Multicast Docs" + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +try: + # extra import for CI test stability during discovery + import sphinxawesome_theme + from sphinxawesome_theme.postprocess import Icons + html_permalinks_icon = Icons.permalinks_icon +except Exception: + html_permalinks_icon = "#" + +# 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 not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' +html_last_updated_fmt = today_fmt.strip() + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# 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 = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = "multicast_doc" + + +# -- Options for MyST markdown parser ------------------------------------------- +# see https://myst-parser.readthedocs.io/en/latest/syntax/roles-and-directives.html#syntax-directives + +# be more like GFM with style +myst_enable_extensions = set(["tasklist", "strikethrough", "fieldlist"]) + +# for GFM diagrams and interoperability with other Markdown renderers +myst_fence_as_directive = ("mermaid", "suggestion", "note") + +# Focus only on github markdown +myst_gfm_only = True + +# how deep should markdown headers have anchors be generated +heading_anchors = 3 + +# -- Options for napoleon ext -------------------------------------------------- + +# include __init__ when it has docstrings +napoleon_include_init_with_doc = True + +# try to be smarter +napoleon_preprocess_types = True + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = {} +# The paper size ('letterpaper' or 'a4paper'). +# 'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +# 'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +# 'preamble': '', +# } + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ( + "index", + "Documentation.tex", + "Multicast Documentation", + "reactive-firewall", + "manual" + ), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + "index", + "multicast", + "Multicast Documentation", + ["reactive-firewall"], + 1 + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + "index", + "Multicast", + "Multicast Documentation", + "reactive-firewall", + "Multicast", + "Multicast Python Module.", + "Miscellaneous" + ), +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# -- Link resolver ------------------------------------------------------------- + +linkcode_url_prefix = str( + """https://github.com/reactive-firewall/{proj}""" +).format(proj=project) + +extlinks = {"""issue""": (str("""{prefix}/{suffix}""").format( + prefix=linkcode_url_prefix, suffix="""/issues/%s""" + ), + """issue #%s""") +} + +# try to link with official python3 documentation. +# see https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html for more +intersphinx_mapping = { + """python""": ( + """https://docs.python.org/3""", + (None, """python-inv.txt""") + ) +} + +def linkcode_resolve(domain, info): + if domain != """py""" or not info["""module"""]: + return None + filename = info["""module"""].replace(""".""", """/""") + theResult = str("""{prefix}/blob/{branch}/{file}.py""").format( + prefix=linkcode_url_prefix, branch="""stable""", file=filename + ) + if str("""/multicast.py""") in theResult: + theResult = theResult.replace("/multicast.py", "/multicast/__init__.py") + if str("""/tests.py""") in theResult: + theResult = theResult.replace("/tests.py", "/tests/__init__.py") + return theResult diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..8efd5bd --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,47 @@ +# Python Multicast Repo docs req file +# .................................. +# Copyright (c) 2017-2024, Mr. Walls +# .................................. +# Licensed under MIT (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# .......................................... +# http://www.github.com/reactive-firewall/multicast/LICENSE.md +# .......................................... +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#python +# time - builtin - PSF license +# re - builtin - PSF license? +# subprocess - PSF license +# argparse - builtin - PSF license +# socket - builtin - PSF license +# struct - builtin - PSF license +# argparse - builtin - PSF license +# argparse>=1.4.0 +# argparse - builtin - PSF license 3.7 = 62.6.0 +# setuptools - MIT license +setuptools>=38.0, !=71.0.1, !=72.0, !=69.4.0, !=69.3.0, !=60.3.0, !=59.1 +# virtualenv - MIT license +#virtualenv>=15.0.1 +# pgpy - BSD 3-Clause licensed +#pgpy>=0.4.1 +# tox - MIT license +#tox>=3.0.0, !=3.16.1 +# wheel - MIT license +wheel>=0.37.0 +# pip - MIT license +pip>=19.0 +# build - MIT license +# build>=0.5.1, !=1.0.3, !=0.6, !=0.6.1 !=1.1.0 !=1.2.0 +# sphinx - BSD license +sphinx>=5.2 +# sphinx-autodoc2 - MIT license +sphinx-autodoc2>=0.5.0 +# myst-parser - MIT license +myst-parser[linkify]>=4.0.0 +# sphinxawesome-theme - MIT license +sphinxawesome-theme>=0.5.0 diff --git a/docs/toc.md b/docs/toc.md new file mode 100644 index 0000000..4719177 --- /dev/null +++ b/docs/toc.md @@ -0,0 +1,65 @@ +# Welcome to Multicast's documentation! + +## Quickstart +**Welcome to the Multicast Python Library! Let's get you started quickly.** + +### Step 1: Install Python 3 + +* Ensure Python 3 is installed on your system. + +### Step 2: Clone the Repository + +* Open your terminal and run: + ```shell + git clone https://github.com/reactive-firewall/multicast.git + cd multicast + ``` + +### Step 3: Install the Package + +* Run: + ```shell + make install + ``` + +### Step 4: Sending Messages + +* Send a message using: + ```shell + python3 -m multicast SAY --mcast-group 224.1.1.2 --port 59595 --message "Hello, Multicast!" + ``` + +### Step 5: Receiving Messages + +* Receive messages by running: + ```shell + python3 -m multicast RECV --use-std --port 59595 --join-mcast-groups 224.1.1.2 + ``` + +**You're all set! Enjoy using Multicast for your projects.** + + + +## Contents + +```{toctree} +:maxdepth: 2 +:Name: Documentation +apidocs/index +/README.md +/FAQ.md +/CI.md +/USAGE.md +:Name: License +/LICENSE.md +``` + +## Overview + +```{autosummary} +``` + +--- +### Copyright (c) 2021-2024, Mr. Walls + +[![License - MIT](https://img.shields.io/github/license/reactive-firewall/multicast.svg?maxAge=3600)](https://github.com/reactive-firewall/multicast/blob/stable/LICENSE.md) diff --git a/multicast/__init__.py b/multicast/__init__.py index a318ddc..855bf7e 100644 --- a/multicast/__init__.py +++ b/multicast/__init__.py @@ -33,7 +33,7 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast as _multicast >>> @@ -50,7 +50,7 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast as _multicast >>> @@ -67,7 +67,7 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast as _multicast >>> @@ -81,12 +81,12 @@ global __version__ # skipcq: PYL-W0604 -__version__ = """1.5-rc""" +__version__ = """1.5.0""" """The version of this program. Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast as _multicast >>> @@ -107,7 +107,7 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> @@ -161,7 +161,7 @@ Minimal Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> @@ -210,7 +210,7 @@ Minimal Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> @@ -234,12 +234,12 @@ """Arbitrary TTL time to live to use by default, though any small (1-126) TTL would work. A Value of 1 (one TTL) is chosen as per RFC1112 Sec 6.1 on the rational that an explicit value that could traverse byond the local connected network should be - chosen by the caller rather than the default vaule. This is inline with the principle + chosen by the caller rather than the default value. This is inline with the principle of none, one or many. Minimal Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> @@ -269,7 +269,7 @@ Minimal Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> _BLANK = multicast._BLANK @@ -348,7 +348,7 @@ class mtool(abc.ABC): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.mtool is not None @@ -375,7 +375,7 @@ def buildArgs(cls, calling_parser_group): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.mtool is not None @@ -447,7 +447,7 @@ def parseArgs(cls, arguments=None): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.mtool is not None @@ -499,7 +499,7 @@ def checkToolArgs(cls, args): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> @@ -546,7 +546,7 @@ def __call__(self, *args, **kwargs): will be silently ignored. Subclasses should not reimplement __call__ directly and instead - should implement nessasary logic in the abstract doStep() function. + should implement necessary logic in the abstract doStep() function. """ return self.doStep(*args, **kwargs) diff --git a/multicast/__main__.py b/multicast/__main__.py index 8f0838d..b3ad074 100644 --- a/multicast/__main__.py +++ b/multicast/__main__.py @@ -21,7 +21,7 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast as multicast >>> @@ -158,7 +158,7 @@ class McastNope(mtool): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast.__main__ as _multicast >>> _multicast.McastNope is not None @@ -228,7 +228,7 @@ def NoOp(*args, **kwargs): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast.__main__ >>> @@ -264,7 +264,7 @@ class McastRecvHearDispatch(mtool): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast.__main__ as _multicast >>> _multicast.McastNope is not None @@ -334,7 +334,7 @@ def setupArgs(cls, parser): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast >>> multicast.hear is not None @@ -504,7 +504,7 @@ def doStep(self, *args): elif (sys.stdout.isatty()): # pragma: no cover print(_TOOL_MSG) except Exception as inerr: # pragma: no branch - w = str("WARNING - An error occured while") + w = str("WARNING - An error occurred while") w += str(" handling the arguments.") w += str(" Refused.") if (sys.stdout.isatty()): # pragma: no cover @@ -514,7 +514,7 @@ def doStep(self, *args): del inerr __EXIT_MSG = (2, "NoOp") except BaseException: # pragma: no branch - e = str("CRITICAL - An error occured while handling") + e = str("CRITICAL - An error occurred while handling") e += str(" the dispatch.") if (sys.stdout.isatty()): # pragma: no cover print(str(e)) @@ -526,7 +526,7 @@ def main(*argv): """Do main event stuff. The main(*args) function in multicast is expected to return a POSIX compatible exit code. - Regardles of errors the result as an 'exit code' (int) is returned. + Regardless of errors the result as an 'exit code' (int) is returned. The only exception is multicast.__main__.main(*args) which will exit with the underlying return codes. The expected return codes are as follows: @@ -541,7 +541,7 @@ def main(*argv): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.send is not None diff --git a/multicast/hear.py b/multicast/hear.py index e9ed046..a4adc51 100644 --- a/multicast/hear.py +++ b/multicast/hear.py @@ -21,7 +21,7 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. @@ -32,7 +32,7 @@ True >>> - Testcase 1: Recv should be automaticly imported. + Testcase 1: Recv should be automatically imported. A: Test that the multicast component is initialized. B: Test that the hear component is initialized. C: Test that the hear component has __doc__ @@ -95,14 +95,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Hear should be automaticly imported. + Testcase 1: Hear should be automatically imported. >>> multicast.hear.__package__ is not None True @@ -119,14 +119,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Hear should be automaticly imported. + Testcase 1: Hear should be automatically imported. >>> multicast.hear.__module__ is not None True @@ -144,14 +144,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Hear should be automaticly imported. + Testcase 1: Hear should be automatically imported. >>> multicast.hear.__name__ is not None True @@ -198,12 +198,12 @@ class McastServer(socketserver.UDPServer): """Generic Subclasses socketserver.UDPServer for handling daemon function. - Basicly simplifies testing by allowing a trivial echo back (case-insensitive) of string + Basically simplifies testing by allowing a trivial echo back (case-insensitive) of string data, after printing the sender's ip out. Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. @@ -213,7 +213,7 @@ class McastServer(socketserver.UDPServer): >>> from multicast.hear import McastServer as McastServer >>> - Testcase 1: McastServer should be automaticly imported. + Testcase 1: McastServer should be automatically imported. >>> McastServer.__name__ is not None True @@ -257,12 +257,12 @@ def kill_func(a_server): class MyUDPHandler(socketserver.BaseRequestHandler): """Subclasses socketserver.BaseRequestHandler for handling echo function. - Basicly simplifies testing by allowing a trivial echo back (case-insensitive) of string + Basically simplifies testing by allowing a trivial echo back (case-insensitive) of string data, after printing the sender's ip out. Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. @@ -272,7 +272,7 @@ class MyUDPHandler(socketserver.BaseRequestHandler): >>> from multicast.hear import MyUDPHandler as MyUDPHandler >>> - Testcase 1: MyUDPHandler should be automaticly imported. + Testcase 1: MyUDPHandler should be automatically imported. >>> MyUDPHandler.__name__ is not None True @@ -291,7 +291,7 @@ def handle(self): class HearUDPHandler(socketserver.BaseRequestHandler): """Subclasses socketserver.BaseRequestHandler for handling echo function. - Basicly simplifies testing by allowing a trivial echo back (case-insensitive) of string + Basically simplifies testing by allowing a trivial echo back (case-insensitive) of string data, after printing the sender's ip out. """ @@ -328,7 +328,7 @@ class McastHEAR(multicast.mtool): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast >>> multicast.hear is not None diff --git a/multicast/recv.py b/multicast/recv.py index 658fecd..ec8adb7 100644 --- a/multicast/recv.py +++ b/multicast/recv.py @@ -34,7 +34,7 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. @@ -45,7 +45,7 @@ True >>> - Testcase 1: Recv should be automaticly imported. + Testcase 1: Recv should be automatically imported. A: Test that the multicast component is initialized. B: Test that the recv component is initialized. C: Test that the recv component has __doc__ @@ -108,14 +108,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Recv should be automaticly imported. + Testcase 1: Recv should be automatically imported. >>> multicast.recv.__package__ is not None True @@ -132,14 +132,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Recv should be automaticly imported. + Testcase 1: Recv should be automatically imported. >>> multicast.recv.__module__ is not None True @@ -157,14 +157,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Recv should be automaticly imported. + Testcase 1: Recv should be automatically imported. >>> multicast.recv.__name__ is not None True @@ -215,7 +215,7 @@ def joinstep(groups, port, iface=None, bind_group=None, isock=None): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.recv is not None @@ -281,7 +281,7 @@ def tryrecv(msgbuffer, chunk, sock): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.recv is not None @@ -339,7 +339,7 @@ class McastRECV(multicast.mtool): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast >>> multicast.recv is not None @@ -394,7 +394,7 @@ def setupArgs(cls, parser): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast >>> multicast.recv is not None @@ -472,7 +472,7 @@ def _hearstep(groups, port, iface=None, bind_group=None): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.recv is not None diff --git a/multicast/send.py b/multicast/send.py index 361a231..b37ba1d 100644 --- a/multicast/send.py +++ b/multicast/send.py @@ -35,14 +35,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Send should be automaticly imported. + Testcase 1: Send should be automatically imported. A: Test that the send component is initialized. B: Test that the send.__MAGIC__ components are initialized. @@ -71,14 +71,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Send should be automaticly imported. + Testcase 1: Send should be automatically imported. >>> multicast.send.__package__ is not None True @@ -95,14 +95,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Send should be automaticly imported. + Testcase 1: Send should be automatically imported. >>> multicast.send.__module__ is not None True @@ -120,14 +120,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: Send should be automaticly imported. + Testcase 1: Send should be automatically imported. >>> multicast.send.__name__ is not None True @@ -172,7 +172,7 @@ class McastSAY(multicast.mtool): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast >>> multicast.send is not None @@ -217,7 +217,7 @@ def setupArgs(cls, parser): Testing: - Testcase 0: First setup test fixtures by importing multicast. + Testcase 0: First set up test fixtures by importing multicast. >>> import multicast >>> multicast.send is not None @@ -289,7 +289,7 @@ def setupArgs(cls, parser): def _sayStep(group, port, data): """Will send the given data over the given port to the given group. - The actual magic is handeled here. + The actual magic is handled here. """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) try: diff --git a/multicast/skt.py b/multicast/skt.py index 2dde40b..7c4f296 100644 --- a/multicast/skt.py +++ b/multicast/skt.py @@ -36,7 +36,7 @@ Minimal Acceptance Testing: -First setup test fixtures by importing multicast. +First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. @@ -47,7 +47,7 @@ True >>> -Testcase 1: SKT utils should be automaticly imported. +Testcase 1: SKT utils should be automatically imported. A: Test that the multicast.skt component is initialized. B: Test that the skt component is initialized. C: Test that the skt component has __doc__ @@ -85,14 +85,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: SKT utils should be automaticly imported. + Testcase 1: SKT utils should be automatically imported. >>> multicast.skt.__package__ is not None True @@ -109,14 +109,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: SKT utils should be automaticly imported. + Testcase 1: SKT utils should be automatically imported. >>> multicast.skt.__module__ is not None True @@ -134,14 +134,14 @@ Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. Testcase 0: Multicast should be importable. >>> import multicast >>> - Testcase 1: SKT utils should be automaticly imported. + Testcase 1: SKT utils should be automatically imported. >>> multicast.skt.__name__ is not None True @@ -170,14 +170,14 @@ def genSocket(): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.__doc__ is not None True >>> - Testcase 0: skt should be automaticly imported. + Testcase 0: skt should be automatically imported. A: Test that the multicast component is initialized. B: Test that the skt component is initialized. @@ -214,14 +214,14 @@ def endSocket(sock=None): Minimal Acceptance Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> multicast.__doc__ is not None True >>> - Testcase 0: skt should be automaticly imported. + Testcase 0: skt should be automatically imported. A: Test that the multicast component is initialized. B: Test that the skt component is initialized. diff --git a/setup.py b/setup.py index 50efdee..2633b4e 100755 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ Minimal Acceptance Testing: - Testcase 0: Just setup test fixtures by importing multicast. + Testcase 0: Just set up test fixtures by importing multicast. >>> import multicast >>> @@ -55,7 +55,7 @@ def readFile(filename): Testing: - First setup test fixtures by importing multicast. + First set up test fixtures by importing multicast. >>> import multicast >>> diff --git a/tests/MulticastUDPClient.py b/tests/MulticastUDPClient.py index a8f5df0..29cb3ad 100644 --- a/tests/MulticastUDPClient.py +++ b/tests/MulticastUDPClient.py @@ -87,7 +87,7 @@ class MCastClient(object): # skipcq: PYL-R0205 """For use as a test fixture. A trivial implementation of a socket-based object with a function named say. The say function of this class performs a send and recv on a given socket and - then prints out simple diognostics about the content sent and any response recived. + then prints out simple diognostics about the content sent and any response received. Testing: @@ -145,7 +145,7 @@ def __init__(self, *args, **kwargs): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.MulticastUDPClient as MulticastUDPClient >>> from MulticastUDPClient import MCastClient as MCastClient diff --git a/tests/check_spelling b/tests/check_spelling index ba94dcd..a60f7b5 100755 --- a/tests/check_spelling +++ b/tests/check_spelling @@ -59,45 +59,124 @@ # the amount of five dollars ($5.00). The foregoing limitations will apply # even if the above stated remedy fails of its essential purpose. ################################################################################ +# +# This script attempts to enforce spell-checking if the codespell tool is available. +# It accomplishes the following tasks: +# 1. Sets up error handling and cleanup mechanisms to ensure proper execution. +# 2. Determines the test root directory based on the project structure. +# 3. lint and check spelling +# 4. cleanup and report +# +# Usage Summary: +# To lint the project without making changes: +# ./tests/check_spelling +# To lint and auto-correct spelling errors: +# ./tests/check_spelling --fix +# +# Exit Code Summary: +# The script uses the EXIT_CODE variable to track exit conditions: +# - 0: Successful execution. +# - 1: General failure. +# - 2: Coverage combine or XML generation failed. +# - 3: git ls-tree command failed. +# - 40: Missing valid repository or source structure. +# - 126: Script already in progress or command not executable. +# - 129: Received SIGHUP signal. +# - 130: Received SIGINT signal (Ctrl+C). +# - 131: Received SIGQUIT signal. +# - 137: Received SIGABRT signal. +# - 143: Received SIGTERM signal. +# +# The primary goal is to allow linter like spell-checking. ulimit -t 600 -PATH="/bin:/sbin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin" +# setting the path may break brain-dead CI that uses crazy paths +# PATH="/bin:/sbin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin" umask 137 -LOCK_FILE="${TMPDIR:-/tmp}/spelling_test_script_lock" +# force utf-8 for spelling +export LC_CTYPE="${LC_CTYPE:-en_US.UTF-8}" + +LOCK_FILE="${TMPDIR:-/tmp}/org.pak.multicast.spell-check-shell" EXIT_CODE=1 -# exit fast if command is missing -test -x /usr/bin/spellintian || exit 126 ; +test -x $(command -v grep) || exit 126 ; +test -x $(command -v python3) || exit 126 ; +test -x $(command -v git) || exit 126 ; +hash -p ./.github/tool_shlock_helper.sh shlock || exit 255 ; +test -x "$(command -v shlock)" || exit 126 ; +test -x $(command -v codespell) || exit 126 ; + +# Set codespell options +CODESPELL_OPTIONS="--quiet-level=4 --builtin clear,rare,code -L assertIn" + +function cleanup() { + rm -f ${LOCK_FILE} 2>/dev/null || : ; wait ; + # unset when done + unset LOCK_FILE 2>/dev/null || : ; + hash -d shlock 2>/dev/null || : ; +} if [[ ( $(shlock -f ${LOCK_FILE} -p $$ ) -eq 0 ) ]] ; then EXIT_CODE=0 - trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null > /dev/null || true ; wait ; exit 129 ;' SIGHUP || EXIT_CODE=129 - trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null > /dev/null || true ; wait ; exit 143 ;' SIGTERM || EXIT_CODE=143 - trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null > /dev/null || true ; wait ; exit 131 ;' SIGQUIT || EXIT_CODE=131 + trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null || true ; wait ; exit 129 ;' SIGHUP || EXIT_CODE=129 + trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null || true ; wait ; exit 143 ;' SIGTERM || EXIT_CODE=143 + trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null || true ; wait ; exit 131 ;' SIGQUIT || EXIT_CODE=131 # SC2173 - https://github.com/koalaman/shellcheck/wiki/SC2173 - #trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null > /dev/null || true ; wait ; exit 1 ;' SIGSTOP || EXIT_CODE=7 - trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null > /dev/null || true ; wait ; exit 130 ;' SIGINT || EXIT_CODE=130 - trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null > /dev/null || true || true ; wait ; exit 137 ;' SIGABRT || EXIT_CODE=137 - trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null > /dev/null || true ; wait ; exit ${EXIT_CODE} ;' EXIT || EXIT_CODE=1 + #trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null || true ; wait ; exit 1 ;' SIGSTOP || EXIT_CODE=7 + trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null || true ; wait ; exit 130 ;' SIGINT || EXIT_CODE=130 + trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null || true || true ; wait ; exit 137 ;' SIGABRT || EXIT_CODE=137 + trap 'cleanup 2>/dev/null || rm -f ${LOCK_FILE} 2>/dev/null || true ; wait ; exit ${EXIT_CODE} ;' EXIT || EXIT_CODE=1 else - echo Test already in progress by `head ${LOCK_FILE}` ; - false ; - exit 126 ; + # shellcheck disable=SC2046 + printf "\t%s\n" "Check Setup Scripts Tests Coverage already in progress by "$(head "${LOCK_FILE}") >&2 ; + exit 126 ; fi +# this is how test files are found: + # THIS IS THE ACTUAL TEST -THE_TEMP_FILE="/tmp/swapfile_spellcheck_${RANDOM}.tmp.txt" ; -( (spellintian "${@:-./**/*}" 2>/dev/null | fgrep -v "(duplicate word)" | fgrep " -> ") & (spellintian "${@:-./*}" 2>/dev/null | fgrep -v "(duplicate word)" | fgrep " -> ") & (spellintian "${@:-./**/**/*}" 2>/dev/null | fgrep -v "(duplicate word)" | fgrep " -> ") ) | sort -h | uniq | tee -a ${THE_TEMP_FILE:-/dev/null} ; -wait ; -THECOUNT=$( (wc -l ${THE_TEMP_FILE} 2>/dev/null || echo 0) | cut -d\ -f 1 ) ; -EXIT_CODE=${THECOUNT} ; -if [[ ("${THECOUNT}" -le 1) ]] ; then - EXIT_CODE=0 ; - echo "OK: Found no detected spelling errors." ; +_TEST_ROOT_DIR=$(git rev-parse --show-toplevel 2>/dev/null) ; +if [[ -d ../.git ]] ; then + _TEST_ROOT_DIR="../" ; +elif [[ -d ./.git ]] ; then + _TEST_ROOT_DIR=$(pwd) ; +elif [[ ( -d $(git rev-parse --show-toplevel 2>/dev/null) ) ]] ; then + _TEST_ROOT_DIR=$(git rev-parse --show-toplevel 2>/dev/null) ; else - echo "FAIL: Found ${THECOUNT:-many} spelling errors." ; + printf "\t%s\n" "FAIL: missing valid repository or source structure" >&2 ; + EXIT_CODE=40 fi -rm -f ${THE_TEMP_FILE} 2>/dev/null >> /dev/null || true ; + +# Get a list of files to check using git ls-tree with filtering +FILES_TO_CHECK=$(git ls-tree -r --full-tree --name-only HEAD -- *.md *.py *.txt **/*.md **/*.txt **/*.py 2>/dev/null || EXIT_CODE=3) + +# Enable auto-correction if '--fix' argument is provided +if [[ "$1" == "--fix" ]]; then + CODESPELL_OPTIONS="--write-changes --interactive 2 ${CODESPELL_OPTIONS}" + printf "%s\n" "Auto-correction enabled." +fi + +# THIS IS THE ACTUAL TEST +# Iterate over files and run codespell +for FILE in $FILES_TO_CHECK; do + printf "%s\n" "Checking ${FILE}" ; + { codespell $CODESPELL_OPTIONS "${FILE}" || EXIT_CODE=$? ;} 2>/dev/null ; wait ; +done + +# cleaning up and reporting + +if [[ ("${EXIT_CODE}" -eq 0) ]] ; then + printf "%s\n" "OK: Found no detected spelling errors." ; +else + printf "%s\n" "FAIL: Found spelling errors." ; +fi + +cleanup || rm -f ${LOCK_FILE} 2>/dev/null || : ; + +# unset when done +unset _TEST_ROOT_DIR 2>/dev/null || : ; +unset CODESPELL_OPTIONS 2>/dev/null || : ; + wait ; -exit ${EXIT_CODE:255} ; +exit ${EXIT_CODE:-255} ; diff --git a/tests/context.py b/tests/context.py index 2ab7c9a..81a8156 100644 --- a/tests/context.py +++ b/tests/context.py @@ -109,11 +109,11 @@ __BLANK = str("""""") """ - A literaly named variable to improve readability of code when using a blank string. + A literally named variable to improve readability of code when using a blank string. Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context as _context >>> @@ -142,7 +142,7 @@ def getCoverageCommand(): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context as context >>> @@ -178,7 +178,7 @@ def __check_cov_before_py(): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context >>> @@ -222,7 +222,7 @@ def getPythonCommand(): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context >>> @@ -263,12 +263,12 @@ def checkCovCommand(args=[None]): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context as context >>> - Testcase 1: Function should return unmodified arguments if 'coverage' is not in the first argument. + Testcase 1: Function should return unmodified arguments if 'coverage' is missing. >>> context.checkCovCommand(["python", "script.py"]) ['python', 'script.py'] @@ -340,7 +340,7 @@ def checkStrOrByte(theInput): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context as _context >>> @@ -416,7 +416,7 @@ def checkPythonCommand(args, stderr=None): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context >>> @@ -430,20 +430,27 @@ def checkPythonCommand(args, stderr=None): Testcase 2: Function should capture stderr when specified. >>> import subprocess - >>> test_args_2 = [str(sys.executable), '-c', 'import sys; print("Error", file=sys.stderr)'] + >>> test_args_2 = [ + ... str(sys.executable), '-c', 'import sys; print("Error", file=sys.stderr)' + ... ] + >>> >>> tests.context.checkPythonCommand(test_args_2, stderr=subprocess.STDOUT) 'Error\\n' Testcase 3: Function should handle exceptions and return output. >>> test_fixture_e = [str(sys.executable), '-c', 'raise ValueError("Test error")'] - >>> tests.context.checkPythonCommand(test_fixture_e, stderr=subprocess.STDOUT) #doctest: +ELLIPSIS + >>> tests.context.checkPythonCommand( + ... test_fixture_e, stderr=subprocess.STDOUT + ... ) #doctest: +ELLIPSIS 'Traceback (most recent call last):\\n...ValueError...' Testcase 4: Function should return the output as a string. >>> test_fixture_s = [str(sys.executable), '-c', 'print(b"Bytes output")'] - >>> isinstance(tests.context.checkPythonCommand(test_fixture_s, stderr=subprocess.STDOUT), str) + >>> isinstance(tests.context.checkPythonCommand( + ... test_fixture_s, stderr=subprocess.STDOUT + ... ), str) True @@ -493,12 +500,12 @@ def checkPythonFuzzing(args=[None], stderr=None): def debugBlob(blob=None): """Helper function to debug unexpected outputs. - Especialy usefull for cross-python testing where output may differ + Especially useful for cross-python testing where output may differ yet may be from the same logical data. Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context >>> @@ -564,7 +571,7 @@ def debugtestError(someError): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context >>> @@ -639,7 +646,7 @@ def debugUnexpectedOutput(expectedOutput, actualOutput, thepython): Meta Testing: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context >>> @@ -709,7 +716,7 @@ class BasicUsageTestSuite(unittest.TestCase): Meta Tests - Creation: - First setup test fixtures by importing test context. + First set up test fixtures by importing test context. >>> import tests.context >>> @@ -735,11 +742,11 @@ class BasicUsageTestSuite(unittest.TestCase): @classmethod def setUpClass(cls): - """Overides unittest.TestCase.setUpClass(cls) to setup thepython test fixture.""" + """Overrides unittest.TestCase.setUpClass(cls) to set up thepython test fixture.""" cls._thepython = getPythonCommand() def setUp(self): - """Overides unittest.TestCase.setUp(unittest.TestCase). + """Overrides unittest.TestCase.setUp(unittest.TestCase). Defaults is to skip test if class is missing thepython test fixture. """ if not self._thepython: @@ -759,6 +766,6 @@ def test_finds_python_WHEN_testing(self): @classmethod def tearDownClass(cls): - """Overides unittest.TestCase.tearDownClass(cls) to clean up thepython test fixture.""" + """Overrides unittest.TestCase.tearDownClass(cls) to clean up thepython test fixture.""" cls._thepython = None diff --git a/tests/test_deps.py b/tests/test_deps.py index ec57089..796a7f2 100644 --- a/tests/test_deps.py +++ b/tests/test_deps.py @@ -54,7 +54,7 @@ class TestRequirementsTxt(context.BasicUsageTestSuite): """Test cases for 'tests/requirements.txt'.""" - + __module__ = """tests.test_deps""" def test_requirements_file_exists(self): @@ -81,14 +81,17 @@ def test_requirements_format(self): line, pattern, str("""Invalid requirement format at line {line_number}: '{line}'""").format( - line_number=line_number, line=line - ) + line_number=line_number, line=line + ) ) - @unittest.skipUnless((_sys.platform.startswith("linux") or - _sys.platform.startswith("darwin")), "This test is not supported on OS.") + @unittest.skipUnless( + ( + _sys.platform.startswith("linux") or _sys.platform.startswith("darwin") + ), "This test is not supported on this OS." + ) def test_requirements_installation(self): - """Attempt to install dependencies from 'tests/requirements.txt' in a virtual environment.""" + """Attempt to install dependencies from 'tests/requirements.txt' in a virtual env.""" env_dir = 'test_env' builder = venv.EnvBuilder(with_pip=True) builder.create(env_dir) diff --git a/tests/test_usage.py b/tests/test_usage.py index 395dce3..e14ac26 100644 --- a/tests/test_usage.py +++ b/tests/test_usage.py @@ -127,7 +127,7 @@ class MulticastTestSuite(context.BasicUsageTestSuite): __name__ = """tests.test_usage.MulticastTestSuite""" def test_aborts_WHEN_calling_multicast_GIVEN_invalid_tools(self): - """Tests the imposible state for CLI tools given bad tools""" + """Tests the impossible state for CLI tools given bad tools""" theResult = False fail_fixture = str("""multicast.__main__.McastDispatch().useTool(JUNK) == error""") tst_dispatch = multicast.__main__.McastDispatch() diff --git a/tox.ini b/tox.ini index 1c45f98..eee252f 100644 --- a/tox.ini +++ b/tox.ini @@ -22,6 +22,7 @@ passenv = deps = -r{toxinidir}/requirements.txt -r{toxinidir}/tests/requirements.txt + -r{toxinidir}/docs/requirements.txt [testenv:py{27,33,34,35,36,37,38,39,310.311,312,313}] @@ -531,7 +532,7 @@ commands = flake8 --ignore=W191,W391 --verbose --max-line-length=100 --count description = Documentation Tests whitelist_externals = make deps = - docs: sphinx>=1.6.3 + docs: sphinx>=5.2 flake8>=2.5.4 mccabe>=0.6.1 pyflakes>=1.1.0 @@ -540,6 +541,8 @@ deps = {[base]deps} commands = - make -s -C ./docs/ -f Makefile clean + - make -s -C ./docs/ -f Makefile html + - make -s -C ./docs/ -f Makefile clean [coverage:run]