def __init__(self): self.ef = EventFormatter() self.requests_session = None self.account_manager = AccountManager() data = self._parse_user_data() self.init_session(data) self.introduce()
def test_add_new_account_to_config(self): # '__add_new_account_to_config' must throw an exception if it is fed an account # that does not have a section_id url = 'bb.com' username = '******' password = None new_account = Account(url, username, password) aa = AccountManager() self.assertRaises(TypeError, lambda: aa._AccountManager__add_account_to_config(new_account))
def redirect_login(): username = request.form['username'] password = request.form['password'] account_manager = AccountManager() identity_id = account_manager.signin(username=username, password=password) if identity_id: return redirect(f'/blog?identity_id={identity_id}') else: return redirect('/login')
def test_add_new_account(self): aa = AccountManager() aa.reset_config() url = 'http://myblog.com' username = '******' password = '******' new_account = Account(url, username, password) aa.add_new_account(new_account) accounts = aa._AccountManager__accounts self.assertEquals(accounts[0], Account(url, username, password)) self.assertEqual(len(accounts), 1)
def test_add_new_account_to_config(self): # '__add_new_account_to_config' must throw an exception if it is fed an account # that does not have a section_id url = 'bb.com' username = '******' password = None new_account = Account(url, username, password) aa = AccountManager() self.assertRaises( TypeError, lambda: aa._AccountManager__add_account_to_config(new_account))
def sign_in(self, email, password): """ Helper method sign_in(email, password) signs in with the provided email address and password. """ self.email = email self.click_next() self.password = password self.click_sign_in() # should redirect to Account Manager (home, logged in) page account_manager = AccountManager(self.mozwebqa) account_manager.wait_for_page_to_load() return account_manager
def test_save_accounts_to_file(self): aa = AccountManager() aa.reset_config() self.assertEqual(len(aa.get_accounts()), 1) url = 'http://cheeky.com' username = '******' password = '******' new_account = Account(url, username, password) aa.add_new_account(new_account) self.assertEqual(len(aa.get_accounts()), 2) bb = AccountManager() aa_account = aa.get_accounts()[0] bb_account = bb.get_accounts()[0] self.assertEquals(aa_account, bb_account)
def test_get_account_by_id(self): aa = AccountManager() aa.reset_config() url = 'hi.com' username = '******' password = None new_account = Account(url, username, password) aa.add_new_account(new_account) self.assertEqual(AccountManager.get_default_account(), aa.get_account_by_id(0)) self.assertEqual(new_account, aa.get_account_by_id(1))
def test_retrieving_account_with_None_password(self): aa = AccountManager() aa.reset_config() url = 'aa.com' username = '******' password = None new_account = Account(url, username, password) aa.add_new_account(new_account) aa_retrieved = aa.get_account_by_id(1) self.assertEqual(aa_retrieved.get_url(), 'aa.com') self.assertEqual(aa_retrieved.get_password(), None) bb = AccountManager() # new instance, pulled from config file bb_retrieved = bb.get_account_by_id(1) self.assertEqual(bb_retrieved.get_url(), 'aa.com') self.assertEqual(bb_retrieved.get_password(), None)
def add(what): """ Route to add accounts or persons - /add/person returns a create form for the class Person - /add/account returns a create form for the Account classes """ message = None if request.method == "POST": if what == "person": name = request.form["name"] id_ = request.form["id"] if bank.add_customer(Person(name, id_)): message = "{} has been added".format(name) else: message = "Error: The id '{}' already exists.".format(id_) elif what == "account": acc_type = request.form["type"] balance = float(request.form["balance"]) bank.add_account( AccountManager.make_new_account(acc_type, balance, [])) message = "A new {} has been added".format(acc_type) else: raise "Unknown action" bank.save_data() account_types = [{"id_": "Account"}, {"id_": "SavingsAccount"}] return render_template("add.html", what=what, account_types=account_types, message=message)
def main(): #Configure logging options logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) logging.info("Starting server") #Create config object config = Configuration("/home/orikeidar01/config.json", "anylink") config.database.set_default_table("anylink") #Initiate SFTP server AnylinkServer.allow_reuse_address = True server = AnylinkServer(config.bind_addr, config=config) logging.info("Server is now serving") try: #Start SFTP server thread sftp_thread = threading.Thread(target=server.serve_forever) sftp_thread.start() #Create managers requests_manager = RequestsManager(SFTPHandler) account_manager = AccountManager(config.database) requests_manager.start_scanning() #Inject functions setattr(anylink, "get_account_manager", lambda: account_manager) setattr(anylink, "get_requests_manager", lambda: requests_manager) #Start web server anylink.start_website() except KeyboardInterrupt: server.shutdown()
def test_publish_image(self): Image.set_abs_reference_dir_from_html_file(self.filename) account = AccountManager.get_default_account() tt = Transmitter() tt.set_account(account) image = Image("some <img src='Suzanne.jpg' /> string") before = image.get_remote_src() self.assertEqual(before, None) tt.publish_image(image) after = image.get_remote_src() self.assertNotEqual(after, None)
def test_calculate_interest_rate_account(self): """ Test calculation of interest rate. """ test_account = SavingsAccount(1000, []) today = date.today() test_date = "22-09-23" diff = (date(22, 9, 23) - today).days interest_rate1 = diff * test_account.calculate_daily_interest_rate() interset_rate2 = AccountManager.calculate_interest_rate( test_account, test_date) self.assertEqual(interest_rate1, interset_rate2)
class AccountMetrics: def __init__(self,con): self.account_manager=AccountManager(con) self.security_data=SecurityData(con) def compare_vs_sharpe(self, acct1, acct2, acct2_vals): #acct1=S&P500 (unless comparing against S&P 500, where acct1=4% fixed rate); acct2=strategy acct1_returns = self.all_returns(acct1) acct2_returns = self.all_returns(acct2) acct1_total = sum(acct1_returns) acct2_total = sum(acct2_returns) stdev_val = stdev(acct2_vals) sharpe = (acct2_total - acct1_total) / stdev_val return sharpe def month_returns(self,account_id,as_of_date): my_stocks=self.account_manager.get_holdings(account_id,as_of_date) stock_ids=[ h[0] for h in my_stocks ] stock_returns=self.security_data.get_returns(stock_ids,as_of_date) my_value=0 my_base=0 for i in range(len(my_stocks)): if stock_returns[i] is not None: my_value=my_value+my_stocks[i][1]*(1+stock_returns[i]) else: my_value=my_value+my_stocks[i][1] my_base=my_base+my_stocks[i][1] return (my_value - my_base) def all_returns(self,account_id): dates=self.security_data.get_dates() annual=[] for d in dates: month=self.month_returns(account_id,d) annual.append(month) return annual def show_stats(self,vals): mean_val=mean(vals); variance_val=variance(vals) stdev_val=stdev(vals) mdd_val=mdd(vals) print("Average Return: %s" %mean_val) #print("The variance: %s" %variance_val) #print("The stdev: %s" %stdev_val) print("Maximum drawdown: %s" %mdd_val)
def registerNewAccount(self, firstName, lastName, pesel, monthlyDeposit, current=None): password = self.user_manager.add_user(pesel) if monthlyDeposit < 0: raise Bank.RegistrationError( reson='Invalid monthly deposit value. Must be >= 0.') if monthlyDeposit < self.deposit_breakpoint: acc_type = Bank.AccountType.STANDARD acc = AccountManager(pesel, password, firstName, lastName, monthlyDeposit) else: acc_type = Bank.AccountType.PREMIUM acc = PremiumAccountManager( pesel, password, firstName, lastName, monthlyDeposit, self.currency_tracker.get_currencies, self.currency_tracker.get_exchange_ratio) self.adapter.add( acc, self.communicator.stringToIdentity(pesel + str(acc_type))) self.accounts[pesel] = acc base = current.adapter.createProxy( Ice.stringToIdentity(pesel + str(acc_type))) if acc_type == Bank.AccountType.STANDARD: acc_prx = Bank.AccountPrx.uncheckedCast(base) else: acc_prx = Bank.PremiumAccountPrx.uncheckedCast(base) print('Registered ' + str(acc_type) + ' account for pesel ' + pesel) return Bank.RegistrationResponse(password=password, accountType=acc_type, account=acc_prx)
class TestBank(unittest.TestCase): """ Submodule for unittests, derives from unittest.TestCase. """ src = "static/data/test_data_orig.json" dst = "static/data/test_data.json" def setUp(self): """ Create object for all tests """ # Arrange copyfile(TestBank.src, TestBank.dst) self.bank = AccountManager(TestBank.dst) def tearDown(self): """ Remove dependencies after test """ copyfile(TestBank.src, TestBank.dst) self.bank = None def test_bank_transfer_to_account(self): """ Test transactions (Account). """ imd = ImmutableMultiDict([('from_account', '1'), ('to_account', '2'), ('amount', '100')]) self.bank.transfer(imd) src_account = self.bank.accounts[0] dst_account = self.bank.accounts[1] self.assertEqual(src_account.balance, 900.0) self.assertEqual(dst_account.balance, 1100 - 1) def test_bank_transfer_to_savingsaccount(self): """ Test transactions (SavingsAccount). """ imd = ImmutableMultiDict([('from_account', '2'), ('to_account', '1'), ('amount', '100')]) self.bank.transfer(imd) dst_account = self.bank.accounts[0] self.assertEqual(dst_account.balance, 1100 - 1.3) def test_calculate_interest_rate_account(self): """ Test calculation of interest rate. """ test_account = SavingsAccount(1000, []) today = date.today() test_date = "22-09-23" diff = (date(22, 9, 23) - today).days interest_rate1 = diff * test_account.calculate_daily_interest_rate() interset_rate2 = AccountManager.calculate_interest_rate( test_account, test_date) self.assertEqual(interest_rate1, interset_rate2) def test_add_customer_true_and_attributes(self): """ Test add customer (true) and whether added attributes are correct """ new_person = Person("Nenad", "nen") res = self.bank.add_customer(new_person) self.assertTrue(res) self.assertEqual(self.bank.customers[-1].name, "Nenad") self.assertEqual(self.bank.customers[-1].id_, "nen") def test_add_customer_false(self): """ Test add customer with existing id (false). """ new_person = Person("Martin", "and") res = self.bank.add_customer(new_person) self.assertFalse(res) def test_add_account(self): """ Test add account. """ new_account = Account(5000, []) self.bank.add_account(new_account) self.assertEqual(new_account, self.bank.accounts[-1]) def test_connect_true_and_customer_id(self): """ Test connect customer to account (true) and if correct customer id. """ imd = ImmutableMultiDict([('account', '2'), ('person', 'and')]) self.assertTrue(self.bank.connect(imd)) self.assertTrue("and" in self.bank.accounts[1].holders) self.assertIn("and", self.bank.accounts[1].holders) def test_connect_false(self): """ Test connect existing customer to account as holder (false). """ imd = ImmutableMultiDict([('account', '2'), ('person', 'mar')]) self.assertFalse(self.bank.connect(imd)) self.assertTrue("mar" in self.bank.accounts[1].holders) self.assertIn("mar", self.bank.accounts[1].holders)
class LyXBlogger: VERSION = '0.43' def __init__(self, input_file, display = None): self.__display = display or Display() self.__state = 0 self.__entry = None self.__manager = AccountManager() self.__input_file = input_file def start(self): self.__welcome() self.__entry = ElyxerEntry() self.__entry.load(self.__input_file) self.__ensure_title() self.__display_summary() account = self.__verify_which_account() self.__ensure_password(account) transmitter = self.__manager.pass_transmitter() self.__entry.set_transmitter(transmitter) self.__verify_create_new_or_overwrite() self.__publishing_message(account) self.__entry.publish() self.__closing_remarks() def __verify_which_account(self): dd = self.__display mm = self.__manager recent_id = mm.get_recent_id() while(1): accounts = mm.get_accounts() response_with_case = dd.ask_which_account(accounts, recent_id) response = response_with_case.lower() if response == 'd': account_id = dd.ask_which_account(accounts, True) mm.delete_account_by_id(int(account_id)) elif response == 'n': username = dd.ask_for_new_username() url = dd.ask_for_new_url() password = dd.ask_for_new_password() new_account = Account(url, username, password) mm.add_new_account(new_account) elif response == '': return mm.get_recent_account() elif re.compile('^\d+$').match(response): account_id = int(response) return mm.get_account_by_id(account_id) else: dd.print_unrecognized_response(response_with_case) def __ensure_title(self): if not self.__entry.get_title(): title = self.__display.ask_for_title() self.__entry.set_title(title) def __ensure_password(self, account): if not account.get_password(): temp = self.__display.ask_for_temp_password(account) account.set_temp_password(temp) def __verify_create_new_or_overwrite(self): pass def __welcome(self): self.__display.welcome(LyXBlogger.VERSION) def __closing_remarks(self): self.__display.print_done() def __display_summary(self): self.__display.print_entry_summary(self.__entry) def __publishing_message(self, account): self.__display.print_uploading(account)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Test Bank. """ from account_manager import AccountManager bank = AccountManager() for customer in bank.customers: print(customer.id_, " ", customer.name) for account in bank.accounts: print(account.id_, " ", account.type_, " ", account.balance)
def setUp(self): """ creates object for all tests""" Account.account_number = 1 self.bank = AccountManager()
use_itunes = input("Update iTunes? [y/n] ") == "y" if use_itunes: fix_itunes = input( "Compare iTunes and cached versions of playlists to re-sync (fixes problems from program crash, also reverts user modifications)? [y/n] " ) == "y" else: fix_itunes = False make_m3u = input( "Make m3u files (stored in the playlists folder)? [y/n] ") == "y" verify_path_lengths = input( "Rename files too long to copy to Android? [y/n] ") == "y" copy_to_android = input( "Copy music and playlists to Android Music folder? (Won't waste time overwriting, make sure to enable USB debugging) [y/n] " ) == "y" account_manager = AccountManager(logger) account_manager.login_spotify() deezer_object = Deezer() account_manager.login_deezer(deezer_object) music_directory = str(Path.cwd().parents[0] / "music") youtube_tag_dict = collections.OrderedDict() youtube_manager = YoutubeManager(log_manager, logger, account_manager.spotipy, music_directory, youtube_tag_dict) playlist_manager = PlaylistManager(logger=logger, account_manager=account_manager) if get_user_playlists:
return annual def show_stats(self,vals): mean_val=mean(vals); variance_val=variance(vals) stdev_val=stdev(vals) mdd_val=mdd(vals) print("Average Return: %s" %mean_val) #print("The variance: %s" %variance_val) #print("The stdev: %s" %stdev_val) print("Maximum drawdown: %s" %mdd_val) if __name__=='__main__': con = sqlite3.connect('qse_test.db') my_metrics=AccountMetrics(con) my_manager=AccountManager(con) acct = my_manager.get_accounts() security_data = SecurityData(con) for x in range(len(acct)): account=x+1 rslt=my_metrics.all_returns(account) total=sum(rslt) up_months = 0 down_months = 0 # If you want sharpe ratio to compare S&P 500, create account to assume 4% growth rate and use acct_id as first argument sharpe_rat = my_metrics.compare_vs_sharpe(2, account, rslt) for result in rslt: if result > 0: up_months += 1 else:
from account_manager import AccountManager from account_metrics import AccountMetrics ''' This file sets up a new account for the following trading strategy: Invest a fixed amount (e.g. 100) of fund into 500 randomly chosen securities. At the end of each month, replace the entire holdings in the account by investing the fixed amount of fund to a new set of 500 randomly selected stocks. ''' if __name__=='__main__': con = sqlite3.connect('qse_test.db') security_data = SecurityData(con) account_manager = AccountManager(con) account_metrics = AccountMetrics(con) dates = security_data.get_dates() stock_ids=security_data.get_security() if len(stock_ids)<=500: print "There are insufficient number of securities in the database for this trading strategy." exit(1) new_id=account_manager.new_account() #print new_id rows=[] for d in dates: my_ids=random.sample(stock_ids, 500)
import random from security_data import SecurityData from account_manager import AccountManager from account_metrics import AccountMetrics ''' This file sets up a new account for the following trading strategy: Invest a fixed amount (e.g. 100) of fund into each security in the SP500 index each month. If there are gains for a stock in a month, sell the gain portion to bring the investment in the stock back to the fixed amount for the next month. If there are losses for a stock in a month, add fund for the loss portion to buy the stock to bring the investment to the stock back to the fixed amount for the next month. ''' if __name__=='__main__': con = sqlite3.connect('qse_test.db') security_data = SecurityData(con) account_manager = AccountManager(con) account_metrics = AccountMetrics(con) dates = security_data.get_dates() new_id=account_manager.new_account() print new_id rows=[] for d in dates: sp500_ids=security_data.get_sp500(d) if len(sp500_ids)<500: print("Warning! There are only %s securities on %s" %(len(sp500_ids), d)) for id in sp500_ids: row=[new_id, id, 100, d] rows.append(row) account_manager.add_holdings(rows) account_manager.add_account(new_id,0,"Invest 100 each month in stocks in the SP500 index")
# coding: utf-8 from utils import read_configuration_file from account_manager import AccountManager if __name__ == "__main__": config = read_configuration_file() manager = AccountManager(config['credentials'], config['participant']) manager.run()
class LyXBlogger: VERSION = '0.43' def __init__(self, input_file, display=None): self.__display = display or Display() self.__state = 0 self.__entry = None self.__manager = AccountManager() self.__input_file = input_file def start(self): self.__welcome() self.__entry = ElyxerEntry() self.__entry.load(self.__input_file) self.__ensure_title() self.__display_summary() account = self.__verify_which_account() self.__ensure_password(account) transmitter = self.__manager.pass_transmitter() self.__entry.set_transmitter(transmitter) self.__verify_create_new_or_overwrite() self.__publishing_message(account) self.__entry.publish() self.__closing_remarks() def __verify_which_account(self): dd = self.__display mm = self.__manager recent_id = mm.get_recent_id() while (1): accounts = mm.get_accounts() response_with_case = dd.ask_which_account(accounts, recent_id) response = response_with_case.lower() if response == 'd': account_id = dd.ask_which_account(accounts, True) mm.delete_account_by_id(int(account_id)) elif response == 'n': username = dd.ask_for_new_username() url = dd.ask_for_new_url() password = dd.ask_for_new_password() new_account = Account(url, username, password) mm.add_new_account(new_account) elif response == '': return mm.get_recent_account() elif re.compile('^\d+$').match(response): account_id = int(response) return mm.get_account_by_id(account_id) else: dd.print_unrecognized_response(response_with_case) def __ensure_title(self): if not self.__entry.get_title(): title = self.__display.ask_for_title() self.__entry.set_title(title) def __ensure_password(self, account): if not account.get_password(): temp = self.__display.ask_for_temp_password(account) account.set_temp_password(temp) def __verify_create_new_or_overwrite(self): pass def __welcome(self): self.__display.welcome(LyXBlogger.VERSION) def __closing_remarks(self): self.__display.print_done() def __display_summary(self): self.__display.print_entry_summary(self.__entry) def __publishing_message(self, account): self.__display.print_uploading(account)
def setUp(self): """ Create object for all tests """ # Arrange copyfile(TestBank.src, TestBank.dst) self.bank = AccountManager(TestBank.dst)
def test_default_account(self): aa = AccountManager() aa.reset_config() expected = AccountManager.get_default_account() self.assertEqual(aa.get_recent_account(), expected)
def test_initialization(self): a = AccountManager() path = a._AccountManager__configpath self.assertTrue(path.endswith(".lyxblogger/config.cfg"))
If there are gains for a stock in a month, sell the gain portion to bring the investment in the stock back to the fixed amount for the next month. If there are losses for a stock in a month, add fund for the loss portion to buy the stock to bring the investment to the stock back to the fixed amount for the next month. ''' if __name__=='__main__': industry_name="Electronic Equipment & Instruments" industry_code="452030" con = sqlite3.connect('qse_test.db') security_data = SecurityData(con) account_manager = AccountManager(con) account_metrics = AccountMetrics(con) dates = security_data.get_dates() stock_ids=security_data.get_security() stock_info=security_data.get_company_info(stock_ids, ['ticker', 'company_name', 'gics_code', 'gics_name']) new_id=account_manager.new_account() #print new_id industry_ids=[] for i in range(len(stock_ids)): if stock_info[i][2]==industry_code: industry_ids.append(stock_ids[i]) if len(industry_ids)<1: print("The database contains no stocks in the sector: %s" %industry_name)
if order_qty <= 0: transfer_amt = 0 break succeeded = cash_func(transfer_amt) if succeeded: # TODO: consider adding commission to average price per share stock_func(symbol, order_qty * multiplier, price) else: order_qty -= 1 if order_qty <= 0: transfer_amt = 0 break return { 'shares': order_qty, 'price': price, 'transfer_amt': transfer_amt, 'type': order_type, 'commission': commission_total } # Used for debugging and development if __name__ == '__main__': from account_manager import AccountManager am = AccountManager(100000.) om = OrderManager('data/daily_gold.db', am) pass
START_DAY = '2008_01_02' # Day of initial stock purchases 'YYYY_MM_DD' ex '2016_01_04' '2008_01_02' COMMISSION = .005 # Cost in dollars per share traded COMMISSION_MIN = 1. # Minimum cost in dollars per stock traded COMMISSION_MAX = .005 # Maximum cost in percent of trade value SLIPPAGE = .01 # Average slippage in price due to market volatility #COMMISSION = .0 # Cost in dollars per share traded #COMMISSION_MIN = .0 # Minimum cost in dollars per stock traded #COMMISSION_MAX = .0 # Maximum cost in percent of trade value #SLIPPAGE = .0 # Average slippage in price due to market volatility # Create QuoteManager object quote_manager = QuoteManager(DB_FILEPATH) # Create AccountManager object my_account = AccountManager(START_BALANCE, MARGIN_PERCENT, quote_manager) # Create OrderManager object order_manager = OrderManager(quote_manager, my_account, slippage=SLIPPAGE, commission_min=COMMISSION_MIN, commission=COMMISSION, commission_max=COMMISSION_MAX) # Create an order_history DataFrame order_history = {} # Load signals data signals = pd.read_csv(SIGNALS_PATH, index_col=0) signal_dates = [date.replace('-', '_') for date in signals.index]
This file sets up a new account for the following trading strategy: Invest 100 each month in the sp500 except during summer month. Simulates how fund managers may not want to invest investing in any stocks in the summer months of May, June, July, and August, so they only resume investing in stocks in September. If there are gains for a stock in a month, sell the gain portion to bring the investment in the stock back to the fixed amount for the next month. If there are losses for a stock in a month, add fund for the loss portion to buy the stock to bring the investment to the stock back to the fixed amount for the next month. ''' if __name__=='__main__': con = sqlite3.connect('qse_test.db') security_data = SecurityData(con) account_manager = AccountManager(con) account_metrics = AccountMetrics(con) dates = security_data.get_dates() new_id=account_manager.new_account() #print new_id rows=[] for d in dates: summer_months = ["2008-05-31", "2008-06-30", "2008-07-31", "2008-08-31"] if d in summer_months: continue print d sp500_ids=security_data.get_sp500(d) for id in sp500_ids: row=[new_id, id, 100, d] rows.append(row)
from pprint import pprint import random from security_data import SecurityData from account_manager import AccountManager from account_metrics import AccountMetrics ''' This file sets up a new account for the following trading strategy: Invest a fixed amount (e.g. 100) of fund into each security where eq>75, arm>90, and rv>50. Only hold those stocks. At the end of each month, replace the stocks in the account by investing a fixed amount (e.g., 100) of fund into new stocks that have the above signals. ''' if __name__=='__main__': con = sqlite3.connect('qse_test.db') security_data = SecurityData(con) account_manager = AccountManager(con) account_metrics = AccountMetrics(con) dates = security_data.get_dates() new_id=account_manager.new_account() #print new_id rows=[] def signal_selection(eq,arm,rv): if eq>75 and arm>90 and rv>50: return True else: return False for d in dates: signals = security_data.get_security_signals(d, signal_selection)
class EAssistantService: def __init__(self): self.ef = EventFormatter() self.requests_session = None self.account_manager = AccountManager() data = self._parse_user_data() self.init_session(data) self.introduce() def _parse_user_data(self): r = {"pin": "", "captcha": "", "koda": ""} for field in ["uporabnik", "geslo"]: r[field] = self.account_manager.retrieve(field, request_if_none=True) return r def init_session(self, user_data): self.requests_session = Session() logger.info("Initialization of session for eassistant.") # Initial get login_url = "https://www.easistent.com/p/ajax_prijava" post_request = self.requests_session.post(login_url, data=user_data, allow_redirects=True) post_json = post_request.json() if post_request.status_code != 200 or len(post_json["errfields"]) != 0: raise Exception(post_request, post_request.text) for err in post_json.get('errfields', []): logger.error(err) redirect = post_json["data"]["prijava_redirect"] get_request = self.requests_session.get(redirect) # get_request.encoding = 'ISO-8859-1' # Extract auth metas from html soup = BeautifulSoup(get_request.text, 'html.parser') metas = {} soup = soup.find("head").find_all("meta") for nm in soup: if nm.get("name", None) in ("x-child-id", "access-token", "refresh-token"): metas[nm.get("name", None)] = nm.get("content", "").strip() # update headers to achieve authorization level :OK :) self.requests_session.headers.update({ "Authorization": metas["access-token"], "X-Child-Id": metas["x-child-id"], "X-Client-Version": "13", "X-Client-Platform": "web", "X-Requested-With": "XMLHttpRequest" }) logger.info("Session authenticated!") return self def introduce(self): table = ask_for(self.requests_session, "GET", "https://www.easistent.com/m/me/child").json() logger.info( f"Logged in as {table['display_name']} (ID:{table['id']}), age level: {table['age_level']}" ) def get_school_events(self, dt_begin: datetime.date = datetime.date.today(), dt_end: datetime.date = None): timetable_payload = get_request_date_boundary(dt_begin, dt_end) logger.debug("Easistent timetable payload: " + str(timetable_payload)) parsed_table = ask_for(self.requests_session, "GET", "https://www.easistent.com/m/timetable/weekly", params=timetable_payload).json() tmp_save(parsed_table, "timetable_parsed", "json") # print(parsed_table) time_table_object = self.ef.format_timetable_for_entry(parsed_table) tmp_save(time_table_object, "timetable_formatted", "json") return time_table_object
class TestBank(unittest.TestCase): "Initiation of Test class" def setUp(self): """ creates object for all tests""" Account.account_number = 1 self.bank = AccountManager() def tearDown(self): "Removes dependicies after every test" self.bank = None def test_init_accounts(self): " test init init methods from both account types" account_obj = self.bank.accounts[0] saving_obj = self.bank.accounts[3] self.assertEqual(account_obj.balance, 9499.0) self.assertEqual(account_obj.type_, 'Account') self.assertEqual(account_obj.id_, 1) self.assertEqual(account_obj.holders, []) self.assertEqual(saving_obj.balance, 10990.0) self.assertEqual(saving_obj.type_, 'SavingsAccount') self.assertEqual(saving_obj.id_, 4) self.assertEqual(saving_obj.holders, []) def test_get_account_id_notfound(self): "Test that bank returns correct string when accountID not exist" self.assertEqual(self.bank.get_account_by_id(10), "konto med detta id finns inte") def test_get_account_id_found(self): "Test bank returns correct account object when accountID exist" self.assertEqual(self.bank.get_account_by_id(1), self.bank.accounts[0]) def test_transaction_account(self): "Test transaction Account" input_dic = {'from_account': '1', 'to_account': '2', 'amount': '1000'} self.assertEqual(self.bank.accounts[0].balance, 9499.0) self.assertEqual(self.bank.accounts[1].balance, 6698.0) self.bank.transfer(input_dic) self.assertEqual(self.bank.accounts[0].balance, 8499.0) self.assertEqual(self.bank.accounts[1].balance, 7688.0) def test_transaction_savingccount(self): "test transaction SavingsAccount" input_dic = {'from_account': '4', 'to_account': '5', 'amount': '1000'} self.assertEqual(self.bank.accounts[3].balance, 10990.0) self.assertEqual(self.bank.accounts[4].balance, 11800.0) self.bank.transfer(input_dic) self.assertEqual(self.bank.accounts[3].balance, 9990.0) self.assertEqual(self.bank.accounts[4].balance, 12787.0) def test_interest_cal(self): "test interest calculation between two days." string = '2021-02-17' acc = self.bank.get_account_by_id(4) self.assertEqual(self.bank.calculate_interest_rate(acc, string), 0.09032876712328768) def test_init_persons(self): "test init method of person class" person_obj = self.bank.persons[0] self.assertEqual(person_obj.name, 'theodor') self.assertEqual(person_obj.id_, 'ted') def test_get_person_id_notfound(self): "Test bank returns correct string when personId not found" self.assertEqual(self.bank.get_person_by_id('lena'), "Detta id har ingen ägare") def test_get__id_found(self): "Test bank returns correct person object when personId found." self.assertEqual(self.bank.get_person_by_id('tedy'), self.bank.persons[1]) def test_person_id_false(self): "Test bank returns False when personId already exist" input_dic = {'name': 'oskar', 'id': 'ted'} self.assertFalse(self.bank.add_persons(input_dic)) def test_person_id_true(self): "Test bank returns correct personId after adding the object." input_dic = {'name': 'oskar', 'id': 'osk'} self.bank.add_persons(input_dic) self.assertEqual(self.bank.get_person_by_id('osk'), self.bank.persons[-1]) def test_connect_false(self): "Test bank returns False when connection to id already exist to account" input_dic = {'person': 'bols', 'account': '3'} self.assertFalse(self.bank.connect_person_account(input_dic)) def test_connect(self): "Test bank returns correct id after connection with account." input_dic = {'person': 'hum', 'account': '1'} self.bank.connect_person_account(input_dic) self.assertTrue(self.bank.get_person_by_id('hum'))
def __init__(self,con): self.account_manager=AccountManager(con) self.security_data=SecurityData(con)
def __init__(self, input_file, display = None): self.__display = display or Display() self.__state = 0 self.__entry = None self.__manager = AccountManager() self.__input_file = input_file
def __init__(self, input_file, display=None): self.__display = display or Display() self.__state = 0 self.__entry = None self.__manager = AccountManager() self.__input_file = input_file