setup_db.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # -*- coding: UTF-8 -*-
  2. import requests
  3. import sys
  4. import json
  5. import random
  6. import string
  7. import os
  8. from csv import reader
  9. from user_test import get_user, get_all_users, delete_user
  10. from group_test import get_group_by_name, get_group, create_group, add_user_to_group
  11. from exam_test import create_exam, create_question, get_question, add_question_to_exam
  12. from category_test import create_material, get_material, create_category, get_category, add_material_to_category, update_category, create_question_category, get_question_category, questions_in_category, add_question_to_question_category, update_question_category
  13. from learningmaterial_test import add_comment
  14. USERNAME_RANDOM_LENGTH = 10
  15. override = False
  16. want_material = False
  17. want_user = False
  18. want_question = False
  19. if len(sys.argv) > 1:
  20. for arg in sys.argv:
  21. if arg == 'override':
  22. override = True
  23. if arg == 'material':
  24. want_material = True
  25. if arg == 'user':
  26. want_user = True
  27. if arg == 'question':
  28. want_question = True
  29. def _random_string(length):
  30. letters = string.ascii_letters
  31. return ''.join(random.choice(letters) for i in range(length))
  32. def _text(resp):
  33. return json.loads(resp.text)
  34. # 创建 10 个 前缀为namePrefix 密码为password的 用户
  35. def add_dummy_users(namePrefix = 'testuser-', password = 'test', number = 10):
  36. groups = add_groups()
  37. users = []
  38. nicknames = ['小强', '小张', '小李子', '大王']
  39. firstNames = ['一', '二', '三', '四', '五']
  40. lastNames = ['张', '王', '李', '杜', '靳']
  41. for i in range(number):
  42. user_name = namePrefix + _random_string(USERNAME_RANDOM_LENGTH)
  43. # register_user(user_name, password)
  44. new_user = {
  45. 'userName': user_name,
  46. 'password': password,
  47. 'nickName': nicknames[i % len(nicknames)],
  48. 'studyId': 'U0000' + str(i),
  49. 'email': 'test@gmail.com',
  50. 'firstName': firstNames[i % len(firstNames)],
  51. 'lastName': lastNames[i % len(lastNames)],
  52. 'phone': '13060901234',
  53. 'birthday': '1999-01-01',
  54. }
  55. register_user(new_user)
  56. user = get_user(user_name)
  57. random_group = groups[random.randint(0, len(groups)-1)]
  58. add_user_to_group(random_group, _text(user))
  59. users.append(_text(user)['userName'])
  60. print('created ' + str(len(users)) + ' users: ' + ','.join(users))
  61. global all_users
  62. all_users = users
  63. return users
  64. # 创建 3个二级的group
  65. # orgtest-level1
  66. # orgtest-level2-a orgtest-level2-b orgtest-level2-c
  67. def add_groups(namePrefix = 'orgtest-', number=3):
  68. # creating level1 group
  69. level1_name = namePrefix + 'level1-' + _random_string(3)
  70. level1_group_body = {
  71. 'name': level1_name
  72. }
  73. create_group(level1_group_body)
  74. level1_group = _text(get_group_by_name(level1_name))
  75. groups = []
  76. for i in range(number):
  77. level2_group_body = {
  78. 'name': namePrefix + 'level2-' + _random_string(3),
  79. 'parentGroupId': level1_group['id']
  80. }
  81. resp = create_group(level2_group_body)
  82. groupId = _text(resp)['id']
  83. groups.append(groupId)
  84. print ('created ' + str(len(groups)) + ' groups: ' + ','.join(groups))
  85. return groups
  86. def randomly_pick_user():
  87. global all_users
  88. rand_index = random.randint(0, len(all_users) - 1)
  89. return all_users[rand_index]
  90. def create_exams(namePrefix='测试考试-', number=2):
  91. exams = []
  92. for i in range(number):
  93. new_exam = {
  94. 'name': namePrefix + _random_string(3),
  95. 'description': '可以回家做',
  96. 'duration': random.randint(0, 863) * 100, # seconds
  97. }
  98. resp = create_exam(new_exam)
  99. exams.append(_text(resp)['id'])
  100. print ('created ' + str(len(exams)) + ' exams: ' + ','.join(exams))
  101. return exams
  102. def create_questions(namePrefix='qtest-', number=10, from_file=False):
  103. exams = create_exams()
  104. questions = []
  105. question_categories = create_question_categories()
  106. if from_file:
  107. files = os.listdir('./demo-questions/')
  108. for file_name in files:
  109. with open('./demo-questions/' + file_name, 'r') as read_obj:
  110. print('loading ' + file_name + ' to db')
  111. csv_reader = reader(read_obj)
  112. for row in csv_reader:
  113. qNumber = row[0]
  114. if qNumber == '题号' or len(qNumber) < 1:
  115. continue
  116. content = row[1] # required
  117. temp_type = row[2] # required
  118. qType = 'DanXuan'
  119. if temp_type == '2':
  120. qType = 'DuoXuan'
  121. if temp_type == '3':
  122. qType = 'PanDuan'
  123. answers = [] # required
  124. for i in [3, 4, 5, 6]:
  125. if len(row[i]) > 0:
  126. answers.append(row[i])
  127. finalAnswer = row[7] # required
  128. answerAnalysis = row[8]
  129. keyword = row[9];
  130. level = row[10];
  131. tags = []
  132. if len(row[11]) > 0:
  133. tags.append(row[11])
  134. if len(content) == 0 or len(qType) == 0 or len(answers) == 0 or len(finalAnswer) == 0:
  135. print('Skip due to required info missing')
  136. continue
  137. question = {
  138. 'userId': randomly_pick_user(),
  139. 'content': content,
  140. 'answers': answers,
  141. 'finalAnswer': [finalAnswer],
  142. 'keyword': keyword,
  143. 'type': qType,
  144. 'questionLevel': level,
  145. 'tags': tags,
  146. 'answerAnalysis': answerAnalysis,
  147. }
  148. resp = create_question(question)
  149. random_exam_id = exams[random.randint(0, len(exams)-1)]
  150. # add newly created question to a random exam
  151. add_question_to_exam(random_exam_id, [_text(resp)])
  152. questions.append(_text(resp)['id'])
  153. else:
  154. for i in range(number):
  155. question = {
  156. 'userId': randomly_pick_user(),
  157. 'content': namePrefix + '天上什么星星最亮?-' + str(i),
  158. 'answers': ['太阳', '小天狼星', '北极星'],
  159. 'finalAnswer': ['小天狼星'],
  160. 'type': 'DanXuan' # 单选题
  161. }
  162. resp = create_question(question)
  163. random_exam_id = exams[random.randint(0, len(exams)-1)]
  164. # add newly created question to a random exam
  165. add_question_to_exam(random_exam_id, [_text(resp)])
  166. questions.append(_text(resp)['id'])
  167. tiankong_question = {
  168. 'userId': randomly_pick_user(),
  169. 'content': namePrefix + '天上$PH$最亮?-' + str(i),
  170. 'finalAnswer': ['小天狼星'],
  171. 'type': 'TianKong' # 填空题
  172. }
  173. resp = create_question(tiankong_question)
  174. random_exam_id = exams[random.randint(0, len(exams)-1)]
  175. # add newly created question to a random exam
  176. add_question_to_exam(random_exam_id, [_text(resp)])
  177. random_category_id = question_categories[random.randint(0, len(question_categories)-1)]
  178. add_question_to_question_category(random_category_id, _text(resp))
  179. questions.append(_text(resp)['id'])
  180. print ('created ' + str(len(questions)) + ' questions')
  181. return questions
  182. def create_question_categories(namePrefix= '知识类-', number=3):
  183. resp = create_question_category(namePrefix + _random_string(3))
  184. question_root_id = _text(resp)['id']
  185. categories = []
  186. names = ['科普类-', '技术类-', '历史类-', '天文类-', '兴趣类-']
  187. for i in range(number):
  188. child = create_question_category(names[i % len(names)] + _random_string(3))
  189. child_id = _text(child)['id']
  190. update_question_category(child_id, {
  191. 'parentId': question_root_id
  192. })
  193. categories.append(child_id)
  194. print ('created ' + str(len(categories)) + ' question categories: ' + ','.join(categories))
  195. return categories
  196. def create_categories(namePrefix= 'testCategory-', number=3):
  197. resp = create_category(namePrefix + 'root-' + _random_string(3))
  198. root_id = _text(resp)['id']
  199. categories = []
  200. for i in range(number):
  201. child = create_category(namePrefix + 'child-' + _random_string(3))
  202. child_id = _text(child)['id']
  203. update_category(child_id, {
  204. 'parentId': root_id
  205. })
  206. categories.append(child_id)
  207. print ('created ' + str(len(categories)) + ' categories: ' + ','.join(categories))
  208. return categories
  209. def read_material_from_file(file_name):
  210. file = open('./demo-materials/' + file_name, 'r')
  211. file_lines = file.readlines()
  212. count = 0
  213. content = ''
  214. title = ''
  215. for line in file_lines:
  216. line = line.strip()
  217. if len(line) < 1:
  218. continue # whitespaces
  219. if count == 0:
  220. title = line
  221. else:
  222. content += line + '\n'
  223. count+=1
  224. return title, content
  225. def create_learning_materials(namePrefix='测试资料-', number=20, from_file=False):
  226. categories = create_categories()
  227. materials = []
  228. if from_file:
  229. files = os.listdir('./demo-materials/')
  230. for file_name in files:
  231. title, content = read_material_from_file(file_name)
  232. material = create_material({
  233. 'name': title,
  234. 'userId': randomly_pick_user(),
  235. 'type': 'ARTICLE',
  236. 'contents': content,
  237. })
  238. materialId = _text(material)['id']
  239. materials.append(materialId)
  240. random_category = categories[random.randint(0, len(categories)-1)]
  241. add_material_to_category(random_category, _text(material))
  242. create_comments(materialId)
  243. else:
  244. for i in range(number):
  245. user = randomly_pick_user()
  246. material = create_material({
  247. 'name': namePrefix + _random_string(5),
  248. 'userId': randomly_pick_user(),
  249. 'description': '好看的资料',
  250. 'type': 'ARTICLE',
  251. 'contents': '十年高考三年模拟-' + _random_string(20),
  252. 'links': [_random_string(3), _random_string(3), _random_string(3)]
  253. })
  254. materialId = _text(material)['id']
  255. materials.append(materialId)
  256. random_category = categories[random.randint(0, len(categories)-1)]
  257. add_material_to_category(random_category, _text(material))
  258. create_comments(materialId)
  259. print ('created ' + len(materials) + ' materials: ' + ','.join(materials))
  260. return materials
  261. def create_comments(materialId, namePrefix='[自动生成]', number=5):
  262. dummy_comments = ['我去,这也太酷了!', '我太爱学这个了,老牛了', '这太有意思了,收藏了', '好文,顶一个', '我踩']
  263. for i in range(number):
  264. comment = {
  265. 'userId': randomly_pick_user(),
  266. 'content': dummy_comments[i % len(dummy_comments)]
  267. }
  268. add_comment(materialId, comment)
  269. print('created ' + str(number) + ' comments to material: ' + materialId)
  270. def register_user(userData):
  271. url = 'http://localhost:8080/user/register'
  272. return requests.post(url, json=userData)
  273. if override:
  274. all_users = json.loads(get_all_users().text)
  275. for user in all_users:
  276. delete_user(user['userName'])
  277. print('deleted all users')
  278. if want_user:
  279. add_dummy_users()
  280. else:
  281. print('Skip creating users')
  282. if want_question:
  283. create_questions(from_file=True)
  284. else:
  285. print('Skip creating questions')
  286. if want_material:
  287. create_learning_materials(from_file=True)
  288. else:
  289. print('Skip creating materials')