Advertisement
Guest User

Untitled

a guest
Feb 24th, 2016
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.87 KB | None | 0 0
  1. diff --git a/.gitignore b/.gitignore
  2. index e2a7f94..b576114 100644
  3. --- a/.gitignore
  4. +++ b/.gitignore
  5. @@ -1,3 +1,2 @@
  6. **/__pycache__/**
  7. __pycache__/**
  8. -*.pyc
  9. \ No newline at end of file
  10. diff --git a/.gitmodules b/.gitmodules
  11. deleted file mode 100644
  12. index 45125a4..0000000
  13. --- a/.gitmodules
  14. +++ /dev/null
  15. @@ -1,3 +0,0 @@
  16. -[submodule "colorama"]
  17. - path = colorama
  18. - url = https://github.com/tartley/colorama
  19. diff --git a/Makefile b/Makefile
  20. deleted file mode 100644
  21. index 8f04b8b..0000000
  22. --- a/Makefile
  23. +++ /dev/null
  24. @@ -1,7 +0,0 @@
  25. -test:
  26. - python3 test/tests.py
  27. -.PHONY: test
  28. -
  29. -clean:
  30. - rm -rf *.pyc */*.pyc __pycache__/* */__pycache__/*
  31. -.PHONY: clean
  32. diff --git a/README.md b/README.md
  33. index a9c2c64..17acf17 100644
  34. --- a/README.md
  35. +++ b/README.md
  36. @@ -1 +1,41 @@
  37. -# PMLR: poor man's (pure python) libreadline
  38. \ No newline at end of file
  39. +# input_constrain
  40. +
  41. +#### simple little module for getting very specific user inputs.
  42. +
  43. +---
  44. +
  45. +## module overview
  46. +
  47. +* `read_single_keypress() -> string` — cross-platform function that gets exactly one keypress
  48. +
  49. +* `thismany(count: int = -1) -> string` — get exactly `count` characters from stdin. if count is `-1`, then `sys.maxsize` chars will be read.
  50. +
  51. +* `until(chars: string || list, count: int = -1) -> string` — get characters from stdin until `char` is read, or until `count` chars have been read. if `count` is `-1`, `sys.maxsize` chars will be read.
  52. +
  53. +* `until_not(chars: string || list, count: int = -1) -> string` — get characters from stdin until any of `chars` is not read. if `count` is `-1`, then `sys.maxsize` chars will be read.
  54. +
  55. +* `pretty_press() -> string` — read a byte from stdin, and send it through the same processing as the other functions do — write it, if it's a backspace, then backspace, etc
  56. +
  57. +## other parts of the module
  58. +
  59. +* class `_Getch`: determines system platform and calls one of `_GetchUnix` or `_GetchWindows` appropriately
  60. +
  61. +* class `_GetchUnix`: get a raw character from stdin, on any *nx box
  62. +
  63. +* class `_GetchWindows`: get a raw character from stdin, on any Windows box
  64. +
  65. +* function `nbsp`: do stuff accordingly for certain chars of input; handles backspace, etc
  66. +
  67. +* function `parsenum`: return a number, or `sys.maxsize` if number is `-1`
  68. +
  69. +## examples overview
  70. +
  71. +* `_until_demo() -> None` — small demo of `until()`
  72. +
  73. +* `_thismany_demo() -> None` — small demo of `thismany()`
  74. +
  75. +* `_can_you_vote() -> None` — small demo of `until_not_multi()`
  76. +
  77. +* `_forth_syntax_test() -> None` — small practical demo of `until()`
  78. +
  79. +Thanks to [Dannno](http://codereview.stackexchange.com/users/47529/dannnno) and [his post](http://codereview.stackexchange.com/a/118726/87163) for making this module cool.
  80. \ No newline at end of file
  81. diff --git a/__init__.py b/__init__.py
  82. new file mode 100644
  83. index 0000000..e69de29
  84. diff --git a/colorama b/colorama
  85. deleted file mode 160000
  86. index 1244a00..0000000
  87. --- a/colorama
  88. +++ /dev/null
  89. @@ -1 +0,0 @@
  90. -Subproject commit 1244a00ae1accfeca3b4b1a85a3b718a920dd6bd
  91. diff --git a/examples.py b/examples.py
  92. new file mode 100755
  93. index 0000000..5ad3a0e
  94. --- /dev/null
  95. +++ b/examples.py
  96. @@ -0,0 +1,64 @@
  97. +#!/usr/bin/env python3
  98. +
  99. +import sys
  100. +import input_constrain
  101. +
  102. +def _until_demo() -> None:
  103. + """demonstrate the until function"""
  104. + print("get until what?")
  105. + char = input_constrain._read_keypress()
  106. + input_constrain._writer(char + "\n")
  107. + y = input_constrain.until(char)
  108. + print("\n" + y)
  109. +
  110. +
  111. +def _thismany_demo() -> None:
  112. + """demonstrate the thismany function"""
  113. + print("get how many chars?")
  114. + kps = input()
  115. + try:
  116. + kps = int(kps)
  117. + except ValueError:
  118. + print("not a number, sorry")
  119. + return
  120. + print("getting", str(kps))
  121. + y = input_constrain.thismany(kps)
  122. + print("\n" + y)
  123. +
  124. +
  125. +def _can_you_vote() -> None:
  126. + """a practical example:
  127. + test if a user can vote based purely on keypresses"""
  128. + input_constrain._writer("can you vote? age : ")
  129. + x = int("0" + until_not("0123456789"))
  130. + if not x:
  131. + print("\nsorry, age can only consist of digits.")
  132. + return
  133. + print(
  134. + "your age is", x, "\nYou can vote!"
  135. + if x >= 18
  136. + else "Sorry! you can't vote"
  137. + )
  138. +
  139. +
  140. +def _forth_syntax_test() -> None:
  141. + """
  142. + in the programming language Forth,
  143. + `function` definitons start at the beginning of a line with a `:` colon
  144. + and go until the next semicolon.
  145. +
  146. + this is an example of how this module can be used
  147. + in a Forth REPL to compile statements specially;
  148. + it's implemented in catb0t/microcat as well.
  149. + """
  150. + input_constrain._writer("demo FORTH repl \n> ")
  151. + firstchar = input_constrain._read_keypress()
  152. + input_constrain._writer(firstchar)
  153. + if firstchar != ":":
  154. + return print("first char wasn't ':'")
  155. + defn = firstchar + input_constrain.until(";") + ";"
  156. + input_constrain._writer("\nrepl got:\n" + defn + "\n")
  157. +
  158. +
  159. +if __name__ == "__main__":
  160. + _forth_syntax_test()
  161. diff --git a/examples/examples.py b/examples/examples.py
  162. deleted file mode 100755
  163. index c899f9e..0000000
  164. --- a/examples/examples.py
  165. +++ /dev/null
  166. @@ -1,81 +0,0 @@
  167. -#!/usr/bin/env python3
  168. -
  169. -import sys
  170. -import string
  171. -import pmlr
  172. -
  173. -
  174. -def _until_demo():
  175. - """
  176. - demonstrate the until function
  177. - """
  178. -
  179. - print("get until what?")
  180. - char = pmlr._read_keypress()
  181. - pmlr._writer(char + "\n")
  182. - y = pmlr.until(char)
  183. - print("\n" + y)
  184. -
  185. -
  186. -def _thismany_demo():
  187. - """
  188. - demonstrate the thismany function
  189. - """
  190. -
  191. - print("get how many chars?")
  192. - kps = input()
  193. - try:
  194. - kps = int(kps)
  195. - except ValueError:
  196. - print("not a number, sorry")
  197. - return
  198. - print("getting", str(kps))
  199. - y = pmlr.thismany(kps)
  200. - print("\n" + y)
  201. -
  202. -
  203. -def _can_you_vote():
  204. - """
  205. - a practical example:
  206. - test if a user can vote based purely on keypresses
  207. - """
  208. -
  209. - pmlr._writer("can you vote? age : ")
  210. - x = int("0" + pmlr.ignore_not("0123456789", "0123456789", end_cond=True, count=2))
  211. - if not x:
  212. - print("\nsorry, age can only consist of digits.")
  213. - return
  214. - print(
  215. - "\nyour age is", x, "\nYou can vote!"
  216. - if x >= 18
  217. - else "Sorry! you can't vote"
  218. - )
  219. -
  220. -
  221. -def _forth_syntax_test():
  222. - """
  223. - in the programming language Forth,
  224. - `function` definitons start at the beginning of a line with a `:` colon
  225. - and go until the next semicolon.
  226. -
  227. - this is an example of how this module can be used
  228. - in a Forth REPL to compile statements specially;
  229. - it's implemented in catb0t/microcat as well.
  230. - """
  231. -
  232. - pmlr._writer("demo FORTH repl \n> ")
  233. - firstchar = pmlr._read_keypress()
  234. - pmlr._writer(firstchar)
  235. - if firstchar != ":":
  236. - print("\nreturned because first char wasn't ':'")
  237. - return
  238. - defn = firstchar + pmlr.until(";") + ";"
  239. - pmlr._writer("\nrepl got:\n" + defn + "\n")
  240. -
  241. -
  242. -def _get_paragraphs():
  243. - from string import printable as ALLOWED_CHARS
  244. - print("\nPress CTRL-C or CTRL-D to stop reading.")
  245. - textwriterCommand = pmlr.until_not(ALLOWED_CHARS, count=500, raw=True)
  246. - pmlr._writer("\n\n")
  247. - return pmlr._writer("you typed:" + textwriterCommand)
  248. diff --git a/input_constrain.py b/input_constrain.py
  249. new file mode 100755
  250. index 0000000..7dcb18c
  251. --- /dev/null
  252. +++ b/input_constrain.py
  253. @@ -0,0 +1,113 @@
  254. +#!/usr/bin/env python3
  255. +
  256. +import sys
  257. +from platform import system
  258. +
  259. +if system == "Windows":
  260. + import msvcrt
  261. +
  262. + def _Getch():
  263. + return msvcrt.getch()
  264. +
  265. +else:
  266. + import tty, termios
  267. +
  268. + def _Getch():
  269. + fd = sys.stdin.fileno()
  270. + old_settings = termios.tcgetattr(fd)
  271. + try:
  272. + tty.setraw(sys.stdin.fileno())
  273. + ch = sys.stdin.read(1)
  274. + finally:
  275. + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
  276. + return ch
  277. +
  278. +
  279. +def parsenum(num):
  280. + return sys.maxsize if 0 > num else num
  281. +
  282. +CHAR_INT = chr(3)
  283. +CHAR_EOF = chr(4)
  284. +CHAR_BKS = chr(8)
  285. +CHAR_ESC = chr(27)
  286. +CHAR_SPC = chr(32)
  287. +CHAR_DEL = chr(127)
  288. +
  289. +
  290. +def _read_keypress():
  291. + """interface for _Getch that interprets backspace and DEL properly"""
  292. + c = _Getch()
  293. +
  294. + if c in (CHAR_BKS, CHAR_DEL, CHAR_ESC):
  295. + sys.stdout.write(CHAR_BKS)
  296. + sys.stdout.write(CHAR_SPC) # hacky? indeed. does it *work*? hell yeah!
  297. + sys.stdout.write(CHAR_BKS)
  298. +
  299. + elif c == CHAR_INT: raise KeyboardInterrupt
  300. + elif c == CHAR_EOF: raise EOFError
  301. +
  302. + return c
  303. +
  304. +
  305. +def _nbsp(x, y):
  306. + """append x to y as long as x is not DEL or backspace"""
  307. + if x in (CHAR_DEL, CHAR_BKS):
  308. + try:
  309. + y.pop()
  310. + except IndexError:
  311. + pass
  312. + return y
  313. + y.append(x)
  314. + return y
  315. +
  316. +
  317. +def _writer(i):
  318. + sys.stdout.write(i)
  319. + sys.stdout.flush()
  320. +
  321. +
  322. +def pretty_press() -> str:
  323. + """literally just read any fancy char from stdin let caller do whatever"""
  324. + i = _read_keypress()
  325. + _writer(i)
  326. + return _nbsp(i, y)
  327. +
  328. +
  329. +def thismany(count=-1) -> str:
  330. + """get exactly count chars of stdin"""
  331. + y = []
  332. + count = parsenum(count)
  333. + while len(y) <= count:
  334. + i = _read_keypress()
  335. + _writer(i)
  336. + y = _nbsp(i, y)
  337. + return "".join(y)
  338. +
  339. +
  340. +def _until_condition(chars, condition, count) -> str:
  341. + y = []
  342. + while len(y) <= count:
  343. + i = _read_keypress()
  344. + _writer(i)
  345. + if condition(i, chars):
  346. + break
  347. + y = _nbsp(i, y)
  348. + return "".join(y)
  349. +
  350. +
  351. +def until(chars, count=-1) -> str:
  352. + """get chars of stdin until any of chars is read,
  353. + or until count chars have been read, whichever comes first"""
  354. +
  355. + return _until_condition(
  356. + chars, lambda i, chars: i in chars, parsenum(count)
  357. + )
  358. +
  359. +
  360. +def until_not(chars, count=-1) -> str:
  361. + """read stdin until any of chars stop being read,
  362. + or until count chars have been read; whichever comes first"""
  363. +
  364. + return _until_condition(
  365. + chars, lambda i, chars: i not in chars, parsenum(count)
  366. + )
  367. diff --git a/pmlr/__init__.py b/pmlr/__init__.py
  368. deleted file mode 100755
  369. index 7ec47e6..0000000
  370. --- a/pmlr/__init__.py
  371. +++ /dev/null
  372. @@ -1,341 +0,0 @@
  373. -#!/usr/bin/env python3
  374. -
  375. -import sys
  376. -import struct
  377. -from platform import system
  378. -SYSTEM = system().lower()
  379. -DEBUG = True
  380. -
  381. -class CHAR:
  382. - """essentially an enum, to avoid clouding the ns"""
  383. - NUL = chr(0)
  384. - INT = chr(3)
  385. - EOF = chr(4)
  386. - BEL = chr(7)
  387. - BKS = chr(8)
  388. - LFD = chr(10)
  389. - CRR = chr(13)
  390. - ESC = chr(27)
  391. - SPC = chr(32)
  392. - DEL = chr(127)
  393. -
  394. - CONDS = [
  395. - (lambda i, chars: i in chars),
  396. - (lambda i, chars: i not in chars),
  397. - (lambda *args, **kwargs: False),
  398. - ]
  399. -
  400. -
  401. -def init(TERM_BUFSIZE=4096):
  402. - """module initialiser: calls constructors so you don't have to
  403. - you must call this before other functions!"""
  404. - global reader
  405. - reader = read_class(TERMCTL_SPECIAL_BUFSIZE=TERM_BUFSIZE)
  406. -
  407. -
  408. -def checkinit(func, *args, **kwargs):
  409. -
  410. - def isdefined(*args, **kwargs):
  411. -
  412. - if "reader" not in globals().keys():
  413. - print("\n\tfatal: init() not called\n")
  414. - msg = "must call init() first, or call init() again before {}()".format(func.__name__)
  415. - raise TypeError(msg)
  416. -
  417. - return func(*args, **kwargs)
  418. -
  419. - return isdefined
  420. -
  421. -
  422. -class _nt_reader():
  423. -
  424. - def __init__(self, *args, **kwargs):
  425. - """reader on nt"""
  426. -
  427. - self.NAME = "NT"
  428. -
  429. - if SYSTEM != "windows":
  430. - util.writer("\n\there be dragons; ye COWER in the SHADOW of", self.NAME, "\n\n")
  431. -
  432. - self.msvcrt = __import__("msvcrt")
  433. - self.ctypes = __import__("ctypes")
  434. - try:
  435. - self.colorama = __import__("colorama")
  436. - self.colorama.init()
  437. - except (AttributeError, ImportError):
  438. - print(
  439. - """
  440. - you must install colorama to use this module on windows
  441. - do this by:
  442. - $ cd colorama
  443. - $ python setup.py install
  444. - """
  445. - )
  446. - exit(2)
  447. -
  448. -
  449. - def getch(self):
  450. - """use msvcrt to get a char"""
  451. - return self.msvcrt.getch()
  452. -
  453. - def drain_buf(self):
  454. - """while buffer, pseudo-nonblocking read bytes from buffer using msvcrt"""
  455. - y = []
  456. - while self.msvcrt.kbhit():
  457. - y.append(self.msvcrt.getch())
  458. - return "".join(y)
  459. -
  460. -
  461. -class _posix_reader():
  462. -
  463. - def __init__(self, TERMCTL_SPECIAL_BUFSIZE=4096):
  464. - """reader on posix"""
  465. -
  466. - self.NAME = "POSIX"
  467. -
  468. - if SYSTEM == "windows":
  469. - util.writer("\n\there be dragons; ye COWER in the SHADOW of", self.NAME, "\n\n")
  470. -
  471. - self.tty = __import__("tty")
  472. - self.termios = __import__("termios")
  473. - self.fcntl = __import__("fcntl")
  474. -
  475. - self.O_NONBLOCK = __import__("os").O_NONBLOCK
  476. -
  477. - self.TERM_BUFSIZE = TERMCTL_SPECIAL_BUFSIZE
  478. -
  479. - def getch(self):
  480. - """use old fashioned termios to getch"""
  481. - if sys.stdin.isatty(): # fixes "Inappropriate ioctl for device"
  482. - fd = sys.stdin.fileno()
  483. - old_settings = self.termios.tcgetattr(fd)
  484. - try:
  485. - self.tty.setraw(sys.stdin.fileno())
  486. - ch = sys.stdin.read(1)
  487. - finally:
  488. - self.termios.tcsetattr(fd, self.termios.TCSADRAIN, old_settings)
  489. - return ch
  490. - else:
  491. - return sys.stdin.read(1)
  492. -
  493. - def drain_buf(self):
  494. - """read TERM_BUFSIZE of waiting keypresses"""
  495. - if sys.stdin.isatty():
  496. - fd = sys.stdin.fileno()
  497. - fl = self.fcntl.fcntl(fd, self.fcntl.F_GETFL)
  498. - self.fcntl.fcntl(fd, self.fcntl.F_SETFL, fl | self.O_NONBLOCK)
  499. - try:
  500. - # if nothing is waiting on sys.stdin, then TypeError
  501. - # because "can't concat NoneType and str"
  502. - chars = sys.stdin.read(self.TERM_BUFSIZE)
  503. - except TypeError:
  504. - chars = ""
  505. - finally:
  506. - self.fcntl.fcntl(fd, self.fcntl.F_SETFL, fl) # restore settings
  507. - return chars
  508. - else:
  509. - return sys.stdin.read(self.TERM_BUFSIZE) # ???
  510. -
  511. -read_class = {
  512. - "windows": _nt_reader,
  513. -}.get(
  514. - SYSTEM,
  515. - _posix_reader # default
  516. -)
  517. -
  518. -
  519. -class util():
  520. - """utilities"""
  521. - def parsenum(num):
  522. - """sys.maxsize if num is negative"""
  523. - num = int(num)
  524. - return sys.maxsize if num < 0 else num
  525. -
  526. - def writer(*args):
  527. - """write a string to stdout and flush.
  528. - should be used by all stdout-writing"""
  529. - if not args:
  530. - raise TypeError("writer requires at least one argument")
  531. - if len(args) > 1:
  532. - args = " ".join(str(i) for i in args).strip(" ")
  533. - else:
  534. - args = "".join(str(i) for i in args)
  535. - sys.stdout.write(args)
  536. - sys.stdout.flush()
  537. -
  538. - def esc_filter(x, y):
  539. - """append x to y as long as x is not DEL or backspace or esc"""
  540. - if x in (CHAR.DEL, CHAR.BKS):
  541. - try:
  542. - y.pop()
  543. - except IndexError:
  544. - pass
  545. - return y
  546. -
  547. - y.append(x)
  548. - return y
  549. -
  550. -
  551. -@checkinit
  552. -def readkey(raw=False):
  553. - """interface for getch + drain_buf
  554. - if raw, behave like getch but with flushing for multibyte inputs"""
  555. - ch = reader.getch()
  556. - more = reader.drain_buf()
  557. -
  558. - if raw:
  559. - return ch + more
  560. -
  561. - # cooked
  562. -
  563. - if ch == CHAR.INT: raise KeyboardInterrupt
  564. - if ch == CHAR.EOF: raise EOFError
  565. -
  566. - if ch in (CHAR.BKS, CHAR.DEL):
  567. - util.writer(CHAR.BKS + CHAR.SPC + CHAR.BKS)
  568. - return CHAR.BKS
  569. -
  570. - elif ch in (CHAR.CRR, CHAR.LFD):
  571. - util.writer(CHAR.CRR if SYSTEM == "Windows" else "")
  572. - return CHAR.LFD
  573. -
  574. - elif ch == CHAR.ESC:
  575. - if more:
  576. - if more[0] == "[":
  577. - sp = more[1:]
  578. - if sp in ("D", "C"):
  579. - return "\033[" + sp
  580. -
  581. - elif sp == "3~":
  582. - return CHAR.SPC
  583. -
  584. - else:
  585. - return CHAR.BEL
  586. - else:
  587. - return CHAR.ESC + more
  588. -
  589. - ch += more
  590. - return ch
  591. -
  592. -
  593. -@checkinit
  594. -def raw_readkey():
  595. - """alias for readkey(raw=True)"""
  596. - return readkey(raw=True)
  597. -
  598. -
  599. -@checkinit
  600. -def pretty_press(raw=False):
  601. - """literally just read any fancy char from stdin let caller do whatever"""
  602. - y = []
  603. - i = readkey(raw=raw)
  604. - if (not raw) and (i not in (CHAR.BKS, CHAR.DEL, CHAR.ESC)):
  605. - util.writer(i)
  606. - return util.esc_filter(i, y)
  607. -
  608. -
  609. -@checkinit
  610. -def _do_condition(
  611. - end_chars,
  612. - end_condition,
  613. - count,
  614. - ignore_chars=(),
  615. - ignore_condition=CHAR.CONDS[True + 1], # always false
  616. - raw=False
  617. - ):
  618. - """singular interface to reading strings from readkey, to minimise duplication"""
  619. - y = []
  620. - count = util.parsenum(count)
  621. - while len(y) <= count:
  622. - i = readkey(raw=raw)
  623. - if end_condition(i, end_chars):
  624. - break
  625. - if not ignore_condition(i, ignore_chars):
  626. - if (not raw) and (i not in (CHAR.BKS, CHAR.DEL)):
  627. - util.writer(i)
  628. - y = util.esc_filter(i, y)
  629. - return "".join(y)
  630. -
  631. -
  632. -@checkinit
  633. -def thismany(count, raw=False):
  634. - """read exactly count chars"""
  635. -
  636. - return _do_condition(
  637. - "",
  638. - CHAR.CONDS[True + 1], # more than true == never expires :D
  639. - count,
  640. - raw=raw
  641. - )
  642. -
  643. -
  644. -@checkinit
  645. -def until(chars, invert=False, count=-1, raw=False):
  646. - """get chars of stdin until any of chars is read,
  647. - or until count chars have been read, whichever comes first"""
  648. -
  649. - return _do_condition(
  650. - chars,
  651. - CHAR.CONDS[invert],
  652. - count,
  653. - raw=raw
  654. - )
  655. -
  656. -
  657. -@checkinit
  658. -def until_not(chars, count=-1, raw=False):
  659. - """read stdin until any of chars stop being read,
  660. - or until count chars have been read; whichever comes first"""
  661. -
  662. - return until(
  663. - chars,
  664. - invert=True,
  665. - count=count,
  666. - raw=raw
  667. - )
  668. -
  669. -
  670. -@checkinit
  671. -def ignore(
  672. - ignore_these,
  673. - end_on,
  674. - end_cond=True,
  675. - count=-1,
  676. - raw=False,
  677. - invert=False
  678. - ):
  679. - """ignore_these keypresses, and stop reading at end_on or count,
  680. - whichever comes first"""
  681. -
  682. - return _do_condition(
  683. - end_on,
  684. - CHAR.CONDS[not end_cond],
  685. - count,
  686. - ignore_chars=ignore_these,
  687. - ignore_condition=CHAR.CONDS[invert],
  688. - raw=raw
  689. - )
  690. -
  691. -
  692. -@checkinit
  693. -def ignore_not(
  694. - ignore_these,
  695. - end_on,
  696. - end_cond=True,
  697. - count=-1,
  698. - raw=False
  699. - ):
  700. - """ignore everything that isn't these keypresses
  701. - and stop reading at end_on or count, whichever comes first"""
  702. -
  703. - return ignore(
  704. - ignore_these,
  705. - end_on,
  706. - end_cond=end_cond,
  707. - count=count,
  708. - raw=raw,
  709. - invert=True
  710. - )
  711. -
  712. -if DEBUG:
  713. - init()
  714. \ No newline at end of file
  715. diff --git a/pmlr/__main__.py b/pmlr/__main__.py
  716. deleted file mode 100644
  717. index 777c7d6..0000000
  718. --- a/pmlr/__main__.py
  719. +++ /dev/null
  720. @@ -1 +0,0 @@
  721. -from .pmlr import *
  722. \ No newline at end of file
  723. diff --git a/test/_tests_helper.py b/test/_tests_helper.py
  724. deleted file mode 100755
  725. index 57be079..0000000
  726. --- a/test/_tests_helper.py
  727. +++ /dev/null
  728. @@ -1,42 +0,0 @@
  729. -#!/usr/bin/env python3
  730. -from sys import argv as _argv
  731. -
  732. -from tests import pmlr as _ic
  733. -
  734. -_p = _ic.util.writer
  735. -
  736. -
  737. -def getch(*a):
  738. - _ic.init()
  739. - _p(ord(_ic.reader.getch()))
  740. -
  741. -
  742. -def readkey(*a):
  743. - _ic.init()
  744. - _p(ord(_ic.readkey()))
  745. -
  746. -
  747. -def raw_readkey(*a):
  748. - _ic.init()
  749. - _p(ord(_ic.raw_readkey()))
  750. -
  751. -
  752. -def writer(*a):
  753. - if a:
  754. - _p(*a)
  755. -
  756. -if __name__ == "__main__":
  757. - try:
  758. - _arg = _argv[1]
  759. - _rest = tuple(_argv[2:])
  760. - except IndexError:
  761. - _g = globals().copy()
  762. - _funcs = [
  763. - i for i in _g
  764. - if not list(_g.keys())[list(_g.keys())
  765. - .index(i)]
  766. - .startswith("_")
  767. - ]
  768. - print("names:\t" + "\n\t".join(i for i in _funcs))
  769. - else:
  770. - globals()[_arg](*_rest)
  771. diff --git a/test/tests.py b/test/tests.py
  772. deleted file mode 100755
  773. index 7d7aea7..0000000
  774. --- a/test/tests.py
  775. +++ /dev/null
  776. @@ -1,135 +0,0 @@
  777. -#!/usr/bin/env python3
  778. -import unittest
  779. -import subprocess as sp
  780. -from sys import executable as py, maxsize as MAXSIZE, version_info as VERINFO
  781. -from os import getcwd, path
  782. -
  783. -TESTMOD_INFO = ("pmlr", path.join(getcwd(), "..", "pmlr", "pmlr", "__main__.py"))
  784. -
  785. -TEST_HELP = path.join(getcwd(), "..", "pmlr", "test", "_tests_helper.py")
  786. -
  787. -
  788. -if VERINFO.major == 2:
  789. - import imp
  790. - pmlr = imp.load_source(*TESTMOD_INFO)
  791. -
  792. -elif VERINFO.major == 3:
  793. - if VERINFO.minor < 5:
  794. - from importlib.machinery import SourceFileLoader
  795. - pmlr = SourceFileLoader(*TESTMOD_INFO).load_module()
  796. -
  797. - elif VERINFO.minor >= 5:
  798. - import importlib.util
  799. - spec = importlib.util.spec_from_file_location(*TESTMOD_INFO)
  800. - pmlr = importlib.util.module_from_spec(spec)
  801. - spec.loader.exec_module(pmlr)
  802. -else:
  803. - raise NotImplementedError("unsupported Python version: ", VERINFO.major)
  804. -
  805. -
  806. -class TestUtilsNoIO(unittest.TestCase):
  807. - """io-less util tests"""
  808. -
  809. - def test_parsenum(self):
  810. - """test parsenum"""
  811. - nums = (-MAXSIZE, -122, -1, 0, 8, 88, 888880, MAXSIZE)
  812. - for elem in nums:
  813. - result = pmlr.util.parsenum(elem)
  814. - expect = MAXSIZE if elem < 0 else elem
  815. - self.assertEqual(result, expect)
  816. -
  817. - def test_parsenum_complex(self):
  818. - """test parsenum failure"""
  819. - with self.assertRaises(TypeError):
  820. - pmlr.util.parsenum(8j)
  821. -
  822. -
  823. -class TestKPressIO(unittest.TestCase):
  824. -
  825. - def setUp(self):
  826. - pmlr.init()
  827. -
  828. - def test_getch(self):
  829. - """test getch (patience)"""
  830. - for ch in range(128):
  831. - p = sp.Popen(
  832. - [py, TEST_HELP, "getch"],
  833. - stdin=sp.PIPE,
  834. - stdout=sp.PIPE,
  835. - )
  836. - out, _ = p.communicate(input=bytes(chr(ch), "utf-8"))
  837. - self.assertEqual(
  838. - out, bytes('{}'.format(ch), "utf-8") # ewww
  839. - )
  840. -
  841. - def test_read_keypress(self):
  842. - """test readkey (patience)"""
  843. - specials = { # special cases
  844. - 3: "KeyboardInterrupt",
  845. - 4: "EOFError",
  846. - 8: b'\x08\x088',
  847. - 13: b'10',
  848. - 27: b'\x08\x0827',
  849. - 127: '',
  850. - }
  851. - for ch in range(128):
  852. - p = sp.Popen(
  853. - [py, TEST_HELP, "readkey"],
  854. - stdin=sp.PIPE,
  855. - stdout=sp.PIPE,
  856. - stderr=sp.PIPE
  857. - )
  858. - out, err = p.communicate(input=bytes(chr(ch), "utf-8"))
  859. - if ch in specials.keys():
  860. - res = ( # magic
  861. - err
  862. - .decode("utf-8")
  863. - .strip()
  864. - .split("\n")[-1]
  865. - if ch not in (8, 13, 27)
  866. - else out
  867. - )
  868. - self.assertEqual(
  869. - specials[ch], res
  870. - )
  871. - else:
  872. - self.assertEqual(
  873. - out, bytes('{}'.format(ch), "utf-8")
  874. - )
  875. -
  876. - def test_read_keypress_raw(self):
  877. - """read raw keypress (patience)"""
  878. - specials = { # special cases
  879. - 8: b'\x08\x088',
  880. - 13: b'10',
  881. - 27: b'\x08\x0827',
  882. - 127: b'\x08\x08127',
  883. - }
  884. - for ch in range(128):
  885. - p = sp.Popen(
  886. - [py, TEST_HELP, "raw_readkey"],
  887. - stdin=sp.PIPE,
  888. - stdout=sp.PIPE,
  889. - stderr=sp.PIPE
  890. - )
  891. - out, err = p.communicate(input=bytes(chr(ch), "utf-8"))
  892. - if ch in specials.keys():
  893. - self.assertEqual(
  894. - specials[ch], out
  895. - )
  896. - else:
  897. - self.assertEqual(
  898. - out, bytes('{}'.format(ch), "utf-8")
  899. - )
  900. -
  901. -
  902. -if __name__ == '__main__':
  903. - from os import stat
  904. - try:
  905. - stat(TEST_HELP)
  906. - except FileNotFoundError as e:
  907. - print(e)
  908. - print("stat: cannot stat '{}': no such file or directory".format(TEST_HELP))
  909. - exit(2)
  910. - else:
  911. - unittest.main(verbosity = 3)
  912. \ No newline at end of file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement