def setUp(self): # mock需要登录的基类函数,统一返回测试用户 if self.contexts is None: self.contexts = [] super(LoginTestCase, self).setUp() user = User( username="******", tenant_id="mt_tenant_1", user_id="mt_user_1", ) user.save_object() user_id = user.id def get_current_user(): raise NotImplementedError("这个方法不应该被调用,参考get_current_user_async方法") # return User.query().get(user_id) # bind session o = patch.object(UserAuthBaseHandle, 'get_current_user', side_effect=get_current_user) @coroutine def get_current_user_async(): user = User.query().get(user_id) raise Return(user) o = patch.object(UserAuthBaseHandle, 'get_current_user_async', side_effect=get_current_user_async) self.contexts.append(o) o.__enter__()
def signup(): form = RegisterForm(request.form) if form.validate_on_submit(): User.create(username=form.username.data, password=form.password.data, active=True) flash('注册成功,请登录', 'success') return redirect(url_for('public.index')) else: flash_errors(form) return render_template('auth/signup.html', form=form)
def test_encode_obj(self): self.assertEqual(User.query(User).count(), 1) first_user = User.query().first() obj = SQLAlchemy2DictEncoder(fields=[ 'id', # int 'username', # str 'created_at' ]).encode(first_user) self.assertIsInstance(obj, dict) self.assertEqual(obj['id'], 1) self.assertEqual(obj['username'], 'test') self.assertIsInstance(obj['created_at'], datetime)
def test_picker(self): User(username="******", tenant_id="mt_tenant_1", user_id="mt_user_1").save_object() user = User.query().first() # have not error dumped_user = user.dumps() loaded_user = User.loads(dumped_user) self.assertEqual(loaded_user.username, user.username) self.assertEqual(loaded_user.tenant_id, user.tenant_id) self.assertEqual(loaded_user.user_id, user.user_id) self.assertEqual(loaded_user.id, user.id) self.assertEqual(loaded_user.updated_at, user.updated_at)
def delete_module(module_id=None): module = Module() try: if module_id is not None: module = Module.objects.get(pk=module_id) api_name = module.api_name User.objects(pk=current_user.id).update(pull__modules=module) shutil.rmtree(MODULES_FOLDER+'/'+api_name) shutil.rmtree(TEMPLATE_DIR+'/'+api_name) return redirect('/appmaker') except Exception, e: print e
def delete_module(module_id=None): module = Module() try: if module_id is not None: module = Module.objects.get(pk=module_id) api_name = module.api_name User.objects(pk=current_user.id).update(pull__modules=module) shutil.rmtree(MODULES_FOLDER + '/' + api_name) shutil.rmtree(TEMPLATE_DIR + '/' + api_name) return redirect('/appmaker') except Exception, e: print e
def test_encode_query(self): self.assertEqual(User.query(User).count(), 1) query = User.query() self.assertIsInstance(query, Query) result = SQLAlchemy2DictEncoder(fields=[ 'id', # int 'username', # str 'created_at' ]).encode(query) self.assertIsInstance(result, list) self.assertEqual(len(result), 1) obj = result[0] self.assertEqual(obj['id'], 1) self.assertEqual(obj['username'], 'test') self.assertIsInstance(obj['created_at'], datetime)
def setUpClass(cls): super().setUpClass() session = cls.Session() cls.username = '******' cls.password = '******' user = User(username=cls.username, password=str( bcrypt.hashpw(cls.password.encode('utf-8'), bcrypt.gensalt()), 'utf-8'), avatar='Katarina.png', introduction='L') article = Article( user=user, title='L', introduction='L', markdown_content='L', compiled_content='L', ) tag = Tag(content='hello') article.tag.append(tag) user.tag.append(tag) session.add(user) session.add(article) fish_record = Record( title='hello', content=['hello'], image_num=1, source='hello', ) session.add(fish_record) session.commit() session.close()
def activate(token): if User.check_activate_token(token): flash('激活成功') return redirect(url_for('user.login')) else: flash('激活失败') return redirect(url_for('user.home'))
def _create_user(self, data): username = self._find_available_username(data) first_name = data.get('first_name') last_name = data.get('last_name') facebook_uid = data.get('uid') img_url = data.get('pic_square') email = '%s@facebookuser.%s.com' % (first_name, settings.SITE_NAME) user = User(username=username, email=email, first_name=first_name, last_name=last_name) temp_password = User.objects.make_random_password(length=24) user.set_password(temp_password) user.save() if img_url: img = ContentFile(requests.get(img_url).content) name = img_url.split('/')[-1] user.picture.save(name, img, False) FacebookAccount.objects.create(uid=facebook_uid, user=user, avatar=img_url) return user
def reset(token): if request.method == 'POST': if session.get('username'): return redirect(url_for('user.home')) if User.reset_password(token, request.form['password']): flash('您的密码已经修改成功') return redirect(url_for('user.login')) return render_template('login/reset.html', token=token)
def register(): form = RegisterForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, "Confir your account", template="confirm", token=token) flash('Confirmation token has been sent to your email.') return redirect(url_for('index')) return render_template("register.html", form=form)
def user_bind_sid(message): """ 绑定 user 和 sid """ user_id = message['user_id'] sid = message['sid'] user = User.get_by_id(user_id) user.sid = sid user.save()
def run(self): print("Create admin") from apps.auth.models import User admin = User(username="******", password="******", email="*****@*****.**", confirmed=True) db.session.add(admin) db.session.commit()
def test_create_or_get(self): self.assertEqual(User.query(User.id).count(), 0) obj, is_created = User.create_or_get(username="******", tenant_id="mt_tenant_1", user_id="mt_user_1") self.assertEqual(obj.id, 1) self.assertEqual(is_created, True) obj, is_created = User.create_or_get(username="******", tenant_id="mt_tenant_1", user_id="mt_user_1") self.assertEqual(obj.id, 1) self.assertEqual(is_created, False) obj, is_created = User.create_or_get(username="******", tenant_id="mt_tenant_1", user_id="mt_user_1") self.assertEqual(obj.id, 1) self.assertEqual(is_created, False)
def test_create_users(self): for _ in range(users_number): username = "******".format(faker.user_name(), str(randrange(0, 99))) email = "{}{}".format(str(randrange(0, 99)), faker.email()) user = User(username=username, password=faker.password(), email=email) db.session.add(user) db.session.commit()
def test_getattr(self): user = User( username="******", tenant_id="mt_tenant_1", user_id="mt_user_1", ) user.save_object() self.assertEqual(User.query(User).count(), 1) first_user = User.query(User).one() self.assertEqual(first_user['username'], "test") first_user['username'] = "******" self.assertEqual(first_user.username, "test2") User.save_updates(first_user)
def test_sso(self): """测试SSO过程 默认的http_client是AsyncHTTPClient 这里不用SessionClient,是因为SessionClient依赖RESTfulAsyncClient 而后者被上面mock掉了 """ # 首页现在重定向到analyze了也需要登录了 # response = self.fetch("/") # # 维持一个session # self.assertTrue(response.effective_url.startswith("http://localhost")) cookies = [] # for cookie in response.headers.get_list("Set-Cookie"): # cookies.append(self._parse_cookie(cookie)) headers = {} url = self.reverse_url("user:logout") response = self.fetch(url, headers=headers) self.assertFalse(response.effective_url.startswith("http://localhost")) self.assertEqual(User.query(User.id).count(), 0) # 经过一番重定向(外部忽略)后,带着token回到callback页面,并登陆 response2 = self.fetch( "/user/callback", method="POST", body="token=suibianshenme", headers=headers, # !!!跟随重定向的时候,cookie就没了,这尼玛心塞 follow_redirects=False) self.assertEqual(User.query(User.id).count(), 1) first_user = User.query(User).one() self.assertEqual(first_user.username, "testusername") self.assertEqual(first_user.tenant_id, "mt_tenant_1") self.assertEqual(first_user.user_id, "mt_user_1") # 再次带着登陆的Cookie for cookie in response2.headers.get_list("Set-Cookie"): cookies.append(self._parse_cookie(cookie)) headers = {"Cookie": "; ".join(cookies)} # 再访问之前需要登录的链接 response = self.fetch("/analyze/", headers=headers) self.assertTrue(response.effective_url.startswith("http://localhost"))
def test_create(self): self.assertEqual(User.query(User.id).count(), 0) user = User( username="******", tenant_id="mt_tenant_1", user_id="mt_user_1", ) user.save_object() self.assertEqual(User.query(User).count(), 1) first_user = User.query(User).one() self.assertEqual(first_user.username, "test") self.assertEqual(first_user.tenant_id, "mt_tenant_1") self.assertEqual(first_user.user_id, "mt_user_1") yield gen.sleep(1) first_user.username = '******' # first_user.updated_at = datetime(2010, 1, 1,tzinfo=UTC) first_user.save_object() self.assertEqual(User.query(User).count(), 1) first_user = User.query(User).one() self.assertGreater(first_user.updated_at, first_user.created_at) # first_user.updated_at = datetime(2010, 1, 1, tzinfo=UTC) # first_user.save_object() first_user = User.query(User).first()
def register(): error = None if request.method == 'POST': db.create_all() if request.form['password1'] != request.form['password2']: error = '两次密码不相同!' elif valid_register(request.form['username'], request.form['email']): user = User(username=request.form['username'], password=my_md5(request.form['password1']), email=request.form['email']) db.session.add(user) db.session.commit() token = user.generate_activate_token() send_activate_mail(user.email, '账号激活', 'activate', username=user.username, token=token) flash("成功注册,请移步至邮箱点击激活") return redirect(url_for('user.home')) else: error = '该用户名或邮箱已被注册!' return render_template('login/register.html', error=error)
def test_iter(self): user = User( username="******", tenant_id="mt_tenant_1", user_id="mt_user_1", ) user.save_object() for i, value in user: pass obj = user.items() keys = user.keys() values = user.values() self.assertEqual(keys, [o[0] for o in obj]) self.assertEqual(values, [o[1] for o in obj])
def test_update_or_create(self): self.assertEqual(User.query(User.id).count(), 0) obj, is_created = User.update_or_create(username="******", defaults={ "tenant_id": "mt_tenant_1", "user_id": "mt_user_1" }) self.assertEqual(obj.id, 1) self.assertEqual(is_created, True) self.assertEqual(User.query(User.id).count(), 1) first_user = User.query(User).one() self.assertEqual(first_user.username, "test") self.assertEqual(first_user.tenant_id, "mt_tenant_1") self.assertEqual(first_user.user_id, "mt_user_1") # 一样的数据则不修改 obj, is_created = User.update_or_create(username="******", defaults={ "tenant_id": "mt_tenant_1", "user_id": "mt_user_1" }) self.assertEqual(obj.id, 1) self.assertEqual(is_created, False) self.assertEqual(User.query(User.id).count(), 1) obj, is_created = User.update_or_create(username="******", defaults={ "tenant_id": "mt_tenant_12", "user_id": "mt_user_12" }) self.assertEqual(obj.id, 1) self.assertEqual(is_created, False) self.assertEqual(User.query(User.id).count(), 1) first_user = User.query(User).first() self.assertEqual(first_user.username, "test") self.assertEqual(first_user.tenant_id, "mt_tenant_12") self.assertEqual(first_user.user_id, "mt_user_12")
def _create_user(self, access_token, data): username = self._find_available_username(data) twitter_username = data.screen_name first_name, last_name = self._get_first_last_name(data) avatar = data.profile_image_url email = '%s@twitteruser.%s.com' % (twitter_username, settings.SITE_NAME) user = User(username=username, email=email, first_name=first_name, last_name=last_name) temp_password = User.objects.make_random_password(length=24) user.set_password(temp_password) user.save() TwitterAccount.objects.create(user=user, username=twitter_username, access_token=access_token.key, avatar=avatar) return user
def test_todict(self): user = User( username="******", tenant_id="mt_tenant_1", user_id="mt_user_1", ) user.save_object() self.assertEqual(User.query(User).count(), 1) first_user = User.query(User).one() self.assertIsNone(first_user.deleted_at) expect = { 'username': u'test', 'user_id': u'mt_user_1', 'tenant_id': u'mt_tenant_1', u'deleted_at': None, 'id': 1 } user_obj = first_user.to_dict() for key, value in expect.iteritems(): self.assertEqual(user_obj[key], value)
def test_email_diff_subtitles(self): initial_count = len(mail.outbox) # set a user who can receive notification # make sure we have a different author, else he won't get notified author = User(username='******', email='*****@*****.**', notify_by_email=True, valid_email=True) author.save(send_email_confirmation=False) # bypass logic from hell author.valid_email = True author.save() # this is needed for the non_editor template check user2 = User(username='******', email='*****@*****.**', notify_by_email=True, valid_email=True) user2.save(send_email_confirmation=False) # bypass logic from hell user2.valid_email = True user2.save() # version is indentical to previous one video = Video.get_or_create_for_url( "http://wwww.example.com/video-diff.mp4")[0] video.followers.add(author) video.followers.add(user2) language = SubtitleLanguage(video=video, language_code='en') language.save() subs_data = [ [0, 1000, '1'], [1000, 2000, '2'], ] subtitles_1 = SubtitleSet.from_list('en', subs_data) old_version = language.add_version(subtitles=subtitles_1, author=author) # now we change the text on the second sub subs_data[1][2] = '2 changed' # add a regular sub subs_data.append([2000, 3000, 'new sub']) # add an unsyced subs_data.append([None, None, 'no sync']) subtitles_2 = SubtitleSet.from_list('en', subs_data) new_version = language.add_version(subtitles=subtitles_2) self.assertTrue(len(video.notification_list()) > 0) res = send_new_version_notification(new_version.pk) self.assertNotEqual(res, None) # we expect two emails, one is the new-edits-non-editor, and # the other for mail_notification.html self.assertEqual(len(mail.outbox), initial_count + 2) for email_number, email_msg in enumerate(mail.outbox): # make sure this is the right message self.assertIn("New edits to ", email_msg.subject) self.assertIn("video-diff.mp4", email_msg.subject) html = BeautifulSoup(email_msg.body) html_text = "".join(html.body(text=True)).replace("\n", "") if email_number == 0: # assert text and timing changes are correct self.assertIn('67% of the text', html_text) self.assertIn('33% of the timing was changed.', html_text) # find the listed text changes to make sure they match diff_table = html.findAll('table', attrs={'class': 'diffs'})[0] old_version_changes = [] new_version_changes = [] for i, node in enumerate(diff_table.findAll('td')): if i % 2 == 0: old_version_changes.append(node.text) else: new_version_changes.append(node.text) self.assertEqual(old_version_changes, [u'2', u'', u'']) self.assertEqual(new_version_changes, [ u'2 changed', u'new sub', u'no sync', ])
def load_user(user_id): return User.get_by_id(int(user_id))
def get_current_user_async(): user = User.query().get(user_id) raise Return(user)
def test_confirmation(self): for _ in range(users_number): u = User(password=faker.password()) self.assertFalse(u.confirmed)
def test_password_setter(self): for _ in range(users_number): u = User(password=faker.password()) self.assertTrue(u.password_hash)
async def clear_db_tables(request): yield engine = await get_engine() async with engine.acquire() as conn: await conn.execute(User.delete())
def _create_followers(self, video, num_followers): for x in xrange(0, num_followers): u = User(username="******" % x, email="*****@*****.**" % x) u.save() video.followers.add(u)