コード例 #1
0
def test_referrals(referrals):
    A = User(0)
    B = User(1)

    Referral().set_referral(referee=B, referrer=A)

    assert len(Referral.referrals) == 1
コード例 #2
0
ファイル: main_test.py プロジェクト: guberti/epschedule
 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()
コード例 #3
0
	def quit(self):
                global a
                a=a+1
                print("                                         THANK YOU                                               ")
		from main import User
		user1=User()
                user1.customer(CusId)
コード例 #4
0
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
コード例 #5
0
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
コード例 #6
0
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
コード例 #7
0
    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)
コード例 #8
0
    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)
コード例 #9
0
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
コード例 #10
0
	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
コード例 #11
0
 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
コード例 #12
0
ファイル: test.py プロジェクト: jadielmwangi/Accounts-App
    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)
コード例 #13
0
ファイル: test_data.py プロジェクト: SgtSteiner/flask_portal
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
コード例 #14
0
ファイル: test_main.py プロジェクト: Otterwerks/Chatterwerks
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)
コード例 #15
0
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
コード例 #16
0
ファイル: routes.py プロジェクト: Nishka/info3180-project3_4
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)
コード例 #17
0
ファイル: login.py プロジェクト: JoschuaL/Stammtisch-Tool
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')
コード例 #18
0
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
コード例 #19
0
ファイル: test_main.py プロジェクト: kjovan27/Fancy_Tracker
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)
コード例 #20
0
ファイル: testLoginHandler.py プロジェクト: DrewB123/FAQMan
 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')
コード例 #21
0
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)}
コード例 #22
0
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()
コード例 #23
0
 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']}])
コード例 #24
0
 def setUp(self):
     db.create_all()
     db.session.add(
         User(id=1,
              Name="",
              Email="*****@*****.**",
              Username="******",
              Password="******"))
     db.session.commit()
コード例 #25
0
ファイル: admin.py プロジェクト: crtr0/Twitter2Mail
 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))
コード例 #26
0
ファイル: admin.py プロジェクト: crtr0/FF2Disqus
 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))
コード例 #27
0
ファイル: test.py プロジェクト: honmaple/flask-maple
    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()
コード例 #28
0
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])
コード例 #29
0
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)
コード例 #30
0
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()
コード例 #31
0
ファイル: test_hello.py プロジェクト: omo/habitalt
 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)        
コード例 #32
0
    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'])
コード例 #33
0
    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')
コード例 #34
0
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
コード例 #35
0
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)
コード例 #36
0
ファイル: test_hello.py プロジェクト: omo/habitalt
    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)
コード例 #37
0
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
コード例 #38
0
ファイル: demo.py プロジェクト: djour/pythonObjects
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')
コード例 #39
0
 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))
コード例 #40
0
ファイル: test.py プロジェクト: tkhunlertkit/python-unit-test
	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)
コード例 #41
0
	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))
コード例 #42
0
 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()))
コード例 #43
0
	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()))