13.misc.py 5.5 KB

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