13.misc.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import re
  2. import subprocess
  3. from functools import partial
  4. from percy import percy_snapshot
  5. from selenium.webdriver import Chrome
  6. from selenium.webdriver.common.by import By
  7. import pywebio
  8. import template
  9. import util
  10. from pywebio import start_server
  11. from pywebio.input import *
  12. from pywebio.output import *
  13. from pywebio.platform import seo
  14. from pywebio.session import *
  15. from pywebio.utils import *
  16. def target():
  17. # test session data
  18. g = data()
  19. assert g.none is None
  20. g.one = 1
  21. g.one += 1
  22. assert g.one == 2
  23. local.name = "Wang"
  24. local.age = 22
  25. assert len(local) == 3
  26. assert local['age'] is local.age
  27. assert local.foo is None
  28. local[10] = "10"
  29. del local['name']
  30. del local.one
  31. for key in local:
  32. print(key)
  33. assert 'bar' not in local
  34. assert 'age' in local
  35. assert local._dict == {'age': 22, 10: '10'}
  36. print(local)
  37. # test eval_js promise
  38. import random
  39. val = random.randint(1, 9999999)
  40. promise_res = yield eval_js('''new Promise((resolve,reject) => {
  41. setTimeout(() => {
  42. resolve(val);
  43. }, 1);
  44. });''', val=val)
  45. print(promise_res, val)
  46. assert promise_res == val
  47. # test pywebio.utils
  48. async def corofunc(**kwargs):
  49. pass
  50. def genfunc(**kwargs):
  51. yield
  52. corofunc = partial(corofunc, a=1)
  53. genfunc = partial(genfunc, a=1)
  54. assert isgeneratorfunction(genfunc)
  55. assert iscoroutinefunction(corofunc)
  56. assert get_function_name(corofunc) == 'corofunc'
  57. get_free_port()
  58. try:
  59. yield put_buttons([{'label': 'must not be shown'}], onclick=[lambda: None])
  60. except Exception:
  61. pass
  62. put_table([
  63. ['Idx', 'Actions'],
  64. ['1', put_buttons(['edit', 'delete'], onclick=lambda _: None)],
  65. ])
  66. popup('title', 'text content')
  67. @popup('Popup title')
  68. def show_popup():
  69. put_html('<h3>Popup Content</h3>')
  70. put_text('html: <br/>')
  71. with popup('Popup title') as s:
  72. put_html('<h3>Popup Content</h3>')
  73. clear(s)
  74. put_buttons(['clear()'], onclick=lambda _: clear(s))
  75. popup('title2', 'text content')
  76. close_popup()
  77. with use_scope() as name:
  78. put_text('no show')
  79. remove(name)
  80. with use_scope('test') as name:
  81. put_text('current scope name:%s' % name)
  82. with use_scope('test', clear=True):
  83. put_text('clear previous scope content')
  84. @use_scope('test')
  85. def scoped_func(text):
  86. put_text(text)
  87. scoped_func('text1 from `scoped_func`')
  88. scoped_func('text2 from `scoped_func`')
  89. put_tabs([
  90. {'title': 'Text', 'content': 'Hello world'},
  91. {'title': 'Markdown', 'content': put_markdown('~~Strikethrough~~')},
  92. {'title': 'More content', 'content': [
  93. put_table([
  94. ['Commodity', 'Price'],
  95. ['Apple', '5.5'],
  96. ['Banana', '7'],
  97. ]),
  98. put_link('pywebio', 'https://github.com/wang0618/PyWebIO')
  99. ]},
  100. ])
  101. try:
  102. put_column([put_text('A'), 'error'])
  103. except Exception:
  104. pass
  105. toast('Awesome PyWebIO!!', duration=0)
  106. def show_msg():
  107. put_text("ToastClicked")
  108. toast('You have new messages', duration=0, onclick=show_msg)
  109. run_js("$('.toastify').eq(0).click()")
  110. assert get_scope() == 'ROOT'
  111. with use_scope('go_app'):
  112. put_buttons(['Go thread App'], [lambda: go_app('threadbased', new_window=False)])
  113. # test unhandled error
  114. with use_scope('error'):
  115. put_buttons(['Raise error'], [lambda: 1 / 0])
  116. put_image('/static/favicon_open_32.png')
  117. with put_info():
  118. put_table([
  119. ['Commodity', 'Price'],
  120. ['Apple', '5.5'],
  121. ['Banana', '7'],
  122. ])
  123. put_markdown('~~Strikethrough~~')
  124. put_file('hello_word.txt', b'hello word!')
  125. with put_collapse('title', open=True):
  126. put_table([
  127. ['Commodity', 'Price'],
  128. ['Apple', '5.5'],
  129. ['Banana', '7'],
  130. ])
  131. with put_collapse('title', open=True):
  132. put_table([
  133. ['Commodity', 'Price'],
  134. ['Apple', '5.5'],
  135. ['Banana', '7'],
  136. ])
  137. put_markdown('~~Strikethrough~~')
  138. put_file('hello_word.txt', b'hello word!')
  139. yield input_group('test input popup', [
  140. input('username', name='user'),
  141. actions('', ['Login', 'Register', 'Forget'], name='action')
  142. ])
  143. @seo("corobased-session", 'This is corobased-session test')
  144. async def corobased():
  145. await wait_host_port(port=8080, host='127.0.0.1')
  146. async def bg_task():
  147. while 1:
  148. await asyncio.sleep(1)
  149. run_async(bg_task())
  150. await to_coroutine(target())
  151. def threadbased():
  152. """threadbased-session
  153. This is threadbased-session test
  154. """
  155. port = get_free_port()
  156. print('free port', port)
  157. run_as_function(target())
  158. def test(server_proc: subprocess.Popen, browser: Chrome):
  159. time.sleep(2)
  160. coro_out = template.save_output(browser)[-1]
  161. # browser.get('http://localhost:8080/?app=thread')
  162. browser.execute_script("arguments[0].click();",
  163. browser.find_element(By.CSS_SELECTOR, '#pywebio-scope-go_app button'))
  164. time.sleep(2)
  165. thread_out = template.save_output(browser)[-1]
  166. assert "ToastClicked" in coro_out
  167. # Eliminate the effects of put_tabs
  168. assert re.sub(r'"webio-.*?"', '', coro_out) == re.sub(r'"webio-.*?"', '', thread_out)
  169. browser.execute_script("WebIO._state.CurrentSession.ws.close()")
  170. time.sleep(6)
  171. browser.execute_script("arguments[0].click();",
  172. browser.find_element(By.CSS_SELECTOR, '#pywebio-scope-error button'))
  173. browser.execute_script("$('button[type=submit]').click();")
  174. time.sleep(2)
  175. percy_snapshot(browser, name='misc')
  176. def start_test_server():
  177. pywebio.enable_debug()
  178. start_server([corobased, partial(threadbased)], port=8080, host='127.0.0.1', debug=True, cdn=False,
  179. static_dir=STATIC_PATH + '/image', reconnect_timeout=10)
  180. if __name__ == '__main__':
  181. util.run_test(start_test_server, test, address='http://localhost:8080/?app=corobased')