def _get_pagination_data(self): page_number = int(self.request.route_kwargs.get('page_number', 1)) number_of_pages = Post.get_post_page_count() if number_of_pages == 1: return {} pagination_data = { 'prev_page_active': (page_number > 1), 'prev_page': get_route('home_by_page', page_number = (page_number - 1)) if (page_number > 1) else '#', 'next_page_active': (page_number < number_of_pages), 'next_page': get_route('home_by_page', page_number = (page_number + 1)) if (page_number < number_of_pages) else '#', 'pages': [] } for i in range(1, number_of_pages + 1): pagination_data['pages'].append({ 'active': (i == page_number), 'number': i, 'url': get_route('home_by_page', page_number=i) }) return pagination_data
def test_can_post_to_process_markdown_url(self): self.app.post( get_route("ajax_markdown", action="process"), params={"markdown": "this here would be markdown"}, headers=self.ajax_header, status=200, )
def test_can_get_existing_tags(self): response = self.app.get(get_route("ajax_tags"), headers=self.ajax_header, status=200) deser_resp = json.loads(response.body) self.assertIsNotNone(deser_resp) self.assertEqual(len(deser_resp), 3)
def test_can_load_author_list_page(self): self.login("*****@*****.**", admin=True) response = self.app.get(get_route("list_author"), status=200) response.mustcontain("test_nickname") response.mustcontain("*****@*****.**")
def test_cannot_create_duplicate_tag(self): response = self.app.post( get_route("ajax_tags"), params={"name": "test tag 1"}, headers=self.ajax_header, status=200 ) deser_resp = json.loads(response.body) self.assertIsNone(deser_resp)
def _menu_item_exists(self, menu_item_text): response = self.app.get(get_route("home")) soup = BeautifulSoup(response.body) menu = soup.first("ul", {"class": "nav"}) return bool(menu.first("a", text=menu_item_text))
def test_can_create_new_tag(self): response = self.app.post( get_route("ajax_tags"), params={"name": "new tag"}, headers=self.ajax_header, status=200 ) deser_resp = json.loads(response.body) self.assertIsNotNone(deser_resp) self.assertEqual(deser_resp["name"], "new tag")
def get_route_by_file_name(self, file_name, file_type): """ Repasse de responsabilidade para o metodo de retorno, apenas para manter uma arquitetura menos acoplada. :param file_name:string :return: row:dict """ return utils.get_route('origem', 'destino', self.origem, self.destino, file_name, file_type)
def test_existing_tags_available_on_page_load(self): self.login("*****@*****.**", admin=True) response = self.app.get(get_route("add_post")) soup = BeautifulSoup(response.body) multiselect_box = soup.find("select", {"name": "tags"}) options = multiselect_box.findAll("option") self.assertEqual(len(options), 3)
def test_can_get_processed_markdown(self): test_markdown_text = "test title\n==========" response = self.app.post( get_route("ajax_markdown", action="process"), params={"markdown": test_markdown_text}, headers=self.ajax_header, status=200, ) response.mustcontain("<h1>test title</h1>")
def test_existing_post_content_loads_on_edit(self): self.login("*****@*****.**", admin=True) response = self.app.get(get_route("edit_post", key=self.test_post.key.urlsafe()), status=200) edit_form = response.form self.assertEqual(edit_form["subject"].value, "test post") self.assertEqual(edit_form["mark_down"].value, "test mark down") self.assertEqual(edit_form["is_published"].value, "on") self.assertEqual(edit_form["tags"].value, [self.test_tag_1.urlsafe()]) self.assertEqual(edit_form["key"].value, self.test_post.key.urlsafe())
def test_must_be_admin_to_update_author(self): self.login("*****@*****.**", admin=False) author_update_dict = { "nickname": "asdf", "first_name": "lkjasdf", "last_name": "asdlkfj", "email": "lkjlkjasdf", } self.app.post( get_route("edit_author", key=self.test_author.key.urlsafe()), params=author_update_dict, status=403 )
def test_can_edit_author_using_page(self): response = self.app.get(get_route("edit_author", key=self.test_author.key.urlsafe()), status=200) author_edit_form = response.form author_edit_form["nickname"] = "updated_nickname" author_edit_form["first_name"] = "updated_firstname" author_edit_form["last_name"] = "updated_lastname" author_edit_form["email"] = "*****@*****.**" form_response = author_edit_form.submit().follow() form_response.mustcontain("updated_nickname") form_response.mustcontain("updated_firstname") form_response.mustcontain("updated_lastname") form_response.mustcontain("*****@*****.**")
def test_can_add_author_using_page(self): response = self.app.get(get_route("add_author"), status=200) author_entry_form = response.form author_entry_form["nickname"] = "test_nickname" author_entry_form["first_name"] = "test_first_name" author_entry_form["last_name"] = "test_last_name" author_entry_form["email"] = "*****@*****.**" form_response = author_entry_form.submit().follow() form_response.mustcontain("test_nickname") form_response.mustcontain("test_first_name") form_response.mustcontain("test_last_name") form_response.mustcontain("*****@*****.**")
def get_route(): params = request.get_json() _auth = params.get('auth_token') _servID = params.get('service_id') if not _auth: return json.dumps({"error": "missing or invalid auth token" }), status.HTTP_404_NOT_FOUND else: try: decoded = jwt.decode(_auth, verify=False) except Exception: return json.dumps({"error": "unauthorized"}), status.HTTP_401_UNAUTHORIZED else: response = utils.get_route(_servID) return json.dumps(response)
def run_miner(): """Run the main miner loop. """ global blockchain global public global private while True: # Load transaction queue and blockchain from server. txns = load_transactions() blockchain = load_blockchain() # Add reward to us yay. reward = Transaction(id=gen_uuid(), owner="mined", receiver=public, coins=REWARD, signature=None) reward.signature = sign(reward.comp(), private) txns.append(reward) # Construct a new block. b = Block(timestamp=datetime.datetime.now(), transactions=txns, previous_hash=blockchain.head.hash_block()) # Let's mine this block. mine_till_found(b) # Is this _the_ new block? # or did the server swoop us :( new_chain = load_blockchain() if new_chain.head.hash_block() == blockchain.head.hash_block(): # WE MINED THIS BLOCK YAY. # AND WE WIN. resp = get_route('add', data=str(b)) if resp['success']: print "Block added!" delete_queue(txns) else: print "Couldn't add block:", resp['message'] else: print "Someone else mined the block before us :("
def test_can_alter_existing_post(self): self.login("*****@*****.**", admin=True) test_post = ( Post( subject="test subject", mark_down="test mark down", is_published=True, tags=[self.test_tag_1.key, self.test_tag_2.key], ) .put() .get() ) test_post_update = [ {"name": "subject", "value": "test subject modified"}, {"name": "mark_down", "value": "This is some test text (modified)."}, {"name": "is_published", "value": ""}, {"name": "tags", "value": self.test_tag_1.key.urlsafe()}, {"name": "tags", "value": self.test_tag_2.key.urlsafe()}, {"name": "tag_name", "value": ""}, {"name": "key", "value": test_post.key.urlsafe()}, ] response = self.app.post( get_route("ajax_edit_post"), headers=self.ajax_header, params={"post": json.dumps(test_post_update)}, status=200, ) processed_response = json.loads(response.body) self.assertIsNotNone(processed_response) self.assertIn("key", processed_response) self.assertEqual(processed_response["key"], test_post.key.urlsafe()) self.assertIn("post_last_modified", processed_response) self.assertIn("post_last_modified_by", processed_response) reloaded_post = test_post.key.get() self.assertEqual(reloaded_post.subject, "test subject modified") self.assertEqual(reloaded_post.mark_down, "This is some test text " "(modified).") self.assertFalse(reloaded_post.is_published)
def mine_till_submit(txns): while True: chain = miner.load_blockchain() b = Block(timestamp=datetime.datetime.now(), transactions=txns, previous_hash=chain.head.hash_block()) miner.mine_till_found(b) try: resp = get_route('add', data=str(b)) if resp['success']: print("Block added!") if miner.load_blockchain().head.hash_block() == b.hash_block(): print("Success!") return else: print("Got beaten") else: print "Couldn't add block:", resp['message'] except Exception as e: print(e)
def test_can_submit_post(self): self.login("*****@*****.**", admin=True) response = self.app.post( get_route("ajax_edit_post"), headers=self.ajax_header, params={"post": self.test_post_json}, status=200 ) processed_response = json.loads(response.body) self.assertIsNotNone(processed_response) self.assertIn("key", processed_response) self.assertIn("post_last_modified", processed_response) self.assertIn("post_last_modified_by", processed_response) submitted_post = model.Key(urlsafe=processed_response["key"]).get() self.assertIsNotNone(submitted_post) self.assertEqual(submitted_post.subject, "Hello World") self.assertEqual(submitted_post.mark_down, "This is some test text.") self.assertTrue(submitted_post.is_published) self.assertIn(self.test_tag_1.key, submitted_post.tags) self.assertIn(self.test_tag_2.key, submitted_post.tags)
def main(filename, start, end): """ Entering method. Creates the map, execs the algorithm and prints the result. Raise exception if map is invalid. filename: map file name (str) start: start point ([int, int]) end: end point ([int, int]) """ try: map = CharMapCost(filename, start, end) except UserInputException: print("[Error] Exiting..", file=stderr) return -1 map.dump() t0 = time.time() goalParentId = astar(map) route = get_route(map.closed_nodes, goalParentId) tf = time.time() print_results([len(route), map.n_checked, round((tf - t0), 5)])
def test_loading_home_page_two_displays_posts_from_page_two(self): self._create_test_posts(12) response = self.app.get(get_route("home_by_page", page_number=1), status=200) response.mustcontain("test post 10", "test mark down")
def test_can_load_home_page_with_no_posts(self): self.app.get(get_route("home"), status=200)
def test_loading_home_page_displays_posts(self): self._create_test_posts(1) response = self.app.get(get_route("home"), status=200) response.mustcontain("test post 1", "test mark down")
def test_pagination_not_displayed_if_only_one_page(self): self._create_test_posts(9) resp = self.app.get(get_route("home"), status=200) resp.mustcontain(no=['<div class="pagination pagination-centered">'])
def test_current_page_is_marked_as_active(self): self._create_test_posts(12) resp = self.app.get(get_route("home_by_page", page_number=2), status=200) resp.mustcontain('<li class="active"><a href="/page/2/">2</a></li>')
def run_miner(): """Run the main miner loop. """ my_address = "2cb4fc5902917e58e531cfbe1d909727aaf331b4856bf8627e09bf8941b69a40" my_private = "610af1630bf08b0072d97bdaf71882cd0a2c86e7af72296b4ee73f508b812c28" my_address_2 = "a173fd8d2330cc2b4776730891f50099204376217c67b7b23254aca04fbeb5a3" my_private_2 = "d0f783f01ac0df1799856964fe74f702763932e1edf3e9d0074646de885d5559" public = my_address_2 private = my_private_2 donor = None while True: print("new public", public) print("new private", private) global blockchain global real_b1 global fake_b1 global fake_b2 blockchain = load_blockchain() # Add reward to us yay. # my_address_3 = "5adbd7137903135fa2cc5a2de2035a326319e42188a9c6714b26fa016c6ac1bb" # my_private_3 = "91f233e1218135b772ddc87a199e6d3cc18233753623f95385dde62e886304c7" amount_1 = blockchain.get_wallet_amount(my_address) amount_2 = blockchain.get_wallet_amount(my_address_2) # amount_3 = blockchain.get_wallet_amount(my_address_3) if amount_1 < 0: my_private, my_address = generate_keys() public = my_address private = my_private donor_pub = my_address_2 donor_private = my_private_2 donor_amount = amount_2 else: my_private_2, my_address_2 = generate_keys() public = my_address_2 private = my_private_2 donor_pub = my_address donor_private = my_private donor_amount = amount_1 # Add reward to us yay. reward = Transaction( id = gen_uuid(), owner = "mined", receiver = public, coins = REWARD, signature = None ) txns = [] reward.signature = sign(reward.comp(), private) txns.append(reward) donation1 = Transaction( id = gen_uuid(), owner = donor_pub, receiver = "3119281c76dc54009925c9208bedc5bd0162c27034a1649fd7e2e5df62dba557", coins = donor_amount, signature = None ) donation1.signature = sign(donation1.comp(), donor_private) donation2 = Transaction( id = gen_uuid(), owner = donor_pub, receiver = public, coins = donor_amount, signature = None ) donation2.signature = sign(donation2.comp(), donor_private) txns.append(donation1) txns.append(donation2) # Construct a new block. real_b1 = Block( timestamp = datetime.datetime.now(), transactions = txns, previous_hash = blockchain.head.hash_block() ) mine_till_found(real_b1) new_chain = load_blockchain() # print "Adding real block now" # resp1 = get_route('add', data=str(real_b1)) # if resp1['success']: # print "Added real block1!" # else: # print "Couldn't add block:", resp1['message'] if new_chain.head.hash_block() == blockchain.head.hash_block(): print "Adding real block now" resp1 = get_route('add', data=str(real_b1)) if resp1['success']: print "Added real block1!" else: print "Couldn't add block:", resp1['message'] else: print "Someone else mined the block before us :("
def test_must_be_admin_to_view_page(self): self.login("*****@*****.**", admin=False) self.app.get(get_route("add_author"), status=403)
def run_miner(): """Run the main miner loop. """ global blockchain global public global private while True: # Load transaction queue and blockchain from server. txns = load_transactions() blockchain = load_blockchain() # Loc: Check our balance balance = get_balance(public) print "Current balance", balance # Loc: Set up attack is_attacking = False if balance > 60: print "Setting up Finney attack" is_attacking = True t = Transaction( id=gen_uuid(), owner=public, receiver= "6f181e44edfc93de084071e590421e5b083f93da6012d441658b6b31a966ae9c", coins=balance, signature=None) # Sign it. t.signature = sign(t.comp(), private) # Pay myself a lot! for x in range(0, 3): txns.append(t) # Add reward to us yay. reward = Transaction(id=gen_uuid(), owner="mined", receiver=public, coins=REWARD, signature=None) reward.signature = sign(reward.comp(), private) txns.append(reward) # Construct a new block. b = Block(timestamp=datetime.datetime.now(), transactions=txns, previous_hash=blockchain.head.hash_block()) # Let's mine this block. mine_till_found(b) # Is this _the_ new block? # or did the server swoop us :( new_chain = load_blockchain() if new_chain.head.hash_block() == blockchain.head.hash_block(): # WE MINED THIS BLOCK YAY. # AND WE WIN. # Loc: Add in a Finney attack to double spend the coin resp = get_route('add', data=str(b)) if resp['success']: print "Block added!" delete_queue(txns) else: print "Couldn't add block:", resp['message'] else: print "Someone else mined the block before us :("
def test_can_render_links_for_available_pages(self): self._create_test_posts(12) resp = self.app.get(get_route("home"), status=200) resp.mustcontain('<li class="active"><a href="/page/1/">1</a></li>', '<li><a href="/page/2/">2</a></li>')
def run_miner(): """Run the main miner loop. """ global blockchain global public global private new_reward = REWARD while True: # Load transaction queue and blockchain from server. new = [] blockchain = Blockchain() blockchain.add_block( Block( timestamp=datetime.datetime.now(), transactions=[], previous_hash=get_genisis().hash_block(), nonce=12834 ), cheat=True ) server = load_blockchain() txns = load_transactions() # Is this _the_ new block? # or did the server swoop us :( new_chain = load_blockchain() num_blocks = 1333 + server.head.height for i in range (num_blocks): reward = Transaction( id = gen_uuid(), owner = "mined", receiver = public, coins = REWARD, signature = None ) reward.signature = sign(reward.comp(), private) txns = [reward] b = Block( timestamp = datetime.datetime.now(), transactions = txns, previous_hash = blockchain.head.hash_block() ) blockchain.add_block(b, cheat=True) # Let's mine this block. reward = Transaction( id = gen_uuid(), owner = "mined", receiver = public, coins = REWARD, signature = None ) reward.signature = sign(reward.comp(), private) txns = [reward] # Construct a new block. b = Block( timestamp = datetime.datetime.now(), transactions = txns, previous_hash = b.hash_block() ) print(blockchain.head.height) mine_till_found(b) # WE MINED THIS BLOCK YAY. # AND WE WIN. resp = get_route('add', data=str(b)) if resp['success']: print "Block added!" delete_queue(txns) else: print "Couldn't add block:", resp['message']
def test_can_load_page(self): self.login("*****@*****.**", admin=True) response = self.app.get(get_route("list_post"), status=200) response.mustcontain("test post", "Published")
for i in range(ITERS): weight = randint(10, 20) txns = [ paySomeone(wallets[0][1], wallets[0][0], wallets[1][1], balances[0]) for _ in range(weight) ] lastBlock = construct_and_mine(txns, lastBlock) blocksToSubmit.append(lastBlock) wallets = (wallets[1], wallets[0]) balances = (balances[1] + weight * balances[0], balances[0] * (1 - weight)) print(balances) lastBlock = construct_and_mine( [paySomeone(wallets[0][1], wallets[0][0], STORE, balances[0])], lastBlock) blocksToSubmit.append(lastBlock) open("filthyrich.jq", "w").writelines(map(str, blocksToSubmit)) exit() for block in blocksToSubmit: try: resp = get_route('add', data=str(block)) if resp['success']: print("Block added!") else: print "Couldn't add block:", resp['message'] except Exception as e: print(e)
def test_bad_request_error_if_markdown_param_not_present(self): self.app.post(get_route("ajax_markdown", action="process"), headers=self.ajax_header, status=400)
def test_can_load_author_add_page(self): self.app.get(get_route("add_author"))
def test_loading_invalid_page_number_presents_404(self): self.app.get(get_route("home_by_page", page_number=1000), status=404) self.app.get(get_route("home_by_page", page_number=-1), status=404)
def test_previous_page_link_disabled_if_on_first_page(self): self._create_test_posts(12) resp = self.app.get(get_route("home"), status=200) resp.mustcontain('<li class="disabled"><a href="#">«</a></li>')
def load_blockchain(): server_blockchain = get_route('blockchain', json=False) server_blockchain = server_blockchain.replace('hackcoin.core.', '') return jsonpickle.decode(server_blockchain)
def test_next_page_link_disabled_if_on_last_page(self): self._create_test_posts(12) resp = self.app.get(get_route("home_by_page", page_number=2), status=200) resp.mustcontain('<li class="disabled"><a href="#">»</a></li>')
def test_must_be_admin_to_view_page(self): self.app.get(get_route("list_post"), status=403)
def test_add_author_page_has_add_author_button(self): response = self.app.get(get_route("add_author"), status=200) response.mustcontain("add_button", no="edit_button")