def test_referrals(referrals): A = User(0) B = User(1) Referral().set_referral(referee=B, referrer=A) assert len(Referral.referrals) == 1
def addUser(self, email, password, join_date, verified): hashed = bcrypt.hashpw(password, bcrypt.gensalt(1)) user = User(email = email, password = hashed, join_date = join_date, verified = verified) user.put()
def quit(self): global a a=a+1 print(" THANK YOU ") from main import User user1=User() user1.customer(CusId)
def test_find_user_by_student_num(): me = InventoryManager() bill = User("*****@*****.**", 123456789) shaquiffa = User("*****@*****.**", 987654321) assert me.find_user_by_student_num(123456789) == bill assert me.find_user_by_student_num(987654321) == shaquiffa
def test_user_refer_a_referrer_with_referees(referrals): A = User(0) B = User(1) C = User(2) Referral().set_referral(referee=B, referrer=A) Referral().set_referral(referee=A, referrer=C) assert len(Referral.referrals) == 2
def test_user_refer_his_referrer(referrals): A = User(0) B = User(1) Referral().set_referral(referee=B, referrer=A) with pytest.raises(CircularRefer): Referral().set_referral(referee=A, referrer=B) assert len(Referral.referrals) == 1
def test_account_exist(self): ''' method to check whether the account details of the User exist ''' self.new_user.save_user_info() test_user = User("Twitter", "Diane", "dee420") test_user.save_user_info() user_exists = User.account_exists("Twitter") self.assertTrue(user_exists)
def test_find_by_account_name(self): ''' Test case to test whether a user can find their account by account_name ''' self.new_user.save_user_info() test_user = User("Twitter", "Diane", "dee420") test_user.save_user_info() user_found = User.find_by_account_name("Twitter") self.assertEqual(user_found.username, test_user.username)
def test_user_refer_a_user_with_referrer(referrals): A = User(0) B = User(1) C = User(2) Referral().set_referral(referee=B, referrer=A) with pytest.raises(RefereeIsAlreadyReferred): Referral().set_referral(referee=B, referrer=C) assert len(Referral.referrals) == 1
def test_add_user_post(self): params = {} params['first_name'] = 'tanawat' params['last_name'] = 'khunlertkit' params['username'] = '******' u_list_before = User.query().fetch() response = self.testapp.post('/user', params) u_list_after = User.query().fetch() u_list = User.query(User.username == 'sdfads').fetch() self.assertEqual(1, len(u_list_after) - len(u_list_before)) self.assertEqual(u_list[0].username, 'sdfads') print response
def test_add_user_post(self): params = {} params["first_name"] = "tanawat" params["last_name"] = "khunlertkit" params["username"] = "******" u_list_before = User.query().fetch() response = self.testapp.post("/user", params) u_list_after = User.query().fetch() u_list = User.query(User.username == "sdfads").fetch() self.assertEqual(1, len(u_list_after) - len(u_list_before)) self.assertEqual(u_list[0].username, "sdfads") print response
def test_delete_user(self): ''' Method to test whether we can delete a user from our user's list ''' self.new_user.save_user() test_user = User("Jadiel", "Muriithi", "0727867684", "*****@*****.**", "sirmwas", "101010") #new user test_user.save_user() self.new_user.delete_user() #Deleting a user self.assertEqual(len(User.user_list), 1)
def generate_users(n): users = list() for i in range(n): user = User(faker.name()) user.username = faker.name() user.password = "******" try: db.session.add(user) db.session.commit() users.append(user) except Exception as e: log.error("Fail to add user %s: %s" % (str(user), e)) db.session.rollback() return users
def test_db_read_write(client): assert User.query.filter_by(user_id=test_user_id).first() == None db.session.add( User(user_id=test_user_id, user_name=test_user_name, user_password=test_user_password)) db.session.commit() assert User.query.filter_by(user_id=test_user_id).first() != None assert Thread.query.filter_by(thread_id=test_thread_id).first() == None db.session.add( Thread(thread_id=test_thread_id, thread_name=test_thread_name)) db.session.commit() assert Thread.query.filter_by(thread_id=test_thread_id).first() != None assert Subscription.query.filter_by( subscription_id=test_subscription_id).first() == None db.session.add( Subscription(subscription_id=test_subscription_id, user_id=test_user_id, thread_id=test_thread_id)) db.session.commit() assert Subscription.query.filter_by( subscription_id=test_subscription_id).first() != None delete_subscription(test_subscription_id) delete_user(test_user_id) delete_thread(test_thread_id)
def test_circular_refer_with_four_levels(referrals): A = User(0) B = User(1) C = User(2) D = User(3) users = [A, B, C, D] Referral().set_referral(referee=B, referrer=A) Referral().set_referral(referee=C, referrer=B) Referral().set_referral(referee=D, referrer=C) with pytest.raises(CircularRefer): Referral().set_referral(referee=A, referrer=D) assert len(Referral.referrals) == len(users) - 1
def register(name=None): """ Adds a new user to the wishlist user base""" title="Register" error=None if request.method == "GET": return render_template("register.html",title=title) if request.method == "POST": print "method is post" if request.form['firstname']=="" or request.form['lastname'] =="" or request.form['email']=="" or request.form['password'] =="" or request.form['password_conf'] =="": error="Invalid User Info Supplied" print error else: try: if request.form['password'] !=request.form['password_conf']: error ="passwords dont match" else: created_user = User(request.form['firstname'].upper(),request.form['lastname'].upper(),request.form['email'].lower(),request.form['password'].upper()) conn = sqlite3.connect(app.config['DATABASE']) if conn is not None: cur = conn.cursor() cur.execute("SELECT * from wishlist_users where email=?",(created_user.email)) row = cur.fetchone() if row is None: cur.execute("INSERT INTO wishlist_users (firstname,lastname,email,password) VALUES (?,?,?,?)", (created_user.firstname, created_user.lastname, created_user.email, created_user.password) ) conn.commit() else: raise ValueError print created_user.firstname error= "User Created Successfully! Please go to login page" except: error="Registration Failed" return render_template("register.html",title=title,error=error)
def login(): """ Dummy implementation. The real login is to be implemented by Ben & co :) """ from main import app from main import User if request.method == "POST": # get parameters data = request.get_json(force=True) username = data.get('username') password = data.get('password') user = User.check_password(username, password) if user is not None: # remember=True means that the session will remember a user. # If not set, the user will be deleted from the session once the browser tab is closed login_user(user, remember=True) return jsonify({'status': 'success', 'user_data': user.to_json()}) else: # what if connection to LDAP failed? return jsonify({ 'status': 'error', 'error': 'Incorrect username or password' }) # if GET, return index.html return app.send_static_file('index.html')
def test_sign_out(): me = InventoryManager() user_a = User("*****@*****.**", 12344) user_b = User("*****@*****.**", 12344) bin_a = Bin("A1", 12345) bin_b = Bin("B1", 41325) part_a = Part("motor", 2, "1j343g", bin_a.id) part_b = Part("sensor", 10, "4h935y", bin_b.id) me.sign_out(part_a, 2, user_a) assert bin_a.qty_in_bin == 0 assert len(me.logs) == 1 me.sign_out(part_b, 4, user_b) assert bin_b.qty_in_bin == 6 assert len(me.logs) == 2
class TestUserClass(TestCase): def setUp(self): try: self.new_user = User("Thegaijin") except NameError as e: raise 'Check the class name and try again' def test_User_instance(self): self.assertIsInstance( self.new_user, User, msg='The object should be an instance of the User class') def test_number_of_arguments_passed_to_object(self): self.assertRaises(TypeError, self.new_user, 'Thegaijin') def test_argument_data_types_for_User(self): self.assertIsInstance(self.new_user.user_name, str, msg="Argument should be a string") def test_if_class_has_add_skills_method(self): getattr(User, 'add_skills', 'None') def test_argument_data_types_for_add_skills_function(self): add_skills_call = self.new_user.add_skills(['Python', 'JavaScript']) self.assertEqual(type(add_skills_call), list)
def testLoginHandlerCookieFaculty(self, mock): user = User() user.Fname = "Matt" user.Lname = "K" user.email = "*****@*****.**" user.password = "******" user.isInstructor = True main.u = user user.put() request = webapp2.Request.blank('/login') request.cookies['uname'] = "*****@*****.**" response = request.get_response(main.app) mock.assert_called_with('Faculty_landing.html')
def create_user(): try: app.users.append(User(**user_schema.load(request.json))) response.status = 201 return user_schema.dumps(app.users[-1]) except ValidationError as error: response.status = 400 return {"error": str(error)}
def create_user(): db.create_all() admin = User(id=0, username='******', password_hash= pwd_context.encrypt("admin")) print("Created user") print("Login: admin") print("Password: admin") db.session.add(admin) db.session.commit()
def test_get_photos(self): self.assertListEqual(User.get_photos(self, top_10_users=[1]), [{'first_name': 'Pavel', 'id': 1, 'last_name': 'Durov', 'url': ['https://sun9-42.userapi.com/c9591/u00001/136592355/w_818d6f79.jpg', 'https://sun9-42.userapi.com/c9591/u00001/136592355/w_f6a60338.jpg', 'https://sun9-3.userapi.com/c7003/v7003978/1ed9/yoeGXOWmW-M.jpg']}])
def setUp(self): db.create_all() db.session.add( User(id=1, Name="", Email="*****@*****.**", Username="******", Password="******")) db.session.commit()
def get(self): q = User.all() results = [{'username':u.username, 'email':u.email, 'reply_mode':u.reply_mode, 'last_run':u.last_run.strftime('%Y-%m-%dT%H:%M:%SZ'), 'digest': u.digest} for u in q] template_values = { 'users': results, 'count': len(results) } path = os.path.join(os.path.dirname(__file__), 'stats.html') self.response.out.write(template.render(path, template_values))
def get(self): q = User.all() results = [{'ff_user':u.ff_user, 'last_sync':u.last_sync.strftime('%Y-%m-%dT%H:%M:%SZ')} for u in q] template_values = { 'users': results, 'count': len(results) } path = os.path.join(os.path.dirname(__file__), 'stats.html') self.response.out.write(template.render(path, template_values))
def setUp(self): class TestConfig(object): SQLALCHEMY_DATABASE_URI = 'sqlite://' DEBUG = True TESTING = True app.config.from_object(TestConfig()) self.app = app with self.app.test_request_context(): db.create_all() raw_users = [ { 'username': '******', 'email': '*****@*****.**', 'password': '******' }, { 'username': '******', 'email': '*****@*****.**', 'password': '******' }, { 'username': '******', 'email': '*****@*****.**', 'password': '******' } ] raw_groups = [ { 'name': 'group1' }, { 'name': 'group2' }, { 'name': 'group3' } ] for user in raw_users: password = user.pop('password') user = User(**user) user.set_password(password) user.save() for group in raw_groups: Group(**group).save()
def test_circular_refer_with_thousand_levels(referrals): users = [User(i) for i in range(1000)] [ Referral().set_referral(referee=users[i + 1], referrer=users[i]) for i in range(len(users)) if i < len(users) - 1 ] with pytest.raises(CircularRefer): Referral().set_referral(referee=users[0], referrer=users[-1])
def get_users(from_path): users = [] with open(from_path, 'r') as file: for row in csv.reader(file): user_id = int(row[0]) username = row[1] member_since = datetime.strptime( row[2], '%Y-%m-%d') if row[2] is not '' else None users.append(User(user_id, username, member_since)) return sorted(users, key=lambda u: u.id)
def addFarm(): farm = User(farmname=user['farmname'], address=user['coordinates'], farmtype=user['farmtype'], about=user['about'], username=user['username'], password=user['password'], date_created=user['date']) db.session.add(farm) db.session.commit()
def test_post(self): self.giveUser() me = User.ensure_current() self.assertEquals(0, Reflect.count_for(me)) request = webapp2.Request.blank('/reflect', POST='{"note":"Hello","source":"http://google.com/"}') request.method = "PUT" request.content_type = "application/json" response = request.get_response(main.app) self.assertEquals(response.status_int, 200) self.assertEquals(1, Reflect.count_for(me)) json.loads(response.body)
def test_get_user_info(self): user = User(name='Vladimir', age=34) db.session.add(user) db.session.commit() with app.test_client() as client: response = json.loads(client.get('/user').data.decode('utf-8')) first = response[0] self.assertEqual(first['name'], user.name) self.assertEqual(first['age'], user.age) self.assertIsNotNone(first['register_date']) self.assertIsNotNone(first['last_activity'])
def testSignUpHandlerBADSTUDENTPost2(self, mock): # Arrange: Make the web request with all of the necessary information. test_user = User() test_user.email = "*****@*****.**" test_user.password = "******" test_user.put() test_request = webapp2.Request.blank('/signup', POST={ "firstname": "TESTFIRST", "lastname": "TESTLAST", "email": "*****@*****.**", "password": "******", "b9": "COMPSCI101" }) main.isInstructor = False test_request.method = 'POST' mock.return_value = None # Act response = test_request.get_response(main.app) # Assert: Inspect the response self.assertTrue(main.error != '') mock.assert_called_with('/signup')
def insertar(numero): print("va a isertar el dato") user4 = User(username='******' + str(numero)) db.session.add(user4) try: db.session.commit() except: db.session.rollback() raise finally: db.session.close() # optional, depends on use case
class TestUser(unittest.TestCase): ''' Test class that defines test cases for the User class behaviours ''' def setUp(self): ''' This method runs each time before every test case. ''' self.new_user = User("Slack", "Ayebale Nelly Abigail", "password123") def tearDown(self): ''' This method runs each time after every test case. ''' User.user_list = [] def test_init(self): """ Method to test if the ojects have been initalized properly. """ self.assertEqual(self.new_user.account_name, "Slack") self.assertEqual(self.new_user.username, "Ayebale Nelly Abigail") self.assertEqual(self.new_user.password, "password123") def test_save_user_info(self): ''' Test case to test if accounts are being saved to the userlist. ''' self.new_user.save_user_info() self.assertEqual(len(User.user_list), 1) def test_find_by_account_name(self): ''' Test case to test whether a user can find their account by account_name ''' self.new_user.save_user_info() test_user = User("Twitter", "Diane", "dee420") test_user.save_user_info() user_found = User.find_by_account_name("Twitter") self.assertEqual(user_found.username, test_user.username) def test_account_exist(self): ''' method to check whether the account details of the User exist ''' self.new_user.save_user_info() test_user = User("Twitter", "Diane", "dee420") test_user.save_user_info() user_exists = User.account_exists("Twitter") self.assertTrue(user_exists) def test_display_accounts(self): ''' Test case to test whether the accounts can be displayed ''' self.assertEqual(User.display_accounts(), User.user_list)
def test_delete(self): self.giveUser() me = User.ensure_current() toput = Reflect(parent=me, source="http://example.com", note="Hello") toput.put() self.assertEquals(1, Reflect.count_for(me)) request = webapp2.Request.blank('/reflect?id=%s' % str(toput.key())) request.method = "DELETE" response = request.get_response(main.app) self.assertEquals(response.status_int, 200) self.assertEquals(0, Reflect.count_for(me)) json.loads(response.body)
def test_return_part(): me = InventoryManager() bin = Bin("C1", 123456) part = Part("wloo cs coop", 10, "kljhee", bin.id) user = User("*****@*****.**", 59487162) me.sign_out(part, 8, user) me.return_part(part, 4, user) assert bin.qty_in_bin == 6 assert len(me.logs) == 4 me.return_part(part, 2, user) assert bin.qty_in_bin == 8 assert len(me.logs) == 5
def main(): user = User('John', 'password', '*****@*****.**', '12/25/1999') print(user.username) print(user.password) print(user) print() print(repr(user)) user2 = User("John", "password", "*****@*****.**", "12/25/1999") print(user == user2) print(user.check_password('1234')) user.username = '******' print(user.username) superuser = SuperUser('jon', 'password', '*****@*****.**', '12/24/1999', 'admin') print(superuser) print() print(repr(superuser)) print('ran demo.main')
def test_add_item_to_user(self): u = User(first_name="tanawat", last_name="khunlertkit", username="******") item = Item(name="car") self.assertTrue(u.add_to_datastore()) item.put() u.add_item(item) self.assertFalse(u.add_to_datastore()) self.assertEqual(1, len(Item.query().fetch())) u_list = User.query(User.username == "tanawat").fetch() self.assertEqual(1, len(u_list)) self.assertEqual(1, len(u_list[0].items))
def test_add_duplicate(self): u = User(first_name='A', last_name='B', username='******') u.put() self.assertEqual(len(User.query().fetch()), 1) item = Item(name='car') res = u.add_item(item) expected = 'added item car to user C' self.assertEqual(res, expected) res = u.add_item(item) expected = 'C already has car' self.assertEqual(res, expected)
def get(self): from main import User, Page, get_hash max_check = 100 max_tweet = 1 if self.is_developer(): max_check = 1 visited_users = set() visited_page = 0 tweet_made = 0 conti = True for page in Page.all().order('modified'): if not conti: break self.debug('%d-th page' % visited_page) user_id, url = page.key().name().split() self.debug('Page(user=%s, url=%s)' % (user_id, url)) if user_id in visited_users: self.debug("don't tweet more than once from a user per a cron job.") continue visited_page += 1 if visited_page == max_check: self.debug('will be the last to process') conti = False content = get_hash(url) if content != '' and page.content != content: page.content = content self.tweet(User.get_by_key_name(user_id), url) tweet_made += 1 if tweet_made == max_tweet: self.debug('the last to tweet') conti = False visited_users.add(user_id) else: self.debug('no update detected in %s' % url) page.put() else: self.debug('checked all pages. terminate.') return self.debug('processed %d pages, tweeting %d times. terminate.' % (visited_page, tweet_made))
def test_add_duplicate_person_to_datastore(self): u = User(first_name="tanawat", last_name="khunlertkit", username="******") u.put() u.put() self.assertEqual(1, len(User.query().fetch()))
def test_add_person_to_datastore(self): u = User(first_name='tanawat', last_name='khunlertkit', username='******') u.put() self.assertEqual(1, len(User.query().fetch()))