test_aggrid.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. from datetime import datetime, timedelta, timezone
  2. from typing import List
  3. import pandas as pd
  4. from selenium.webdriver.common.action_chains import ActionChains
  5. from selenium.webdriver.common.keys import Keys
  6. from nicegui import ui
  7. from nicegui.testing import Screen
  8. def test_update_table(screen: Screen):
  9. grid = ui.aggrid({
  10. 'columnDefs': [{'field': 'name'}, {'field': 'age'}],
  11. 'rowData': [{'name': 'Alice', 'age': 18}],
  12. })
  13. screen.open('/')
  14. screen.should_contain('Name')
  15. screen.should_contain('Age')
  16. screen.should_contain('Alice')
  17. screen.should_contain('18')
  18. grid.options['rowData'][0]['age'] = 42
  19. screen.wait(0.5) # HACK: try to fix flaky test
  20. grid.update()
  21. screen.wait(0.5) # HACK: try to fix flaky test
  22. screen.should_contain('42')
  23. def test_add_row(screen: Screen):
  24. grid = ui.aggrid({
  25. 'columnDefs': [{'field': 'name'}, {'field': 'age'}],
  26. 'rowData': [],
  27. })
  28. ui.button('Update', on_click=grid.update)
  29. screen.open('/')
  30. grid.options['rowData'].append({'name': 'Alice', 'age': 18})
  31. screen.click('Update')
  32. screen.wait(0.5)
  33. screen.should_contain('Alice')
  34. screen.should_contain('18')
  35. grid.options['rowData'].append({'name': 'Bob', 'age': 21})
  36. screen.click('Update')
  37. screen.wait(0.5)
  38. screen.should_contain('Alice')
  39. screen.should_contain('18')
  40. screen.should_contain('Bob')
  41. screen.should_contain('21')
  42. def test_click_cell(screen: Screen):
  43. grid = ui.aggrid({
  44. 'columnDefs': [{'field': 'name'}, {'field': 'age'}],
  45. 'rowData': [{'name': 'Alice', 'age': 18}],
  46. })
  47. grid.on('cellClicked', lambda e: ui.label(f'{e.args["data"]["name"]} has been clicked!'))
  48. screen.open('/')
  49. screen.click('Alice')
  50. screen.should_contain('Alice has been clicked!')
  51. def test_html_columns(screen: Screen):
  52. ui.aggrid({
  53. 'columnDefs': [{'field': 'name'}, {'field': 'age'}],
  54. 'rowData': [{'name': '<span class="text-bold">Alice</span>', 'age': 18}],
  55. }, html_columns=[0])
  56. screen.open('/')
  57. screen.should_contain('Alice')
  58. screen.should_not_contain('<span')
  59. assert 'text-bold' in screen.find('Alice').get_attribute('class')
  60. def test_dynamic_method(screen: Screen):
  61. ui.aggrid({
  62. 'columnDefs': [{'field': 'name'}, {'field': 'age'}],
  63. 'rowData': [{'name': 'Alice', 'age': '18'}, {'name': 'Bob', 'age': '21'}, {'name': 'Carol', 'age': '42'}],
  64. ':getRowHeight': 'params => params.data.age > 35 ? 50 : 25',
  65. })
  66. screen.open('/')
  67. trs = screen.find_all_by_class('ag-row')
  68. assert len(trs) == 3
  69. heights = [int(tr.get_attribute('clientHeight')) for tr in trs]
  70. assert 23 <= heights[0] <= 25
  71. assert 23 <= heights[1] <= 25
  72. assert 48 <= heights[2] <= 50
  73. def test_run_grid_method_with_argument(screen: Screen):
  74. grid = ui.aggrid({
  75. 'columnDefs': [{'field': 'name', 'filter': True}],
  76. 'rowData': [{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carol'}],
  77. })
  78. filter_model = {'name': {'filterType': 'text', 'type': 'equals', 'filter': 'Alice'}}
  79. ui.button('Filter', on_click=lambda: grid.run_grid_method('setFilterModel', filter_model))
  80. screen.open('/')
  81. screen.should_contain('Alice')
  82. screen.should_contain('Bob')
  83. screen.should_contain('Carol')
  84. screen.click('Filter')
  85. screen.should_contain('Alice')
  86. screen.should_not_contain('Bob')
  87. screen.should_not_contain('Carol')
  88. def test_run_column_method_with_argument(screen: Screen):
  89. grid = ui.aggrid({
  90. 'columnDefs': [{'field': 'name'}, {'field': 'age', 'hide': True}],
  91. 'rowData': [{'name': 'Alice', 'age': '18'}, {'name': 'Bob', 'age': '21'}, {'name': 'Carol', 'age': '42'}],
  92. })
  93. ui.button('Show Age', on_click=lambda: grid.run_column_method('setColumnVisible', 'age', True))
  94. screen.open('/')
  95. screen.should_contain('Alice')
  96. screen.should_not_contain('18')
  97. screen.click('Show Age')
  98. screen.should_contain('18')
  99. def test_get_selected_rows(screen: Screen):
  100. @ui.page('/')
  101. def page():
  102. grid = ui.aggrid({
  103. 'columnDefs': [{'field': 'name'}],
  104. 'rowData': [{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carol'}],
  105. 'rowSelection': 'multiple',
  106. })
  107. async def get_selected_rows():
  108. ui.label(str(await grid.get_selected_rows()))
  109. ui.button('Get selected rows', on_click=get_selected_rows)
  110. async def get_selected_row():
  111. ui.label(str(await grid.get_selected_row()))
  112. ui.button('Get selected row', on_click=get_selected_row)
  113. screen.open('/')
  114. screen.click('Alice')
  115. screen.find('Bob')
  116. ActionChains(screen.selenium).key_down(Keys.SHIFT).click(screen.find('Bob')).key_up(Keys.SHIFT).perform()
  117. screen.click('Get selected rows')
  118. screen.should_contain("[{'name': 'Alice'}, {'name': 'Bob'}]")
  119. screen.click('Get selected row')
  120. screen.should_contain("{'name': 'Alice'}")
  121. def test_replace_aggrid(screen: Screen):
  122. with ui.row().classes('w-full') as container:
  123. ui.aggrid({'columnDefs': [{'field': 'name'}], 'rowData': [{'name': 'Alice'}]})
  124. def replace():
  125. container.clear()
  126. with container:
  127. ui.aggrid({'columnDefs': [{'field': 'name'}], 'rowData': [{'name': 'Bob'}]})
  128. ui.button('Replace', on_click=replace)
  129. screen.open('/')
  130. screen.should_contain('Alice')
  131. screen.click('Replace')
  132. screen.should_contain('Bob')
  133. screen.should_not_contain('Alice')
  134. def test_create_from_pandas(screen: Screen):
  135. df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [18, 21], 42: 'answer'})
  136. ui.aggrid.from_pandas(df)
  137. screen.open('/')
  138. screen.should_contain('Alice')
  139. screen.should_contain('Bob')
  140. screen.should_contain('18')
  141. screen.should_contain('21')
  142. screen.should_contain('42')
  143. screen.should_contain('answer')
  144. def test_create_dynamically(screen: Screen):
  145. ui.button('Create', on_click=lambda: ui.aggrid({'columnDefs': [{'field': 'name'}], 'rowData': [{'name': 'Alice'}]}))
  146. screen.open('/')
  147. screen.click('Create')
  148. screen.should_contain('Alice')
  149. def test_api_method_after_creation(screen: Screen):
  150. options = {'columnDefs': [{'field': 'name'}], 'rowData': [{'name': 'Alice'}]}
  151. ui.button('Create', on_click=lambda: ui.aggrid(options).run_grid_method('selectAll'))
  152. screen.open('/')
  153. screen.click('Create')
  154. assert screen.find_by_class('ag-row-selected')
  155. def test_problematic_datatypes(screen: Screen):
  156. df = pd.DataFrame({
  157. 'datetime_col': [datetime(2020, 1, 1)],
  158. 'datetime_col_tz': [datetime(2020, 1, 1, tzinfo=timezone.utc)],
  159. 'timedelta_col': [timedelta(days=5)],
  160. 'complex_col': [1 + 2j],
  161. 'period_col': pd.Series([pd.Period('2021-01')]),
  162. })
  163. ui.aggrid.from_pandas(df)
  164. screen.open('/')
  165. screen.should_contain('Datetime_col')
  166. screen.should_contain('Datetime_col_tz')
  167. screen.should_contain('Timedelta_col')
  168. screen.should_contain('Complex_col')
  169. screen.should_contain('Period_col')
  170. screen.should_contain('2020-01-01')
  171. screen.should_contain('5 days')
  172. screen.should_contain('(1+2j)')
  173. screen.should_contain('2021-01')
  174. def test_run_row_method(screen: Screen):
  175. grid = ui.aggrid({
  176. 'columnDefs': [{'field': 'name'}, {'field': 'age'}],
  177. 'rowData': [{'name': 'Alice', 'age': 18}],
  178. ':getRowId': '(params) => params.data.name',
  179. })
  180. ui.button('Update', on_click=lambda: grid.run_row_method('Alice', 'setDataValue', 'age', 42))
  181. screen.open('/')
  182. screen.should_contain('Alice')
  183. screen.should_contain('18')
  184. screen.click('Update')
  185. screen.should_contain('Alice')
  186. screen.should_contain('42')
  187. def test_run_method_with_function(screen: Screen):
  188. @ui.page('/')
  189. def page():
  190. grid = ui.aggrid({'columnDefs': [{'field': 'name'}], 'rowData': [{'name': 'Alice'}, {'name': 'Bob'}]})
  191. async def print_row(index: int) -> None:
  192. ui.label(f'Row {index}: {await grid.run_grid_method(f"(g) => g.getDisplayedRowAtIndex({index}).data")}')
  193. ui.button('Print Row 0', on_click=lambda: print_row(0))
  194. screen.open('/')
  195. screen.click('Print Row 0')
  196. screen.should_contain("Row 0: {'name': 'Alice'}")
  197. def test_get_client_data(screen: Screen):
  198. data: List = []
  199. @ui.page('/')
  200. def page():
  201. grid = ui.aggrid({
  202. 'columnDefs': [
  203. {'field': 'name'},
  204. {'field': 'age', 'sort': 'desc'},
  205. ],
  206. 'rowData': [
  207. {'name': 'Alice', 'age': 18},
  208. {'name': 'Bob', 'age': 21},
  209. {'name': 'Carol', 'age': 42},
  210. ],
  211. })
  212. async def get_data():
  213. data[:] = await grid.get_client_data()
  214. ui.button('Get Data', on_click=get_data)
  215. async def get_sorted_data():
  216. data[:] = await grid.get_client_data(method='filtered_sorted')
  217. ui.button('Get Sorted Data', on_click=get_sorted_data)
  218. screen.open('/')
  219. screen.click('Get Data')
  220. screen.wait(0.5)
  221. assert data == [{'name': 'Alice', 'age': 18}, {'name': 'Bob', 'age': 21}, {'name': 'Carol', 'age': 42}]
  222. screen.click('Get Sorted Data')
  223. screen.wait(0.5)
  224. assert data == [{'name': 'Carol', 'age': 42}, {'name': 'Bob', 'age': 21}, {'name': 'Alice', 'age': 18}]