13.misc.py 5.2 KB

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