def generate_users(cnt): names = [ 'john', 'peter', 'kolya', 'misha', 'pasha', 'ilja', 'trump', 'derek' ] snames = ['obama', 'trum', 'ivanov', 'prtrov', 'lomov', 'morgan'] mails = ['ya', 'ma', 'go'] nsize = len(names) ssize = len(snames) msize = len(mails) imgs = os.listdir('/home/hase/technopark/web/AskZaytsev/scripts/test_img') imgsc = len(imgs) for i in range(0, cnt): print(i) fname = names[random.randint(0, nsize - 1)] sname = snames[random.randint(0, ssize - 1)] email = names[random.randint( 0, nsize - 1)] + '@' + mails[random.randint(0, msize - 1)] + '.ru' pwd = str(random.randint(10000, 1000000)) u = User() u.username = fname + ' ' + sname + str(i) u.password = pwd u.email = email u.first_name = fname u.last_name = sname u.is_active = True u.is_superuser = False u.save() img = imgs[random.randint(0, imgsc - 1)] print(img) p = Profile(user=u, avatar=img) p.save() print(p.avatar)
def test_mention_event(self): user = User({"username": "******", "ext_id": "test"}) user.save() other_user = User({"username": "******", "ext_id": "other"}) other_user.save() p = Question({ "title": "test title", "body": "test body, @test is mentioned", "tags": ["test-tag"], "author_id": user._id }) p.save() self.run_tasks() events = user.get_new_events() self.assertEqual(events.count(), 0) a = p.create_answer({ "author_id": other_user._id, "body": "this @test mention should create an event" }) a.save() self.run_tasks() events = user.get_new_events() self.assertEqual(events.count(), 2) # new comment event and mention event found_mention_event = False for event in events: if isinstance(event, MentionEvent): found_mention_event = True self.assertEqual(event.author_id, other_user._id) self.assertEqual(event.post_id, a._id) self.assertTrue(found_mention_event)
def fill_db(self): for i in range(0, 30): usr = User(username='******' + str(i), password='******' + str(i), first_name='User') usr.save() prof = Profile(avatar='avatar.jpeg', user=usr) prof.save() try: tbag = Tag.objects.get(name='Bucket' + str(i % 20)) tbag.popularity += 1 except Exception: tbag = Tag(name='Bucket' + str(i % 20), popularity=1) tbag.save() quest = Question(title=str(i) + 'bucket', text='see my bucket, I have a' + str(10000 - i) + ' bucket remains', author=prof, votes=i) quest.save() quest.liked.add(prof) quest.tag.add(tbag) for j in range(0, 20): ans = Answer(text='Test answer' + str(i), author=prof, question=quest) ans.votes = int(((i + j) * 6) % 40) ans.save() ans.voted.add(prof)
def oauth_callback(): code = request.values.get("code") state = request.values.get("state") if not code: raise AuthenticationError("no code from provider") if not state: raise AuthenticationError("no state from provider") tokens = state.split(":") if len(tokens) != 2: raise AuthenticationError( "invalid state from provider. expected <provider>:<origin>") provider_name, origin = tokens provider = BaseProvider.get_provider(provider_name) token = provider.acquire_token(code) user_data = provider.get_user_data(token) user = User.find_one({"ext_id": user_data["ext_id"]}) if not user: user = User(user_data) user.fixup_username() user.save() session["user_id"] = user._id session.modified = True path = ctx.cfg.get("base_uri", "http://localhost:8080/") return redirect(f"{path}#{origin}")
def _fill_user(self): print('FILLING USER MODEL...') for ix in range(500): temp_user = User(username='******'.format(ix + 1), registration_date=timezone.now(), rating=np.random.normal(scale=50), path='user{}'.format(ix + 1)) temp_user.save() print('ADDED {} USERS.'.format(User.objects.count()))
def generateUsers(n): import urllib2, hashlib nickWords = [ "Void", "Facelessness", "OMG", "_xxxMLGxxx_", "lox", "zeus", "warlock", "murlock", "YoLo", "YoYo", "rwl_lll_rl", "Flash", "Batman", "Bat", "mobile", "rang", "l33t", "h@xx0r", "Orange", "Annoying", "Apple", "Hey", "dummy", "stuff", "annoy", "word", "Shadow", "Ivan", "Vladimir", "ROFL", "Enigma", "Rubick", "cube", "Cube", "Horadirc", "Deckard", "Kain", "user", "version", "test", "hello", "world", "master", "HealBot", "Loatheb", "jinxed" ] + [""] * 5 nameWords = [ "Ivan", "Leah", "Deckard", "Tyrael", "Nova", "Sarah", "Jim", "Tassadar", "Zeratul", "Azmodan" ] + [""] * 10 surnameWords = [ "Chrono", "Kain", "ArchangelOfJustice", "Terra", "Kerrigan", "Raynor", "SaviorOfTemplar", "LordOfSin" ] + [""] * 9 for i in range(n): username = random.choice(nickWords) + random.choice(nickWords) + str( random.randint(i, i * 10 + 10)) password = ''.join([ random.choice("qwertyuiopasdfghjklzxcvbnm!@1234567890") for t in range(16) ]) email = random.choice(nickWords) + random.choice( username) + '@' + random.choice(["mail.ru"] + ["mailinator.com"] * 10) firstName = random.choice(nameWords) lastName = random.choice(surnameWords) avatarSize = 100 gravatarUrl = "http://www.gravatar.com/avatar/" + hashlib.md5( email.lower()).hexdigest() + "?" gravatarUrl += "d=identicon&s=100" av = urllib2.urlopen(gravatarUrl) tmpFile = open("tmp", "w") tmpFile.write(av.read()) tmpFile.close() av = open("tmp", "r") av = File(av) usr = User(username=username, password=password, email=email, first_name=firstName, last_name=lastName) usr.save() usrAccount = UserAccount(user=usr, avatar=av, rating=random.randint(1, 10)) usrAccount.save() av.close() if i % 5 == 0: print i
def test_reg(req): if req.method == "POST": name = req.POST['name'].strip() pwd = req.POST['password'].strip() email = req.POST['email'].strip() if name and pwd and email: rf = RegForm({'name': name, 'password': pwd, 'email': email}) if rf.is_valid(): if User.objects.filter(name = name).count() == 0: u = User(name = name, email = email, password = hashlib.sha1(pwd).hexdigest(), reg_date = datetime.datetime.now(), raiting = 0) u.save() req.session['name'] = u.id return HttpResponse('{"status": "ok"}') else: return HttpResponse('{"status": "error", "code": "1"}') else: return HttpResponse('{"status": "error", "code": "2"}') #Uncorrect data return HttpResponse('{"status": "error", "code": "3"}') # Other error
def test_question_new_answer_event(self): user = User({"username": "******", "ext_id": "test"}) user.save() other_user = User({"username": "******", "ext_id": "other"}) other_user.save() p = Question({ "title": "test title", "body": "test body, needs to be long", "tags": ["test-tag", "test-tag2"], "author_id": user._id }) p.save() self.run_tasks() Event.destroy_all() a = p.create_answer({ "body": "this is a self-answer, should not generate events", "author_id": user._id }) a.save() self.run_tasks() events = user.get_new_events() self.assertEqual(events.count(), 0) a = p.create_answer({ "body": "this is an answer by somebody else", "author_id": other_user._id }) a.save() self.run_tasks() events = user.get_new_events() self.assertEqual(events.count(), 1) event: QuestionNewAnswerEvent = events[0] self.assertEqual(event.question_id, p._id) self.assertEqual(event.answer_id, a._id) self.assertEqual(event.author_id, other_user._id)
def test_post_comment_event(self): user = User({"username": "******", "ext_id": "test"}) user.save() other_user = User({"username": "******", "ext_id": "other"}) other_user.save() p = Question({ "title": "test title", "body": "test body, needs to be long", "tags": ["test-tag", "test-tag2"], "author_id": user._id }) p.save() self.run_tasks() Event.destroy_all() c = p.create_comment({ "body": "this is a self-comment, should not generate events", "author_id": user._id }) c.save() self.run_tasks() events = user.get_new_events() self.assertEqual(events.count(), 0) c = p.create_comment({ "body": "this is a real comment, should generate an event", "author_id": other_user._id }) c.save() self.run_tasks() events = user.get_new_events() self.assertEqual(events.count(), 1) event: PostNewCommentEvent = events[0] self.assertEqual(event.post_id, p._id) self.assertEqual(event.comment_id, c._id) self.assertEqual(event.author_id, other_user._id)
def test_tag_new_post_event(self): u = User({"username": "******", "ext_id": "test"}) u.save() u.subscribe_to_tag("test-tag") u.subscribe_to_tag("test-tag2") u.subscribe_to_tag("test-tag3") p = Question({ "title": "test title", "body": "test body, needs to be long", "tags": ["test-tag", "test-tag2"], "author_id": u._id }) p.save() self.run_tasks() events = u.get_new_events() self.assertEqual(events.count(), 0) other_user = User({"username": "******", "ext_id": "other"}) other_user.save() p = Question({ "title": "test title", "body": "test body, needs to be long", "tags": ["test-tag", "test-tag2"], "author_id": other_user._id }) p.save() self.run_tasks() events = u.get_new_events() self.assertEqual(events.count(), 1) event: TagNewQuestionEvent = events[0] # only subscribed tags are listed in event self.assertCountEqual(event.tags, ["test-tag", "test-tag2"]) self.assertEqual(event.question_id, p._id)
class HTTPAPITestCase(MongoMockTest): @classmethod def setUpClass(cls) -> None: force_init_app() super().setUpClass() User.ensure_indexes() cls.app = app def setUp(self) -> None: User.destroy_all() self.user1 = User({"username": "******", "ext_id": "user1"}) self.user1.save() self.user1.create_auth_token() self.user2 = User({"username": "******", "ext_id": "user2"}) self.user2.save() self.user2.create_auth_token() self.moderator = User({ "username": "******", "ext_id": "mod", "moderator": True }) self.moderator.save() self.moderator.create_auth_token() @staticmethod def run_tasks(): for task in ctx.queue.tasks: wrk.run_task(task) @staticmethod def clear_task_queue(): for task in ctx.queue.tasks: try: wrk.run_task(task) except: pass @property def client(self): return self.app.flask.test_client() def request(self, method, path, headers=None, user=None, json=None): if headers is None: headers = {} if user is not None: headers["X-Api-Auth-Token"] = user.get_auth_token().token kwargs = {"headers": headers, "method": method} if json is not None: kwargs["json"] = json headers["Content-Type"] = "application/json" return self.client.open(path, **kwargs) def get(self, path, user=None): return self.request("GET", path, user=user) def post(self, path, user=None, json=None): return self.request("POST", path, user=user, json=json) def patch(self, path, user=None, json=None): return self.request("PATCH", path, user=user, json=json) def put(self, path, user=None, json=None): return self.request("PUT", path, user=user, json=json) def delete(self, path, user=None, json=None): return self.request("DELETE", path, user=user, json=json)
def handle(self, *args, **options): for i in range(10): user = User(username=self.text_gen(), password=self.text_gen(100) + "?") user.save() self.stdout.write(self.style.SUCCESS('Successfully created user ' + user.username + ' with pass' + user.password))