1
0

13.misc.py 6.0 KB

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