diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index e7d592e..0000000 --- a/.coveragerc +++ /dev/null @@ -1,2 +0,0 @@ -[run] -omit = */tests* diff --git a/.flake8 b/.flake8 deleted file mode 100644 index c057b0f..0000000 --- a/.flake8 +++ /dev/null @@ -1,2 +0,0 @@ -[flake8] -max-line-length=119 diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 9f6ea51..01233b9 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -4,7 +4,7 @@ # For more information see: # https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions -name: Python package +name: Pytests on: push: @@ -17,11 +17,14 @@ on: jobs: build: - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} strategy: matrix: + os: + - ubuntu-latest + - windows-latest + - macos-latest python-version: - - "3.5" - "3.6" - "3.7" - "3.8" @@ -38,6 +41,7 @@ jobs: run: | python -m pip install --upgrade pip python -m pip install -r requirements-test.txt + python -m pip install -e . - name: Test with pytest run: | pytest diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 45f221f..74a7905 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,12 +1,14 @@ --- repos: + - repo: https://github.com/adrienverge/yamllint rev: v1.26.3 hooks: - name: check YAML format id: yamllint + - repo: https://github.com/psf/black - rev: 22.1.0 + rev: 22.3.0 hooks: - name: re-format with black id: black @@ -17,14 +19,11 @@ repos: hooks: - name: remove whitespaces id: trailing-whitespace + - name: add newline to end of files + id: end-of-file-fixer - repo: https://gitlab.com/pycqa/flake8 - rev: 21d3c70d676007470908d39b73f0521d39b3b997 + rev: 4.0.1 hooks: - name: check-format with flake8 id: flake8 - args: - - --show-source - - --statistics - - --count - - --max-complexity=12 diff --git a/.yamllint.yaml b/.yamllint.yaml index e9147c4..da62e9a 100644 --- a/.yamllint.yaml +++ b/.yamllint.yaml @@ -1,8 +1,9 @@ extends: default +ignore: | + .github/workflows/* + venv/* + rules: - truthy: - ignore: | - .github/workflows/* indentation: spaces: 2 diff --git a/Makefile b/Makefile index f5ea67e..482d2ad 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,10 @@ -all: precommit test +all: test precommit test: - python setup.py test + @pytest -precommit:: - pre-commit run -a +precommit: + @pre-commit run -a publish: @python setup.py bdist_wheel upload diff --git a/README.rst b/README.rst index 611cdac..de8db25 100644 --- a/README.rst +++ b/README.rst @@ -29,7 +29,7 @@ Installation pip install readchar -The :code:`readchar` library works with python 2.7, 3.4, 3.5, 3.6 and Pypy. +The :code:`readchar` library works with python 3.6, 3.7, 3.8 and 3.10. Usage ----- diff --git a/readchar/__init__.py b/readchar/__init__.py index f4ffd5c..edbb350 100644 --- a/readchar/__init__.py +++ b/readchar/__init__.py @@ -1,4 +1,14 @@ -from . import key -from .readchar import readchar, readkey +from sys import platform -__all__ = [readchar, readkey, key] + +if platform.startswith("linux") or platform in ("darwin"): + from .read_linux import readchar, readkey + from . import key_linux as key +elif platform in ("win32", "cygwin"): + from .read_windows import readchar, readkey + from . import key_windows as key +else: + raise NotImplementedError(f"The platform {platform} is not supported yet") + + +__all__ = ["readchar", "readkey", "key"] diff --git a/readchar/key.py b/readchar/key.py deleted file mode 100644 index 865427f..0000000 --- a/readchar/key.py +++ /dev/null @@ -1,98 +0,0 @@ -# common -LF = "\x0d" -CR = "\x0a" -ENTER = "\x0d" -BACKSPACE = "\x08" -SUPR = "" -SPACE = "\x20" -ESC = "\x1b" - -# CTRL -CTRL_A = "\x01" -CTRL_B = "\x02" -CTRL_C = "\x03" -CTRL_D = "\x04" -CTRL_E = "\x05" -CTRL_F = "\x06" -CTRL_G = "\x07" -CTRL_H = "\x08" -CTRL_I = "\t" -CTRL_J = "\n" -CTRL_K = "\x0b" -CTRL_L = "\x0c" -CTRL_M = "\r" -CTRL_N = "\x0e" -CTRL_O = "\x0f" -CTRL_P = "\x10" -CTRL_Q = "\x11" -CTRL_R = "\x12" -CTRL_S = "\x13" -CTRL_T = "\x14" -CTRL_U = "\x15" -CTRL_V = "\x16" -CTRL_W = "\x17" -CTRL_X = "\x18" -CTRL_Y = "\x19" -CTRL_Z = "\x1a" - -# ALT -ALT_A = "\x1b\x61" - -# CTRL + ALT -CTRL_ALT_A = "\x1b\x01" - -# cursors -UP = "\x1b\x5b\x41" -DOWN = "\x1b\x5b\x42" -LEFT = "\x1b\x5b\x44" -RIGHT = "\x1b\x5b\x43" - -CTRL_ALT_SUPR = "\x1b\x5b\x33\x5e" - -# other -F1 = "\x1b\x4f\x50" -F2 = "\x1b\x4f\x51" -F3 = "\x1b\x4f\x52" -F4 = "\x1b\x4f\x53" -F5 = "\x1b\x4f\x31\x35\x7e" -F6 = "\x1b\x4f\x31\x37\x7e" -F7 = "\x1b\x4f\x31\x38\x7e" -F8 = "\x1b\x4f\x31\x39\x7e" -F9 = "\x1b\x4f\x32\x30\x7e" -F10 = "\x1b\x4f\x32\x31\x7e" -F11 = "\x1b\x4f\x32\x33\x7e" -F12 = "\x1b\x4f\x32\x34\x7e" - -PAGE_UP = "\x1b\x5b\x35\x7e" -PAGE_DOWN = "\x1b\x5b\x36\x7e" -HOME = "\x1b\x5b\x48" -END = "\x1b\x5b\x46" - -INSERT = "\x1b\x5b\x32\x7e" -SUPR = "\x1b\x5b\x33\x7e" - - -ESCAPE_SEQUENCES = ( - ESC, - ESC + "\x5b", - ESC + "\x5b" + "\x31", - ESC + "\x5b" + "\x32", - ESC + "\x5b" + "\x33", - ESC + "\x5b" + "\x35", - ESC + "\x5b" + "\x36", - ESC + "\x5b" + "\x31" + "\x35", - ESC + "\x5b" + "\x31" + "\x36", - ESC + "\x5b" + "\x31" + "\x37", - ESC + "\x5b" + "\x31" + "\x38", - ESC + "\x5b" + "\x31" + "\x39", - ESC + "\x5b" + "\x32" + "\x30", - ESC + "\x5b" + "\x32" + "\x31", - ESC + "\x5b" + "\x32" + "\x32", - ESC + "\x5b" + "\x32" + "\x33", - ESC + "\x5b" + "\x32" + "\x34", - ESC + "\x4f", - ESC + ESC, - ESC + ESC + "\x5b", - ESC + ESC + "\x5b" + "\x32", - ESC + ESC + "\x5b" + "\x33", -) diff --git a/readchar/key_linux.py b/readchar/key_linux.py new file mode 100644 index 0000000..26f5b0c --- /dev/null +++ b/readchar/key_linux.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- + +# common +LF = "\x0a" +CR = "\x0d" +ENTER = LF +BACKSPACE = "\x7F" +SPACE = "\x20" +ESC = "\x1b" +TAB = "\x09" + +# CTRL +CTRL_A = "\x01" +CTRL_B = "\x02" +CTRL_C = "\x03" +CTRL_D = "\x04" +CTRL_E = "\x05" +CTRL_F = "\x06" +CTRL_G = "\x07" +CTRL_H = "\x08" +CTRL_I = TAB +CTRL_J = LF +CTRL_K = "\x0b" +CTRL_L = "\x0c" +CTRL_M = CR +CTRL_N = "\x0e" +CTRL_O = "\x0f" +CTRL_P = "\x10" +CTRL_Q = "\x11" +CTRL_R = "\x12" +CTRL_S = "\x13" +CTRL_T = "\x14" +CTRL_U = "\x15" +CTRL_V = "\x16" +CTRL_W = "\x17" +CTRL_X = "\x18" +CTRL_Y = "\x19" +CTRL_Z = "\x1a" + +# ALT +ALT_A = "\x1b\x61" + +# CTRL + ALT +CTRL_ALT_A = "\x1b\x01" + +# cursors +UP = "\x1b\x5b\x41" +DOWN = "\x1b\x5b\x42" +LEFT = "\x1b\x5b\x44" +RIGHT = "\x1b\x5b\x43" + +CTRL_ALT_SUPR = "\x1b\x5b\x33\x5e" +CTRL_ALT_DELETE = CTRL_ALT_SUPR + +# other +F1 = "\x1b\x4f\x50" +F2 = "\x1b\x4f\x51" +F3 = "\x1b\x4f\x52" +F4 = "\x1b\x4f\x53" +F5 = "\x1b\x5b\x31\x35\x7e" +F6 = "\x1b\x5b\x31\x37\x7e" +F7 = "\x1b\x5b\x31\x38\x7e" +F8 = "\x1b\x5b\x31\x39\x7e" +F9 = "\x1b\x5b\x32\x30\x7e" +F10 = "\x1b\x5b\x32\x31\x7e" +F11 = "\x1b\x5b\x32\x33\x7e" +F12 = "\x1b\x5b\x32\x34\x7e" + +PAGE_UP = "\x1b\x5b\x35\x7e" +PAGE_DOWN = "\x1b\x5b\x36\x7e" +HOME = "\x1b\x5b\x48" +END = "\x1b\x5b\x46" + +INSERT = "\x1b\x5b\x32\x7e" +SUPR = "\x1b\x5b\x33\x7e" +DELETE = SUPR diff --git a/readchar/key_windows.py b/readchar/key_windows.py new file mode 100644 index 0000000..22d7e0f --- /dev/null +++ b/readchar/key_windows.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- + +# common +LF = "\x0a" +CR = "\x0d" +ENTER = CR +BACKSPACE = "\x08" +SPACE = "\x20" +ESC = "\x1b" +TAB = "\x09" + +# CTRL +CTRL_A = "\x01" +CTRL_B = "\x02" +CTRL_C = "\x03" +CTRL_D = "\x04" +CTRL_E = "\x05" +CTRL_F = "\x06" +CTRL_G = "\x07" +CTRL_H = BACKSPACE +CTRL_I = TAB +CTRL_J = LF +CTRL_K = "\x0b" +CTRL_L = "\x0c" +CTRL_M = CR +CTRL_N = "\x0e" +CTRL_O = "\x0f" +CTRL_P = "\x10" +CTRL_Q = "\x11" +CTRL_R = "\x12" +CTRL_S = "\x13" +CTRL_T = "\x14" +CTRL_U = "\x15" +CTRL_V = "\x16" +CTRL_W = "\x17" +CTRL_X = "\x18" +CTRL_Y = "\x19" +CTRL_Z = "\x1a" + +# Windows uses scan codes for extended characters. This dictionary +# translates the second half of the scan codes of special Keys +# into the corresponding variable used by readchar. +# +# for windows scan codes see: +# https://msdn.microsoft.com/en-us/library/aa299374 +# or +# https://www.freepascal.org/docs-html/rtl/keyboard/kbdscancode.html + +# cursors +UP = "\x00\x48" +DOWN = "\x00\x50" +LEFT = "\x00\x4b" +RIGHT = "\x00\x4d" + +# other +ESC_2 = "\x00\x01" +ENTER_2 = "\x00\x1c" +F1 = "\x00\x3b" +F2 = "\x00\x3c" +F3 = "\x00\x3d" +F4 = "\x00\x3e" +F5 = "\x00\x3f" +F6 = "\x00\x40" +F7 = "\x00\x41" +F8 = "\x00\x42" +F9 = "\x00\x43" +F10 = "\x00\x44" +F11 = "\x00\x85" # only in second source +F12 = "\x00\x86" # only in second source + +# don't have table entries for... +# ALT_[A-Z] +# CTRL_ALT_A, # Ctrl-Alt-A, etc. +# CTRL_ALT_SUPR, +# CTRL-F1 + +PAGE_UP = "\x00\x49" +PAGE_DOWN = "\x00\x51" +HOME = "\x00\x47" +END = "\x00\x4f" + +INSERT = "\x00\x52" +SUPR = "\x00\x53" +DELETE = SUPR diff --git a/readchar/read_linux.py b/readchar/read_linux.py new file mode 100644 index 0000000..fa6624b --- /dev/null +++ b/readchar/read_linux.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +import sys +import termios +import tty +import select + + +# idea from: +# https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/ +# Thanks to REPOLINUX +def kbhit(): + return sys.stdin in select.select([sys.stdin], [], [], 0)[0] + + +# Initially taken from: +# http://code.activestate.com/recipes/134892/ +# Thanks to Danny Yoo +def readchar(blocking=False): + if not blocking and not kbhit(): + return None + fd = sys.stdin.fileno() + old_settings = termios.tcgetattr(fd) + try: + tty.setraw(sys.stdin.fileno()) + ch = sys.stdin.read(1) + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + return ch + + +def readkey(): + """Get a single character on Linux. If an escaped key is pressed, the + following characters are read as well (see key_linux.py).""" + + c1 = readchar(blocking=True) + + if c1 == "\x03": + raise KeyboardInterrupt + + if c1 != "\x1B": + return c1 + + c2 = readchar(blocking=True) + if c2 not in "\x4F\x5B": + return c1 + c2 + + c3 = readchar(blocking=True) + if c3 not in "\x31\x32\x33\x35\x36": + return c1 + c2 + c3 + + c4 = readchar(blocking=True) + if c4 not in "\x30\x31\x33\x34\x35\x37\x38\x39": + return c1 + c2 + c3 + c4 + + c5 = readchar(blocking=True) + return c1 + c2 + c3 + c4 + c5 diff --git a/readchar/read_windows.py b/readchar/read_windows.py new file mode 100644 index 0000000..b9aa6b1 --- /dev/null +++ b/readchar/read_windows.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# This file is based on this gist: +# http://code.activestate.com/recipes/134892/ +# So real authors are DannyYoo and company. + +import msvcrt + + +def readchar(blocking=False): + """reads a single character from the input stream. Retruns None if none is avalable. + If blocking=True the function waits for the next character.""" + + if blocking or msvcrt.kbhit(): + # manual byte decoding because some bytes in windows are not utf-8 encodable. + return chr(int.from_bytes(msvcrt.getch(), "big")) + else: + return None + + +def readkey(): + """Get a single character on Windows. If an extended key is pressed, the + Windows scan code is translated into a the unicode sequences readchar + expects (see key_windows.py).""" + + ch = readchar(blocking=True) + + if ch == "\x03": + raise KeyboardInterrupt + + # if it is a normal character: + if ch not in "\x00\xe0": + return ch + + # if it is a scpeal key, read second half: + ch2 = readchar() + + return "\x00" + ch2 diff --git a/readchar/readchar.py b/readchar/readchar.py deleted file mode 100644 index 8aa352a..0000000 --- a/readchar/readchar.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# This file is based on this gist: -# http://code.activestate.com/recipes/134892/ -# So real authors are DannyYoo and company. -import sys - -if sys.platform.startswith("linux"): - from .readchar_linux import readchar -elif sys.platform == "darwin": - from .readchar_linux import readchar -elif sys.platform in ("win32", "cygwin"): - import msvcrt - - from . import key - from .readchar_windows import readchar -else: - raise NotImplementedError("The platform %s is not supported yet" % sys.platform) - - -if sys.platform in ("win32", "cygwin"): - # - # Windows uses scan codes for extended characters. The ordinal returned is - # 256 * the scan code. This dictionary translates scan codes to the - # unicode sequences expected by readkey. - # - # for windows scan codes see: - # https://msdn.microsoft.com/en-us/library/aa299374 - # or - # http://www.quadibloc.com/comp/scan.htm - xlate_dict = { - 13: key.ENTER, - 27: key.ESC, - 15104: key.F1, - 15360: key.F2, - 15616: key.F3, - 15872: key.F4, - 16128: key.F5, - 16384: key.F6, - 16640: key.F7, - 16896: key.F8, - 17152: key.F9, - 17408: key.F10, - 22272: key.F11, - 34528: key.F12, - 7680: key.ALT_A, - # don't have table entries for... - # CTRL_ALT_A, # Ctrl-Alt-A, etc. - # CTRL_ALT_SUPR, - # CTRL-F1 - 21216: key.INSERT, - 21472: key.SUPR, # key.py uses SUPR, not DELETE - 18912: key.PAGE_UP, - 20960: key.PAGE_DOWN, - 18400: key.HOME, - 20448: key.END, - 18432: key.UP, # 72 * 256 - 20480: key.DOWN, # 80 * 256 - 19200: key.LEFT, # 75 * 256 - 19712: key.RIGHT, # 77 * 256 - } - - def readkey(getchar_fn=None): - # Get a single character on Windows. if an extended key is pressed, the - # Windows scan code is translated into a the unicode sequences readchar - # expects (see key.py). - while True: - if msvcrt.kbhit(): - ch = msvcrt.getch() - a = ord(ch) - if a == 0 or a == 224: - b = ord(msvcrt.getch()) - x = a + (b * 256) - - try: - return xlate_dict[x] - except KeyError: - return None - return x - else: - return ch.decode() - -else: - - def readkey(getchar_fn=None): - getchar = getchar_fn or readchar - c1 = getchar() - if ord(c1) != 0x1B: - return c1 - c2 = getchar() - if ord(c2) != 0x5B: - return c1 + c2 - c3 = getchar() - if ord(c3) != 0x33: - return c1 + c2 + c3 - c4 = getchar() - return c1 + c2 + c3 + c4 diff --git a/readchar/readchar_linux.py b/readchar/readchar_linux.py deleted file mode 100644 index 6bcb4e2..0000000 --- a/readchar/readchar_linux.py +++ /dev/null @@ -1,18 +0,0 @@ -# -*- coding: utf-8 -*- -# Initially taken from: -# http://code.activestate.com/recipes/134892/ -# Thanks to Danny Yoo -import sys -import termios -import tty - - -def readchar(): - fd = sys.stdin.fileno() - old_settings = termios.tcgetattr(fd) - try: - tty.setraw(sys.stdin.fileno()) - ch = sys.stdin.read(1) - finally: - termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) - return ch diff --git a/readchar/readchar_windows.py b/readchar/readchar_windows.py deleted file mode 100644 index 3afb4f8..0000000 --- a/readchar/readchar_windows.py +++ /dev/null @@ -1,27 +0,0 @@ -# -*- coding: utf-8 -*- -# Initially taken from: -# http://code.activestate.com/recipes/134892/#c9 -# Thanks to Stephen Chappell -import msvcrt -import sys - -win_encoding = "mbcs" - - -XE0_OR_00 = "\x00\xe0" - - -def readchar(blocking=False): - "Get a single character on Windows." - - while msvcrt.kbhit(): - msvcrt.getch() - ch = msvcrt.getch() - # print('ch={}, type(ch)={}'.format(ch, type(ch))) - # while ch.decode(win_encoding) in unicode('\x00\xe0', win_encoding): - while ch.decode(win_encoding) in XE0_OR_00: - # print('found x00 or xe0') - msvcrt.getch() - ch = msvcrt.getch() - - return ch if sys.version_info.major > 2 else ch.decode(encoding=win_encoding) diff --git a/requirements-test.txt b/requirements-test.txt index 462fa01..f6320d3 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -1,4 +1,3 @@ flake8 pytest pytest-cov - diff --git a/setup.cfg b/setup.cfg index c59270b..cea3297 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,7 +1,14 @@ [tool:pytest] -norecursedirs = .git venv build dist *egg -addopts = -rfEsxwX --cov readchar +testpaths = tests +addopts = -r fEsxwX -s --cov=readchar -[flake8] -exclude = **/.*,venv/**,.eggs/** +[coverage:run] +omit = */tests* +[flake8] +exclude = __pycache__,.eggs,.git,.pytest_cache,venv,*.egg +show-source = true +statistics = true +count = true +max-complexity = 12 +max-line-length = 88 diff --git a/setup.py b/setup.py index c5b46b4..2ca40eb 100644 --- a/setup.py +++ b/setup.py @@ -53,15 +53,11 @@ def run_tests(self): "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", + "Programming Language :: Python :: 3.10", "Topic :: Software Development", "Topic :: Software Development :: User Interfaces", ], diff --git a/test.py b/test.py deleted file mode 100644 index d78b18f..0000000 --- a/test.py +++ /dev/null @@ -1,39 +0,0 @@ -import readchar.key -import readchar.readchar - -decode_dict = { - readchar.key.ESC: "ESC", - readchar.key.UP: "UP", - readchar.key.DOWN: "DOWN", - readchar.key.LEFT: "LEFT", - readchar.key.RIGHT: "RIGHT", - readchar.key.PAGE_UP: "PAGE_UP", - readchar.key.PAGE_DOWN: "PAGE_DOWN", - readchar.key.HOME: "HOME", - readchar.key.END: "END", - readchar.key.INSERT: "INSERT", - readchar.key.SUPR: "DELETE", - readchar.key.F1: "F1", - readchar.key.F2: "F2", - readchar.key.F3: "F3", - readchar.key.F4: "F4", - readchar.key.F5: "F5", - readchar.key.F6: "F6", - readchar.key.F7: "F7", - readchar.key.F8: "F8", - readchar.key.F9: "F9", - readchar.key.F10: "F10", - readchar.key.F12: "F12", - readchar.key.ALT_A: "ALT_A", -} - -while True: - c = readchar.readkey() - - if c in decode_dict: - print("got {}".format(decode_dict[c])) - else: - print(c) - - if c == "d": - break diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/acceptance/__init__.py b/tests/acceptance/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/linux/conftest.py b/tests/linux/conftest.py new file mode 100644 index 0000000..54fa5df --- /dev/null +++ b/tests/linux/conftest.py @@ -0,0 +1,50 @@ +import pytest +import sys + +if sys.platform.startswith("linux") or sys.platform in ("darwin"): + import termios + import tty + import readchar.read_linux as read_linux + + +# ignore all tests in this folder if not on linux +def pytest_ignore_collect(path, config): + if not (sys.platform.startswith("linux") or sys.platform in ("darwin")): + return True + + +@pytest.fixture +def patched_stdin(): + class mocked_stdin: + buffer = [] + + def push(self, string): + for c in string: + self.buffer.append(c) + + def read(self, n): + string = "" + for i in range(n): + string += self.buffer.pop(0) + return string + + def mock_tcgetattr(fd): + return None + + def mock_tcsetattr(fd, TCSADRAIN, old_settings): + return None + + def mock_setraw(fd): + return None + + def mock_kbhit(): + return True + + mock = mocked_stdin() + with pytest.MonkeyPatch.context() as mp: + mp.setattr(sys.stdin, "read", mock.read) + mp.setattr(termios, "tcgetattr", mock_tcgetattr) + mp.setattr(termios, "tcsetattr", mock_tcsetattr) + mp.setattr(tty, "setraw", mock_setraw) + mp.setattr(read_linux, "kbhit", mock_kbhit) + yield mock diff --git a/tests/linux/test_keys.py b/tests/linux/test_keys.py new file mode 100644 index 0000000..dd3e212 --- /dev/null +++ b/tests/linux/test_keys.py @@ -0,0 +1,17 @@ +from readchar import key + + +def test_character_length_1(): + assert 1 == len(key.CTRL_A) + + +def test_character_length_2(): + assert 2 == len(key.ALT_A) + + +def test_character_length_3(): + assert 3 == len(key.UP) + + +def test_character_length_4(): + assert 4 == len(key.CTRL_ALT_SUPR) diff --git a/tests/linux/test_readchar.py b/tests/linux/test_readchar.py new file mode 100644 index 0000000..75cf5cd --- /dev/null +++ b/tests/linux/test_readchar.py @@ -0,0 +1,26 @@ +import pytest +from string import printable +from readchar import readchar, key + + +@pytest.mark.parametrize("c", printable) +def test_printableCharacters(patched_stdin, c): + patched_stdin.push(c) + assert c == readchar(blocking=True) + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + ("\x0a", key.LF), + ("\x0a", key.ENTER), + ("\x0d", key.CR), + ("\x7F", key.BACKSPACE), + ("\x20", key.SPACE), + ("\x1b", key.ESC), + ("\x09", key.TAB), + ], +) +def test_controlCharacters(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readchar() diff --git a/tests/linux/test_readkey.py b/tests/linux/test_readkey.py new file mode 100644 index 0000000..203f467 --- /dev/null +++ b/tests/linux/test_readkey.py @@ -0,0 +1,60 @@ +import pytest +from readchar import readkey, key + + +def test_KeyboardInterrupt(patched_stdin): + patched_stdin.push("\x03") + with pytest.raises(KeyboardInterrupt): + readkey() + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + ("\x1b\x5b\x41", key.UP), + ("\x1b\x5b\x42", key.DOWN), + ("\x1b\x5b\x44", key.LEFT), + ("\x1b\x5b\x43", key.RIGHT), + ], +) +def test_arrowKeys(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readkey() + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + ("\x1b\x5b\x32\x7e", key.INSERT), + ("\x1b\x5b\x33\x7e", key.SUPR), + ("\x1b\x5b\x48", key.HOME), + ("\x1b\x5b\x46", key.END), + ("\x1b\x5b\x35\x7e", key.PAGE_UP), + ("\x1b\x5b\x36\x7e", key.PAGE_DOWN), + ], +) +def test_specialKeys(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readkey() + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + (key.F1, "\x1b\x4f\x50"), + (key.F2, "\x1b\x4f\x51"), + (key.F3, "\x1b\x4f\x52"), + (key.F4, "\x1b\x4f\x53"), + (key.F5, "\x1b\x5b\x31\x35\x7e"), + (key.F6, "\x1b\x5b\x31\x37\x7e"), + (key.F7, "\x1b\x5b\x31\x38\x7e"), + (key.F8, "\x1b\x5b\x31\x39\x7e"), + (key.F9, "\x1b\x5b\x32\x30\x7e"), + (key.F10, "\x1b\x5b\x32\x31\x7e"), + (key.F11, "\x1b\x5b\x32\x33\x7e"), + (key.F12, "\x1b\x5b\x32\x34\x7e"), + ], +) +def test_functionKeys(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readkey() diff --git a/tests/manual-test.py b/tests/manual-test.py new file mode 100644 index 0000000..45eaaf9 --- /dev/null +++ b/tests/manual-test.py @@ -0,0 +1,17 @@ +from readchar import key, readkey + + +# construct an inverted code -> key-name mapping +# we need to revese the items so that aliases won't overrive the original name later on +known_keys = {v: k for k, v in reversed(vars(key).items()) if not k.startswith("__")} + + +while True: + data = readkey() + + if data in known_keys: + print(f"got {known_keys[data]}", end="") + else: + print(data, end="") + + print(f' - \\x{"".join([f"{ord(c):02x}" for c in data])}') diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/unit/test_key.py b/tests/unit/test_key.py deleted file mode 100644 index ef605f3..0000000 --- a/tests/unit/test_key.py +++ /dev/null @@ -1,17 +0,0 @@ -import unittest - -from readchar import key - - -class KeyTest(unittest.TestCase): - def test_character_length_1(self): - self.assertEqual(1, len(key.CTRL_A)) - - def test_character_length_2(self): - self.assertEqual(2, len(key.ALT_A)) - - def test_character_length_3(self): - self.assertEqual(3, len(key.UP)) - - def test_character_length_4(self): - self.assertEqual(4, len(key.CTRL_ALT_SUPR)) diff --git a/tests/unit/test_readkey.py b/tests/unit/test_readkey.py deleted file mode 100644 index 5f52727..0000000 --- a/tests/unit/test_readkey.py +++ /dev/null @@ -1,54 +0,0 @@ -import unittest - -from readchar import readkey - - -def readchar_fn_factory(stream): - - v = [x for x in stream] - - def inner(): - return v.pop(0) - - return inner - - -class ReadKeyTest(unittest.TestCase): - def test_basic_character(self): - getchar_fn = readchar_fn_factory("a") - - result = readkey(getchar_fn) - - self.assertEqual("a", result) - - def test_string_instead_of_char(self): - char = "a" - getchar_fn = readchar_fn_factory(char + "bcde") - - result = readkey(getchar_fn) - - self.assertEqual(char, result) - - def test_special_combo_character(self): - char = "\x1b\x01" - getchar_fn = readchar_fn_factory(char + "foo") - - result = readkey(getchar_fn) - - self.assertEqual(char, result) - - def test_special_key(self): - char = "\x1b\x5b\x41" - getchar_fn = readchar_fn_factory(char + "foo") - - result = readkey(getchar_fn) - - self.assertEqual(char, result) - - def test_special_key_combo(self): - char = "\x1b\x5b\x33\x5e" - getchar_fn = readchar_fn_factory(char + "foo") - - result = readkey(getchar_fn) - - self.assertEqual(char, result) diff --git a/tests/windows/conftest.py b/tests/windows/conftest.py new file mode 100644 index 0000000..94299d4 --- /dev/null +++ b/tests/windows/conftest.py @@ -0,0 +1,22 @@ +import pytest +import sys + + +if sys.platform in ("win32", "cygwin"): + import msvcrt + + +# ignore all tests in this folder if not on windows +def pytest_ignore_collect(path, config): + if sys.platform not in ("win32", "cygwin"): + return True + + +@pytest.fixture +def patched_stdin(): + class mocked_stdin: + def push(self, string): + for c in string: + msvcrt.ungetch(ord(c).to_bytes(1, "big")) + + return mocked_stdin() diff --git a/tests/windows/test_keys.py b/tests/windows/test_keys.py new file mode 100644 index 0000000..55a8d4a --- /dev/null +++ b/tests/windows/test_keys.py @@ -0,0 +1,51 @@ +import pytest +from readchar import key as keys + + +defaultKeys = ["LF", "CR", "ENTER", "BACKSPACE", "SPACE", "ESC", "TAB"] + + +@pytest.mark.parametrize("key", defaultKeys) +def test_defaultKeysExists(key): + assert key in keys.__dict__ + + +@pytest.mark.parametrize("key", defaultKeys) +def test_defaultKeysLength(key): + assert 1 == len(keys.__dict__[key]) + + +specialKeys = [ + "INSERT", + "SUPR", + "PAGE_UP", + "PAGE_DOWN", + "HOME", + "END", + "UP", + "DOWN", + "LEFT", + "RIGHT", + "F1", + "F2", + "F3", + "F4", + "F5", + "F6", + "F7", + "F8", + "F9", + "F10", + "F11", + "F12", +] + + +@pytest.mark.parametrize("key", specialKeys) +def test_specialKeysExists(key): + assert key in keys.__dict__ + + +@pytest.mark.parametrize("key", specialKeys) +def test_specialKeysLength(key): + assert 2 == len(keys.__dict__[key]) diff --git a/tests/windows/test_readchar.py b/tests/windows/test_readchar.py new file mode 100644 index 0000000..184c91f --- /dev/null +++ b/tests/windows/test_readchar.py @@ -0,0 +1,26 @@ +import pytest +from string import printable +from readchar import readchar, key + + +@pytest.mark.parametrize("c", printable) +def test_printableCharacters(patched_stdin, c): + patched_stdin.push(c) + assert c == readchar() + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + ("\n", key.LF), + ("\r", key.ENTER), + ("\r", key.CR), + ("\x08", key.BACKSPACE), + ("\x20", key.SPACE), + ("\x1b", key.ESC), + ("\t", key.TAB), + ], +) +def test_controlCharacters(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readchar() diff --git a/tests/windows/test_readkey.py b/tests/windows/test_readkey.py new file mode 100644 index 0000000..c65b9e7 --- /dev/null +++ b/tests/windows/test_readkey.py @@ -0,0 +1,66 @@ +import pytest +from readchar import readkey, key + + +def test_KeyboardInterrupt(patched_stdin): + patched_stdin.push("\x03") + with pytest.raises(KeyboardInterrupt): + readkey() + + +# for windows scan codes see: +# https://msdn.microsoft.com/en-us/library/aa299374 +# or +# https://www.freepascal.org/docs-html/rtl/keyboard/kbdscancode.html + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + ("\x00\x48", key.UP), + ("\x00\x50", key.DOWN), + ("\x00\x4b", key.LEFT), + ("\x00\x4d", key.RIGHT), + ], +) +def test_arrowKeys(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readkey() + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + ("\x00\x52", key.INSERT), + ("\x00\x53", key.SUPR), + ("\x00\x47", key.HOME), + ("\x00\x4f", key.END), + ("\x00\x49", key.PAGE_UP), + ("\x00\x51", key.PAGE_DOWN), + ], +) +def test_specialKeys(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readkey() + + +@pytest.mark.parametrize( + ["seq", "key"], + [ + ("\x00\x3b", key.F1), + ("\x00\x3c", key.F2), + ("\x00\x3d", key.F3), + ("\x00\x3e", key.F4), + ("\x00\x3f", key.F5), + ("\x00\x40", key.F6), + ("\x00\x41", key.F7), + ("\x00\x42", key.F8), + ("\x00\x43", key.F9), + ("\x00\x44", key.F10), + ("\x00\x85", key.F11), + ("\x00\x86", key.F12), + ], +) +def test_functionKeys(seq, key, patched_stdin): + patched_stdin.push(seq) + assert key == readkey()