def __init__(self): # Used for the server to send outbound messages self.receivesocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Used for the server to receive inbound messages # self.receivesocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP #Used for the shuffle protocol self.randomnumber = (int)(random.random() * 1000) ### SOCKET CREATION ### # Creates a socket at localhost and next available 5000 client self.MY_IP = "127.0.0.1" self.MY_PORT = 5000 self.CURRENT_GEN_POWERED = G connected = False while not connected: try: self.receivesocket.bind((self.MY_IP, self.MY_PORT)) print("Connected to port ", self.MY_PORT) connected = True except: print("Port {} is probably in use".format(self.MY_PORT)) self.MY_PORT += 1 self.serverjoin() ### CLIENT CREATION ### self.MY_CLIENTS = {} self.newclient() self.known_clients = [] ### LEDGER CREATION ### ### we can have the ledgers be in just the clients or just the servers or both self.MY_LEDGER = Ledger() self.current_round = "NONE"
def __init__(self, stream_id, line_spec, config, master_clock): self.line_id = line_spec['line-id'] self.linetype = line_spec['line-type'] self.site_name = line_spec['site-name'] self.site_efficiency = config['efficiency'][self.site_name] self.building = Buildings[self.linetype] self.building_count = line_spec[ 'buildingCount'] #TODO change camel to kebab case self.production = self._init_production(self.building_count) self.queue_identity = '' self.queue = self._init_production_queue(line_spec['queue']) self.ledger = Ledger(stream_id, self.line_id, self.linetype, self.building_count, config['market']) self.inventory = config['inventory'] self.sourcing_strategy = config['sourcing-strategy'] self.essentials_strategy = config['essentials-strategy'] self.non_essentials_strategy = config['non-essentials-strategy'] # initialize workers and efficiency before initializing production self.worker_efficiency = 0.0 self.workers = self._init_workers() self.worker_clock = DecrClock(Duration("0")) self._reset_workers(master_clock) self.efficiency = self._calc_line_efficiency() for bnum in range(0, self.building_count): self._set_next_recipe_active(master_clock, bnum) self.production[bnum]['producing'] = \ self._start_next_recipe(master_clock, bnum, last_round_producing=False) print('{} {} initialized - {} buildings'.format( master_clock, self.line_id, self.building_count), file=config['outfile'])
def __init__(self, consensus, transport): assert isinstance(consensus, SCP) assert isinstance(transport, BaseTransport) super(Herder, self).__init__() self.consensus = consensus self.overlay = transport self.ledger = Ledger(self.consensus, self)
def reconcile(self, **kwargs): """Match transactions in the ledger and bank statements. This might be useful: * ledger -f Chase_Bank-Preferred_Business_Checking.ledger --sort 'date' print * ledger -f main.ledger --sort 'date' print """ # If a set of accounts hasn't been provided, load them here. if not kwargs.setdefault('accounts', None): self._load_banks() for name, bank in self.banks.items(): kwargs['accounts'] = bank self.reconcile(**kwargs) return begin_date = "" if 'begin_date' in kwargs and kwargs['begin_date']: begin_date = " -b " + kwargs['begin_date'] for name, account in kwargs['accounts'].items(): log.info( "Loading ledger." ) ledger = Ledger(search=account.ledger_account, opts = "--related-all" + begin_date) ledger.load() reconciler = Reconciler(ledger, account) reconciler.reconcile()
def test_is_balance_gt_0(): """ Test the is balance greater than 0 function """ # Setup ledger_1 = Ledger('monies') user_2 = User('foo', ledger_1) user_1 = User('Anon', ledger_1) amount = 1 # test base case for Anon user_1._credit = 100 result = user_1.is_balance_gt_0(amount) assert result == True # test send amount for users amount = 101 ledger_1.transactions_by_user['foo']['running_balance'] = [] ledger_1.transactions_by_user['foo']['running_balance'].append(-101) assert user_2.is_balance_gt_0(amount) == True # test when user doesn't have enough money ledger_1.transactions_by_user['foo']['running_balance'].append(-102) assert user_2.is_balance_gt_0(amount) == False # test exception case ledger_1.transactions_by_user = Exception with raises(Exception): user_2.is_balance_gt_0(amount)
def summarize_run(self, lines, start_inv, end_inv): """ summarize and report on the summary """ print('', file=self.outfile) print('*** RUN SUMMARY {} ***'.format(self.stream_id), file=self.outfile) print('', file=self.outfile) print('Value Stream Summary:', file=self.outfile) stream_ledger = Ledger(self.stream_id, 'RUN.TOTALS', None, None, self.market) for line in lines: stream_ledger.add_ledger(line.ledger) stream_summary = stream_ledger.output_summary(self.duration, self.outfile) print('', file=self.outfile) print('Production Line Summaries:', file=self.outfile) line_summary = [] for line in lines: line.ledger.output_summary(self.duration, self.outfile) line_summary.append(line.line_identity()) print("", file=self.outfile) print('Inventory Summaries:', file=self.outfile) start_inv.output_summary('Starting Assets', self.market, self.outfile) end_inv.output_summary('Ending Assets', self.market, self.outfile) net_inv = end_inv.diff(start_inv) net_inv.output_summary('Asset Changes', self.market, self.outfile) self.log_run({ 'net': '{:5.2f}'.format(stream_summary['net']), 'fp': '-'.join(line_summary), 'uptime': stream_summary['uptime'], 'e-start': '{:5.2%}'.format(stream_summary['e-start']), 'e-delta': '{:5.2%}'.format(stream_summary['e-delta']), 'cdate': self.config_date, 'id': self.stream_id })
def test_mine_blocks_on_ledger(monkeypatch): """ test mining blocks """ mock_ledger = Ledger('foo') mock_miner = Miner('foominer', mock_ledger) mock_miner_2 = Miner('barminer', mock_ledger) mock_miners = [mock_miner, mock_miner_2] mock_ledger.transaction_sequence = 256 mine_blocks_on_ledger(mock_ledger, mock_miners, 10)
def main() -> None: # Prompt user for initial game info, including players and cards player = input('Enter your name: ').strip() opponents = input('Enter opponents (in order): ').strip().split() own_cards = [ Card.parse(s) for s in input('Enter your cards: ').strip().split() ] # Prompt for opponents' hand sizes if necessary hand_sizes = [len(own_cards)] card_count = len(Card.__members__) player_count = 1 + len(opponents) if (card_count - 3) % player_count != 0: for opponent in opponents: hand_sizes.append( int( input( 'Enter hand size for {}: '.format(opponent)).strip())) else: hand_sizes *= player_count # Set up the ledger and card/suggestion trackers all_players = [player] + opponents ledger = Ledger(all_players, hand_sizes, player, own_cards) suggestions = SuggestionTracker() shown_cards = ShownCardTracker(opponents) skipped_cards = SkippedCardTracker() # Main game loop did_solve = False while True: # Display the current game info print() print('#' * 79) print() for info in (suggestions, shown_cards, skipped_cards, ledger): print(info) print() # Check if we have a unique solution solution = ledger.solve() if solution is not None: print('*** Unique solution found! ***') print(', '.join(card.name for card in solution)) if not did_solve: show_continue_prompt() did_solve = True print() # noinspection PyBroadException try: process_input(player, all_players, ledger, shown_cards, skipped_cards, suggestions) except Exception: print() print('Whoops! Something went wrong...') traceback.print_exc() show_continue_prompt(1)
def get_ledger(): ''' Creates a new ledger object based on the blockchain stored in redis. ''' blockchain = read_from_redis() ledger = Ledger() ledger.load_blockchain(blockchain) return ledger
def __init__(self): AppWrapper.__init__(self) AppClient.__init__(self, wrapper=self) RequestManager.__init__(self) self.ledger = Ledger() try: signal.signal(signal.SIGINT, self.interruptHandler) signal.signal(signal.SIGTSTP, self.statusHandler) except AttributeError: console().warning("Warning. Unable to Bind a Signal Handler.")
def __init__(self, config): """ Open the socket for information retrieval at port <port>. Arguments: config -- a Config object that contains the configuration for the node """ self._unpack(config) self.msg_size_mapping = self._create_msg_mapping() self.socket = self._create_socket_server() self.ledger = Ledger() self.threads = [] self.thread_lock = threading.Lock()
def __init__(self, client_id): # I imagined wallets to be a list of dictionaries and each dictionary would have the following: # { # "private_key": the key that will be used to sign new messages # "public_key": the public key of the wallet # "Reputation": the amount of reputation that the wallet has << all wallets have only one reputation, so this is unncessary # maybe we want to add another item in here for the wallet's identity # } self.wallets = [] # start with 1 wallet with reputation=1 (feel free to change this) first_wallet = self.createwallet() # maybe we want to publish to the ledger? it's not an important issue, but we want to make sure that we can't just create random wallets out of nowhere self.wallets.append(first_wallet) # Client ID is just the ID of the port it's on, since we only have 1 client/port # Long standing private key # I think we're going to need a list of private keys that correspond to the individual wallets # ^that should be taken care of by self.wallets self.client_id = client_id self.private_key = util.generatePrivateKey() self.public_key = util.generatePublicKey(self.private_key) self.my_ledger = Ledger() print("Client ID: ", self.client_id) print("Client public key: ", self.public_key) print("Client private key: ", self.private_key)
def test_last_block_hash(): """ Test function for last block hash """ # Setup mock_ledger = Ledger('monies') mock_miner = Miner('Mock', mock_ledger) mock_header = {'hdr': 'foo'} mock_ledger.block_count = 1 mock_ledger.all_transactions.append(mock_header) mock_message = mock_ledger.all_transactions[0]['hdr'] mock_nonce_attempts = 1000000 mock_difficulty = 4 mock_hash = cryptohash(mock_message, mock_nonce_attempts, mock_difficulty) # Assert assert mock_miner.last_block_hash() == mock_hash
def compareToBudget(ledger_: Ledger, budgetFilename: Path, queryInput: QueryInput, formatOptions: FormatOptions) -> None: budgetDict = getBudgetDict(budgetFilename) periodBudgetDict = extrapolate(budgetDict, queryInput.period) # WHY are namedtuples immutable? This code is awful but I am so tired queryInput = QueryInput(periodBudgetDict[config.accountsIdentifier], queryInput.timeframe, queryInput.period, queryInput.exactMatch) queryResult = ledger_.periodicAccountQuery(queryInput) for (timeframe, result) in queryResult: result = BudgetResult(result, periodBudgetDict) print(timeframe) print(result.toStr(formatOptions, factor=1)) # Show total totalBudgetDict = extrapolateToTimeframe(budgetDict, queryInput.timeframe) queryInput = QueryInput(totalBudgetDict[config.accountsIdentifier], queryInput.timeframe, Period("infinite"), queryInput.exactMatch) result = BudgetResult(ledger_.patternAccountQuery(queryInput), totalBudgetDict) print("TOTAL") print(result.toStr(formatOptions, factor=1))
def _prepare(self): self.ledger = Ledger() self.ledger.records = [ ("Joe", 1, "BigBag", 1000), ("Mick", 2, "MoneyPile", 1000), ("Bob", 3, "BigBag", 1000), ("Alice", 4, "MoneyPile", 1000), ]
def test_ledger(): arr = np.array([["id 1a", "id 1b"], ["id 2a", "id 2b"]]) ls = ConstantLedgerSource(arr) t = FunctionTrigger() ledger = Ledger(t, ls) t.invoke() assert np.array_equal(ledger.get(), arr) arr.put([2, 3], ["id 3a", "id 3b"]) assert not np.array_equal(ledger.get(), arr) t.invoke() assert np.array_equal(ledger.get(), arr)
class Herder(LoggingMixin): consensus = None overlay = None ledger = None recievedTxs = list() proposedValues = list() pendingEnvelope = None slotIndex = 0 valuePrev = "" def __init__(self, consensus, transport): assert isinstance(consensus, SCP) assert isinstance(transport, BaseTransport) super(Herder, self).__init__() self.consensus = consensus self.overlay = transport self.ledger = Ledger(self.consensus, self) def bootstrap(self, application): # sync Ledger and.... print("bootstrap()") self.legerClosed(application) def legerClosed(self, application): print("legder closed") if application is not None: func = getattr(application, "triggerNextLedger") func() def triggerNextLedger(self): print("triggerNextLedger()") self.proposedValues = self.recievedTxs self.valuePrev, self.slotIndex = self.ledger.latest() self.slotIndex += 1 self.consensus.nominate(self.slotIndex, self.proposedValues, self.valuePrev) def receiveTransaction(self, txEnvelop): assert isinstance(txEnvelop, TXEnvelop) # check if tx is valid self.recvTxs.append(txEnvelop.tx) # no duplicates self.recvTxs = list(set(self.recvTxs)) # print("Tx Set : %s", self.pendingValues) return def receiveSCPMessage(self, scpEnvelop): assert isinstance(scpEnvelop, SCPEnvelop) self.consensus.receiveEnvelop(scpEnvelop) return def rebroadcast(self): pass def broadcast(self): pass
def test_send_exception(): """ Test if send will throw an exception if no monies """ # Setup ledger_1 = Ledger('monies') user_2 = User('foo', ledger_1) user_1 = User('oops', ledger_1) amount = 1 with raises(Exception): user_1.send(amount, user_2)
class Transaction(object): def __init__(self, market, quantity = 0, rate = 0): self.log = Log() self.market = market self.quantity = quantity self.rate = rate self.ledger = Ledger(self.market) def buy(self, quantity, rate): self.ledger.record_transaction('BUY', quantity, rate) print('Purchased: ' + str(quantity) + self.market.split('-')[1] + 'at ' + str(rate)) def sell(self, quantity, rate): self.ledger.record_transaction('SELL', quantity, rate) print('Sold: ' + str(quantity) + self.market.split('-')[1] + 'at ' + str(rate))
def test_generate_initial_balance(): """ test to make sure initial balance is on a user """ # Setup mock_ledger = Ledger('foo') mock_anon = User('Anon', mock_ledger) mock_user = User('bar', mock_ledger) mock_users = [mock_user] initial_value = 1000 generate_initial_balance(mock_anon, mock_users, initial_value, 10) assert mock_anon._credit == initial_value * len(mock_users) * 10
def test_queryset(): lut = FunctionTrigger() ledger1 = pd.DataFrame({"Key1": ["A1", "B1"], "Key2": ["A2", "B2"]}) ledger2 = pd.DataFrame({ "Key1": ["A1", "D1", "E1"], "Key2": ["A2", "D2", "E2"] }) cls1 = ConstantLedgerSource(ledger1) cls2 = ConstantLedgerSource(ledger2) led1 = Ledger(lut, cls1) led2 = Ledger(lut, cls2) lut.invoke() qs = QuerySet([led1, led2], pd.DataFrame({ "Source": ["S0", "S0"], "Query": ["Q0", "Q2"] })) result_iterator = qs.join(3) results = result_iterator.as_list() target = pd.DataFrame({ "Key1": ["A1", "B1", "D1", "A1", "B1", "D1", "E1", "E1"], "Key2": ["A2", "B2", "D2", "A2", "B2", "D2", "E2", "E2"], "Source": ["S0"] * 8, "Query": ["Q0", "Q2"] * 4 }) c = 0 for result in results: row = target.loc[[c]] query = Query(**row.to_dict(orient="index")[c]) assert query == result c += 1
def reconcile(book, bank, externalData): """ Reconciles a book statement with a bank statement, supported by extra external data. Args: book: a Ledger object bank: a Ledger object externalData: extra data such as previous bank reconciliations Returns: Nothing Raises: Nothing """ # Algorithm 1: One-to-one reconciliation ut.clean_columns(book.ledger) bankColumn = ut.clean_string('G/L Account Name') # Filter by bank bookByBank = Ledger( ledger=book.ledger.query('{} == "{}"'.format(bankColumn, bank.name))) pivotTable = Ledger(ledger=ut.toPivotTable(bookByBank.ledger)) vendorPivotTable = Ledger( ledger=pivotTable.ledger.drop('Customer', axis=1).copy()) customerPivotTable = Ledger( ledger=pivotTable.ledger.drop('Vendor', axis=1).copy()) appendMatchColumn(vendorPivotTable) appendMatchColumn(customerPivotTable) appendMatchColumn(bank) oneToOneMatch(vendorPivotTable, bank, ut.clean_string('Vendor'), ut.clean_string('Debit')) oneToOneMatch(customerPivotTable, bank, ut.clean_string('Customer'), ut.clean_string('Credit')) # After getting all pivot table matches, map it back up to the Book Ledger reversePivotMapping(book, bookByBank, vendorPivotTable, customerPivotTable) # Reflect changes in excel highlightMatches(book) highlightMatches(bank) ut.newExcel(vendorPivotTable, 'VendorByDate.xlsx', 'Reconciliation') ut.newExcel(customerPivotTable, 'CustomerByDate.xlsx', 'Reconciliation') highlightMatches(vendorPivotTable) highlightMatches(customerPivotTable) return
def test_app(): l = Ledger() g1 = [2, 3, 3] g2 = [1, 2, 2] g3 = [1, 1, 1] gmax = 5 # range of each element g_length = 3 # length of the vector total_bound = 10 # range of the vector # Phase 0: initiate z1 = Zorro(l, 0, g_length, gmax, total_bound) z2 = Zorro(l, 1, g_length, gmax, total_bound) z3 = Zorro(l, 2, g_length, gmax, total_bound) print("Phase 1: commit...") # Phase 1: commit if (l.phase('c') == 1): z1.commit(g1) z2.commit(g2) z3.commit(g3) else: print("Phase 1 failed!") print("Phase 2: proof...") # Phase 2: generate zkp proofs if (l.phase('p') == 1): z1.prove() z2.prove() z3.prove() else: print("Phase 2 failed!") print("Phase 3: results...") # Phase 3: get results if (l.phase('r') == 1): print(z1.results()) #z2.results() #z3.results() else: print("Phase 3 failed!")
def create_users_and_ledger(): """ Create the users and ledger """ monies = Ledger('monies') alice = User('Alice', monies) bob = Miner('Bob', monies) jon = User('Jon', monies) howard = User('Howard', monies) rocky = Miner('Rocky', monies) # using an anon user for creating an initial balance anon = User('Anon', monies) users = [alice, jon, howard] miners = [rocky, bob] return (monies, anon, users, miners)
def import_data(account, currency, dry_run, gnucash_file, classifier): """ Import data from a given file into a given gnucash file. Must have an account and a gnucash file defined. Is optional define the currency (default can setted in seupt.cfg - usiing BRL). Also, is optional define dry_run (default is **true**). """ logging.info( Util.info("Importing data to ") + colored("{a}".format(a=account.name), 'yellow', attrs=['bold', 'underline']) + Util.info("'s account")) Ledger(account, currency, dry_run, gnucash_file, classifier).write()
class Second30Trader(AppWrapper, AppClient, RequestManager): """ Client, Wrapper, and Logic Bundler """ def __init__(self): AppWrapper.__init__(self) AppClient.__init__(self, wrapper=self) RequestManager.__init__(self) self.ledger = Ledger() try: signal.signal(signal.SIGINT, self.interruptHandler) signal.signal(signal.SIGTSTP, self.statusHandler) except AttributeError: console().warning("Warning. Unable to Bind a Signal Handler.") def interruptHandler(self, *_): """ Gracefully quit on CTRL+C """ console().info("Disconnecting From API...") self.stopAllSubscriptions() self.disconnect() self.ledger.close() sys.exit(0) def statusHandler(self, *_): """ Show Price and Other Data on Ctrl + Z """ self.printStatus()
def process_input(player: str, all_players: List[str], ledger: Ledger, shown_cards: ShownCardTracker, skipped_cards: SkippedCardTracker, suggestions: SuggestionTracker) -> None: """Updates the current known game state based on user input.""" # Prompt user to enter relevant info for each suggestion suggesting_prefix = input('Enter suggesting player: ').strip() suggested_card_prefixes = input('Enter suggested cards: ').strip().split() showing_prefix = input('Enter player showing: ').strip() assert len(suggested_card_prefixes) == 3, 'Suggestions involve 3 cards' # Map prefixes to actual players/cards suggesting_player = prefix.find_match(suggesting_prefix, all_players) suggested_cards = [Card.parse(name) for name in suggested_card_prefixes] showing_player = (None if showing_prefix == '' else prefix.find_match( showing_prefix, all_players)) # Get passing players based on suggesting and showing players passing_players = find_passing_players(all_players, suggesting_player, showing_player) # Handle cases where user is directly involved in suggestion shown_card: Optional[Card] = None if (showing_player is not None and player in (suggesting_player, showing_player)): shown_card = Card.parse(input('Enter shown card: ').strip()) if player == showing_player: shown_cards.update(suggesting_player, shown_card) # Update ledger and suggestion/card trackers ledger.update(suggested_cards, passing_players, showing_player, shown_card) suggestions.update(suggesting_player, suggested_cards, passing_players, showing_player) if player in passing_players: skipped_cards.update(suggested_cards)
def readLedgers(cfg, type): """ Reads a list of excel files from the list specified in cfg for the type specified Args: cfg: The config file that contains the list of files type: The name of the list that you want from cfg Returns: A list of Ledger objects that contain the data within the excel files Raises: Nothing """ # TODO: How do I do read-only access, and not have them open up when I call Book()? return [Ledger(file=file) for file in cfg['files'][type]]
def append_sums_from_trans(self, trans: Ledger, prorate_fraction: int = 1): """Calculate the subtotal for each node (direct subtotal only, no children) in the tree, based on exactly provided transaction frame, and return a new account tree with subtotals """ trans = trans.reset_index(drop=True).set_index(CONST["account_col"]) subtotals = trans.groupby(CONST["account_col"]).sum()["amount"] atree = self.subtree(self.root) atree = ATree.cast(atree) for node in atree.all_nodes(): try: subtotal = subtotals.loc[node.tag] except KeyError: # These should be nodes without leaf_totals, and therefore # not present in the subtotals DataFrame continue prorated_subtotal = 0 if subtotal and subtotal > 0: try: prorated_subtotal = round(subtotal * prorate_fraction) except OverflowError: pass node.data = {"leaf_total": prorated_subtotal} return atree
def test_generate_transactions_on_ledger(): """ test generating transactions """ # Setup mock_ledger = Ledger('foo') mock_anon = User('Anon', mock_ledger) mock_user = User('bar', mock_ledger) mock_user_2 = User('foobar', mock_ledger) mock_miner = Miner('foominer', mock_ledger) mock_users = [mock_user, mock_user_2] mock_miners = [mock_miner] initial_value = 100 generate_initial_balance(mock_anon, mock_users, initial_value, 10) ledger, users = generate_transactions_on_ledger( mock_ledger, mock_users, 3, mock_miners, 10) assert isinstance(ledger, Ledger) for user in users: assert isinstance(user, User)
def test_initializeLedgers_proportional1(): expected = { 0: { 1: Ledger(5, 5), 2: Ledger(5, 5) }, 1: { 0: Ledger(5, 5), 2: Ledger(5, 5) }, 2: { 0: Ledger(5, 5), 1: Ledger(5, 5) }, } actual = initialLedgers('proportional', [10, 10, 10]) assert actual == expected, "proportional ledger generation not as expected (1)"
def test_initializeLedgers_proportional2(): expected = { 0: { 1: Ledger(1.2, 1), 2: Ledger(9, 3) }, 1: { 0: Ledger(1, 1.2), 2: Ledger(27, 10.8) }, 2: { 0: Ledger(3, 9), 1: Ledger(10.8, 27) }, } actual = initialLedgers('proportional', [4, 12, 36]) assert actual == expected, "proportional ledger generation not as expected (2)"
#!/usr/local/bin/python2 # -*- coding: UTF-8 -*- import cgitb, sys cgitb.enable() sys.path.insert(0, '../controller') import cgi, datetime, json, StringIO from html5print import HTMLBeautifier from decimal import Decimal as Dec from ledger import Ledger import page_elements if __name__ == '__main__': settings = json.load(open('../model/settings.json')) ledger = Ledger('../model/ledger.db', settings['roommate_names']) html = ''' <!DOCTYPE html> <html> <head> <title>Cannon Ct. Bills</title> <link rel="stylesheet" href="style/styles.css" /> <link rel="icon" type="image/png" href="images/bills_icon.png" /> </head> <body> <a class="right" href="https://github.com/jperryhouts/roommate_bills_tracker">Source Code</a> {warnings} <div class="content"> <table>
help='Acts as user') parser.add_argument('command', type=str, help='command') parser.add_argument('command_args', type=str, nargs='*', help='command arguments') args = parser.parse_args() if args.command == 'init': if 3 > len(args.command_args): raise Exception("Must specifiy a user when initializing") user = User(args.command_args[0], args.command_args[1], args.command_args[2]) # FOR TESTING ONLY # THIS WILL ERROR if os.path.exists(args.ledger): shutil.rmtree(args.ledger) ledger = Ledger.init(args.ledger, user) else: with Ledger(args.ledger, args.user) as ledger: if args.command == 'add-user': if 2 > len(args.command_args): raise Exception("Must specifiy a user when initializing") user_to_add = User( args.command_args[0], # Username args.command_args[1], # Full Name args.command_args[2]) # Email user_to_add.generate_key() ledger.add_user(user_to_add) elif args.command == "tx": ledger.create_tx( args.command_args[0], # to
class TestLedger(unittest.TestCase): def _prepare(self): self.ledger = Ledger() self.ledger.records = [ ("Joe", 1, "BigBag", 1000), ("Mick", 2, "MoneyPile", 1000), ("Bob", 3, "BigBag", 1000), ("Alice", 4, "MoneyPile", 1000), ] def test_credit(self): self._prepare() self.ledger.credit("Joe", 1, "BigBag", 500) self.assertEqual(len(self.ledger.records), 5) self.assertEqual(self.ledger.records[-1], ("Joe", 1, "BigBag", -500)) def test_debit(self): self._prepare() self.ledger.debit("Joe", 1, "BigBag", 500) self.assertEqual(len(self.ledger.records), 5) self.assertEqual(self.ledger.records[-1], ("Joe", 1, "BigBag", 500)) def test_credit_neg(self): self._prepare() with self.assertRaises(Exception): self.ledger.credit("Joe", 1, "BigBag", -500) def test_bank_balance(self): self._prepare() self.assertEqual(self.ledger.bank_balance("MoneyPile"), 2000) def test_transfer(self): self._prepare() self.ledger.transfer("Joe", 1, "BigBank", "Mick", 1, "MoneyPile", 1) self.assertEqual(self.ledger.person_balance("Joe"), 999) self.assertEqual(self.ledger.person_balance("Mick"), 1001)
'application/json': output_json, } class BanksApi: def __init__(self, app, ledger, *args, **kwargs): api = MyApi(app) api.add_resource(BankBalanceResource,'/api/bank/<string:bank>/balance') api.add_resource(PersonBalanceResource,'/api/person/<string:person>/balance') api.add_resource(AccountBalanceResource,'/api/account/<int:account>/balance') api.add_resource(TransactionsResource,'/api/transactions') api.add_resource(TransferResource, '/api/transfer/<string:person>/<string:account>/<string:bank>/to'+ '/<string:person_to>/<int:account_to>/<string:bank_to>/amount/<int:amount>' ) ledger = Ledger() ledger.records = [ ("Joe", 1, "BigBag", 1000), ("Mick", 2, "MoneyPile", 1000), ("Bob", 3, "BigBag", 1000), ("Alice", 4, "MoneyPile", 1000), ] if __name__ == '__main__': app = Flask(__name__) api = BanksApi(app, ledger) app.run()