class MyTestCase(unittest.TestCase): """ Simple Test """ def setUp(self): """ Hook method for setting up the test fixture before exercising it. """ self.account_data = {"id": "1", "name": "test"} mock_data_interface = Mock() mock_data_interface.get_id.return_value = '1' mock_data_interface.get_name.return_value = 'test' mock_data_interface.get.side_effect = AccountException() self.account = Account(mock_data_interface) def test_account_returns_data_for_id(self): """ Simple Test for ID """ self.assertEqual(self.account_data["id"], self.account.get_account_id()) def test_account_returns_data_for_name(self): """ Simple Test for NAME """ self.assertEqual(self.account_data["name"], self.account.get_account_name()) def test_account_when_connect_exception_raised(self): """ Raises Exception """ self.assertEqual("Connection error occurred", self.account.get_account())
def test_from_pk(self): result = Account.from_pk(jimid) self.assertIsInstance(result, Account, "from_pk returns an instance of an account") self.assertEqual(result.email, "*****@*****.**") self.assertIsNone(Account.from_pk(0), "from_pk returns None for bad pk")
def test_account_conn_exception(self): mock_data_interface = Mock() mock_data_interface.get.side_effect = ConnectionError() # mock_data_interface.wibble_list = ['wibble', 'wobble'] account = Account(mock_data_interface) self.assertEqual("Connection error occurred. Try Again.", account.get_account(1))
def test_login_attempt(self): result = Account.from_pk(jimid) result.set_password("password") result.save() test = Account.login_attempt("JimmyLove", "password") self.assertIsNotNone(test, "login should work with the username & password")
def filter_byAgeGap(age_gap, ids, sort=False, tags: list = []): selector = { "user": { "$in": ids }, "$and": [{ "$where": "this.tags.length >= 5" }, { "$where": "this.images.length >= 1" }, { "$where": "this.gender != '%s'" % Account.GENDER_UNSET }, { "$where": "this.biography.length >= 25" }] } if age_gap >= 0: curr = Account.get({"user": current_user._id}, {"dob": 1})["dob"] min = curr - relativedelta.relativedelta(years=int(age_gap)) max = curr + relativedelta.relativedelta(years=int(age_gap)) selector = {**selector, **{"dob": {"$lte": max, "$gte": min}}} if tags: selector = {**selector, **{"tags": {"$all": tags}}} ret = Account.get(selector, {"user": 1, "class": 1, "dob": 1}) if not ret: return [] if not isinstance(ret, list): ret = [ret] if sort: ret.sort(key=lambda x: x.age(), reverse=True) ret = [x.user for x in ret] return ret
def test_withdraw(self): # Given account = Account(Decimal(100)) amount = Decimal(10) # When account.withdraw(amount) # Then assert account.balance == Decimal(90)
def viewapikey(name, password): if not Account.login(name, password): msg = "Invalid login credentials, pls retry" else: pk = Account.login(name, password).pk retrieve_ak = Account(pk=pk) msg = "Your API Key = {}".format(retrieve_ak.get_account().api_key) return jsonify({'message': msg})
def test_get_current_balance_returns_data_correctly(self, mock_requests): mock_response = Mock() mock_response.status_code = 200 mock_response.text = 'Some text data' mock_requests.get.return_value = mock_response account = Account(Mock()) self.assertEqual({'status': 200, 'data': 'Some text data'}, account.get_current_balance('1'))
def balance(api_key): if Account.api_authenticate(api_key) == None: msg = "Invalid login credentials, pls retry" else: pk = Account.api_authenticate(api_key).pk retrieve_bal = Account(pk=pk) msg = "Your current balance = {}".format(retrieve_bal.get_account().balance) return jsonify({'message':msg})
def setUp(self): """ Hook method for setting up the test fixture before exercising it. """ self.account_data = {"id": "1", "name": "test"} mock_data_interface = Mock() mock_data_interface.get_id.return_value = '1' mock_data_interface.get_name.return_value = 'test' mock_data_interface.get.side_effect = AccountException() self.account = Account(mock_data_interface)
def buy(key, ticker, shares): if Account.api_authenticate(key) == None: msg = "Invalid login credentials, pls retry" else: #pk = Account.login(name, password).pk pk = Account.api_authenticate(key).pk buy_txn = Account(pk=pk) msg = buy_txn.buy(ticker, shares) return jsonify({'message': msg})
def test_update(self): #Tests Save - update function result = Account.from_pk(jimid) result.balance = 100 result.save() result = Account.all() #using the all fucntion to count rows in DB self.assertEqual( result[0].balance, 100, "all func populates attributes, checking updated first for row[0] / pk1" )
def create(): if not request.json or 'username' not in request.json or 'password_hash' not in request.json: return jsonify(BAD_REQUEST), 401 account = Account(username=request.json['username'], password_hash=request.json['password_hash']) account.save() token = encodeAuthToken(account.pk) return jsonify({'status': 'success', 'auth_token': str(token)})
def admin_leaderboard(): print('Terminal Trader Leaderboard\n') accounts = Account.all() account_username_pk_list = [] for account in accounts: account_username_pk_list.append( [account, account.pk, account.username]) for item in account_username_pk_list: Account.leaderboard_stats_by_acct(item[0], item[1], item[2])
def viewbalance(name, password): if not Account.login(name, password): msg = "Invalid login credentials, pls retry" else: pk = Account.login(name, password).pk retrieve_bal = Account(pk=pk) msg = "Your current balance = {}".format( retrieve_bal.get_account().balance) return jsonify({'message': msg})
def sell(api_key): if Account.api_authenticate(api_key) == None: msg = "Invalid login credentials, pls retry" else: if not request.json or 'ticker' not in request.json or 'volume' not in request.json: return jsonify({"error": "bad request"}), 400 pk = Account.api_authenticate(api_key).pk sell_txn = Account(pk=pk) msg = sell_txn.sell(request.json['ticker'], request.json['volume']) return jsonify({'message':msg})
def test_current_balance(self, mock_requests): # mock_the thing we patched mock_response = Mock() mock_response.status_code = 200 mock_response.text = 'any old text' mock_requests.get.return_value = mock_response account = Account(Mock()) self.assertEqual({ 'status': 200, 'data': 'any old text' }, account.get_current_balance('1'))
def sell(name, password, ticker, shares): if not Account.login(name, password): msg = "Invalid login credentials, pls retry" else: pk = Account.login(name, password).pk sell_txn = Account(pk=pk) # sell_txn.sell(ticker, shares) # msg = "Sell transaction complete" msg = sell_txn.sell(ticker, shares) return jsonify({'message': msg})
def buy(name, password, ticker, shares): if not Account.login(name, password): msg = "Invalid login credentials, pls retry" else: pk = Account.login(name, password).pk buy_txn = Account(pk=pk) # buy_txn.buy(ticker, shares) # msg = "Buy transaction complete" msg = buy_txn.buy(ticker, shares) return jsonify({'message': msg})
def test_get_current_balance_returns_data_correctly(self, mock_requests): mock_response = Mock() mock_response.status_code = 200 mock_response.text = 'Some text data' mock_requests.get.return_value = mock_response account = Account(Mock()) self.assertEqual({ 'status': 200, 'data': 'Some text data' }, account.get_current_balance('1'))
def test_add_account(self): bank = Bank() account_1 = Account("001", 50) account_2 = Account("002", 100) bank.add_account(account_1) bank.add_account(account_2) self.assertEqual(len(bank.accounts), 2)
def login_menu(): while True: try: user_input = view.login_menu() if int(user_input) == 3: view.program_end() sys.exit() elif int(user_input) == 2: username = view.username_inpt() pwd = util.hash_pass(view.password_inpt()) user = Account.login(username, pwd) if user == None: view.invalid_info() return login_menu() return user elif int(user_input) == 1: user = Account() user.username = view.username_inpt() user.set_password(util.hash_pass(view.set_password_inpt())) user.balance = view.deposit_inpt() user.save() view.acc_created(user.username) return user except ValueError: view.choose_valid()
def positions_sub_menu(pk): retrieve_bal = Account(pk=pk) views.generic_msg("Your current balance = {}".format( retrieve_bal.get_account().balance)) while True: position_choice = views.position_menu() if position_choice is None: #Bad input views.generic_msg( "Please enter a number that corresponds to a stated option") elif position_choice == 3: #Exit break elif position_choice == 1: #Retrieve and display a given position ticker = views.get_input("Please enter a Ticker Symbol") user_position = Account(pk=pk) position = user_position.get_position_for(ticker) valuation = Position() getval = valuation.current_value(ticker, position.shares) views.show_positions(position, getval) elif position_choice == 2: #Retrieve and display all positions user_positions = Account(pk=pk) positions = user_positions.get_positions() for position in positions: valuation = Position() getval = valuation.current_value(position.ticker, position.shares) views.show_positions(position, getval)
def test_user_can_deposit(self): # Arrange account = Account("Alan", "33") expected_result = 100 # Act account.deposit(100) observed = account.balance # Assert self.assertEqual(observed, expected_result)
def test_user_can_withdraw_amount_not_in_account(self): # Arrange account = Account("Alan", "33") account.balance = 100 expected_result = "Sorry insufficent funds" # Act observed = account.withdraw(101) # Assert self.assertEqual(observed, expected_result)
def account_create(): username, password, f_name, l_name, deposit = view.create_account( ) #takes all return values from create_account crypted_password = crypt_password(password) new_account = Account(username=username, crypted_password=crypted_password, f_name=f_name, l_name=l_name, balance=deposit) new_account.save()
def positions(api_key, ticker): if Account.api_authenticate(api_key) == None: msg = "Invalid login credentials, pls retry" else: pk = Account.api_authenticate(api_key).pk user_position = Account(pk=pk) position = user_position.get_position_for(ticker) valuation = Position() getval = valuation.current_value(ticker, position.shares) msg = "Ticker Symbol: {}, Shares: {}, Valuation: ${}".format(position.ticker, position.shares, getval) return jsonify({'message':msg})
def login_account(): loginaccount = Account() view.enter_user_name() username = input() view.enter_password() password = getpass.getpass() enteraccount = loginaccount.login(username, password) if enteraccount is None: view.login_failed_message() return login_menu() elif enteraccount is not None: return main_menu(enteraccount)
def test_get_account_returns_data_for_id_1(self): account_data = {"id": "1", "name": "test"} # we can Mock external dependencies ssuch as services, API endpoints etc. mock_data_interface = Mock() mock_data_interface.get.return_value = account_data # use the mock as we instantiate an Account account = Account(mock_data_interface) # now make a unittetst asertion # wrong = {"id":"2", "name":"test"} # this fails the test! # self.assertDictEqual( wrong, account.get_account(1) ) self.assertDictEqual(account_data, account.get_account(1)) # this passes the test
def positions(name, password, ticker): if not Account.login(name, password): msg = "Invalid login credentials, pls retry" else: pk = Account.login(name, password).pk user_position = Account(pk=pk) position = user_position.get_position_for(ticker) valuation = Position() getval = valuation.current_value(ticker, position.shares) msg = "Ticker Symbol: {}, Shares: {}, Valuation: ${}".format( position.ticker, position.shares, getval) return jsonify({'message': msg})
def test_user_can_withdraw_amount_in_account(self): # Arrange account = Account("Alan", "33") account.balance = 200 expected_result = 100 # Act account.withdraw(100) observed = account.balance # Assert self.assertEqual(observed, expected_result)
def test_account_when_connect_exception_raised(self): mock_data_interface = Mock() mock_data_interface.get.side_effect = ConnectionError() account = Account(mock_data_interface) self.assertEqual("Connection error occurred. Try Again.", account.get_account(1))
def test_account_returns_data_for_id_1(self): account_data = {"id": "1", "name": "test"} mock_data_interface = Mock() mock_data_interface.get.return_value = account_data account = Account(mock_data_interface) self.assertDictEqual(account_data, account.get_account(1))