def test_tradebucket_current_value(): """ Tests TradeBucket.current_value() """ account = account_helper() value_of_stock1 = 3 stock1 = Stock.create_new_stock(name="Name1X", ticker="TKRC") stock1.daily_quote.create(value=value_of_stock1, date="2016-06-03") invest_bucket = InvestmentBucket(name="Bucket Test", public=True, owner=account.profile, available=1) invest_bucket.save() InvestmentStockConfiguration( quantity=1, stock=stock1, bucket=invest_bucket, start="2016-07-11", end="2016-06-10", ).save() quantity = 4 trade_bucket = TradeBucket(quantity=quantity, account=account, stock=invest_bucket) trade_bucket.save() assert trade_bucket.current_value() == -quantity
def test_mutation_add_attribute_to_investment(rf, snapshot): """ This submits a massive graphql query to verify all fields work """ # pylint: enable=invalid-name request = rf.post('/graphql') pw1 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9)) request.user = User.objects.create(username='******', password=pw1) bucket = InvestmentBucket(name="i1", public=False, available=100, owner=request.user.profile) bucket.save() client = Client(SCHEMA) executed = client.execute(""" mutation {{ addAttributeToBucket(desc: "{}", bucketId: "{}", isGood: true) {{ bucketAttr {{ text isGood }} }} }} """.format("Test Desc", to_global_id("GInvestmentBucket", bucket.id)), context_value=request) snapshot.assert_match(executed) assert InvestmentBucketDescription.objects.count() == 1
def test_stock_config_value_on(): """ Tests InvestmentStockConfiguration.value_on() """ user = User.objects.create(username='******', password="******") stock = Stock(name="Name1X", ticker="TKRC") stock.save() value = 5 stock.daily_quote.create(value=value, date="2016-06-06") bucket = InvestmentBucket(name="bucket", public=True, owner=user.profile, available=2) bucket.save() quantity = 3 config = InvestmentStockConfiguration(quantity=quantity, stock=stock, bucket=bucket, start="2016-06-08") config.save() with pytest.raises(Exception): config.value_on("2016-06-01") assert config.value_on("2016-06-08") == quantity * value mock_quote = namedtuple('mock_quote', 'value') with mock.patch.object( Stock, "latest_quote", mock.MagicMock(return_value=mock_quote(float('NaN')))): with pytest.raises(Exception): config.value_on()
def test_mutation_delete_attribute(rf, snapshot): """ This submits a massive graphql query to verify all fields work """ # pylint: enable=invalid-name request = rf.post('/graphql') pw1 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9)) request.user = User.objects.create(username='******', password=pw1) bucket = InvestmentBucket(name="i1", public=False, available=100, owner=request.user.profile) bucket.save() attr = InvestmentBucketDescription(text="Blabla", is_good=True, bucket=bucket) attr.save() client = Client(SCHEMA) executed = client.execute(""" mutation {{ deleteAttribute(idValue: "{}") {{ isOk }} }} """.format(to_global_id("GInvestmentBucketDescription", attr.id)), context_value=request) snapshot.assert_match(executed) assert InvestmentBucketDescription.objects.all().count() == 0
def test_bucket_historical(): """ Tests InvestmentBucket.historical() """ user = User.objects.create(username='******', password="******") stock = Stock(name="Name1X", ticker="TKRC") stock.save() value = [3, 5, 7, 2] skip = 2 for idx, val in enumerate(value): stock.daily_quote.create(value=val, date=datetime.datetime.now().date() - datetime.timedelta(days=idx + 2)) available = 2 bucket = InvestmentBucket(name="bucket", public=True, owner=user.profile, available=available) bucket.save() quantity = 3 config = InvestmentStockConfiguration( quantity=quantity, stock=stock, bucket=bucket, start=datetime.datetime.now().date() - datetime.timedelta(days=len(value) + 2)) config.save() historical = bucket.historical(count=len(value), skip=skip) for idx, val in enumerate(value): assert historical[idx] == (datetime.datetime.now().date() - datetime.timedelta(days=idx + 2), val * quantity + available) stock2 = Stock(name="Name2X", ticker="Testes") stock2.save() value = list(range(1, 31)) for val in value: idx = val - 1 stock2.daily_quote.create(value=val, date=datetime.datetime.now().date() - datetime.timedelta(days=idx)) bucket2 = InvestmentBucket(name="bucket2", public=True, owner=user.profile, available=0) bucket2.save() config2 = InvestmentStockConfiguration( quantity=1, stock=stock2, bucket=bucket2, start=datetime.datetime.now().date() - datetime.timedelta(days=len(value))) config2.save() historical2 = bucket2.historical() for val in value: idx = val - 1 assert historical2[idx] == (datetime.datetime.now().date() - datetime.timedelta(days=idx), val)
def test_bucket_value_on(): """ Tests to see if bucket properly handles exception """ user = User.objects.create(username='******', password="******") bucket = InvestmentBucket(name="bucket", public=True, owner=user.profile, available=10) bucket.save() assert bucket.value_on("2016-06-01") == 10
def test_bucket_create_new_bucket(): """ Tests InvestmentBucket.create_new_bucket() """ user1 = User.objects.create(username='******', password="******") user2 = User.objects.create(username='******', password="******") assert user1.profile.owned_bucket.count() == 0 InvestmentBucket.create_new_bucket(name="Bucket1", public=True, owner=user1.profile) InvestmentBucket.create_new_bucket(name="Bucket2", public=True, owner=user2.profile) assert user1.profile.owned_bucket.count() == 1
def test_mutation_add_stock_to_bucket(rf, snapshot): """ This submits a massive graphql query to verify all fields work """ # pylint: enable=invalid-name request = rf.post('/graphql') pw1 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9)) request.user = User.objects.create(username='******', password=pw1) bucket = InvestmentBucket(name="i1", public=False, available=100, owner=request.user.profile) bucket.save() post_save.disconnect(receiver=create_stock, sender=Stock) stock = Stock(name="Google", ticker="GOOGL") stock.save() DailyStockQuote(value=9, date="2017-05-08", stock=stock).save() DailyStockQuote(value=10, date="2017-05-10", stock=stock).save() DailyStockQuote(value=9, date="2017-05-09", stock=stock).save() client = Client(SCHEMA) executed = client.execute(""" mutation {{ addStockToBucket(stockId: "{}", bucketId: "{}", quantity: {}) {{ bucket {{ available isOwner public name stocks {{ edges {{ node {{ quantity stock {{ ticker }} }} }} }} }} }} }} """.format(to_global_id("GStock", stock.id), to_global_id("GInvestmentBucket", bucket.id), 3.5), context_value=request) snapshot.assert_match(executed) assert InvestmentStockConfiguration.objects.count() == 1
def test_trading_acc_trade_bucket(): """ Test trade bucket """ user = user_helper() trading_account = user.profile.trading_accounts.create( account_name="spesh") buffa = InvestmentBucket(name="buffeta", owner=user.profile, public=False, available=1.0) buffa.save() with pytest.raises(Exception): trading_account.trade_bucket(buffa, -2) trading_account.trade_bucket(buffa, 2) with pytest.raises(Exception): trading_account.trade_bucket(buffa, -3) assert trading_account.has_enough_bucket(buffa, 2) trading_account.trade_bucket(buffa, -2) assert trading_account.available_buckets(buffa) == 0
def test_investmentbucket_descrip(): """ Tests InvestmentBucketDescription.change_description() """ user = user_helper() value_of_stock1 = 3 stock1 = Stock.create_new_stock(name="Name1X", ticker="TKRC") stock1.daily_quote.create(value=value_of_stock1, date="2016-06-03") available = 3 bucket = InvestmentBucket(name="Bucket Test", public=True, owner=user.profile, available=available) bucket.save() description = InvestmentBucketDescription(text="fladshjfdsa", is_good=True, bucket=bucket) description.save() description.change_description(text="changed") assert description.text == "changed"
def resolve_invest_suggestions(_data, info, **_args): """ Returns a list of buckets that the User can invest in. (see :py:meth:`stocks.models.InvestmentBucket.available_buckets`) :param info: Information about the user to check which recommendations are best for the user. :type info: Graphene Request Info. :returns: :py:class:`django.db.models.query.QuerySet` of :py:class:`stocks.models.InvestmentBucket` """ return InvestmentBucket.accessible_buckets(info.context.user.profile)
def test_bucket_get_stock_configs(): """ Tests InvestmentBucket.get_stock_configs() """ user1 = User.objects.create(username='******', password="******") stock1 = Stock(name="Name1X", ticker="TKRC") stock2 = Stock(name="Name2X", ticker="TKRCF") stock1.save() stock2.save() bucket = InvestmentBucket(name="Bucket1", public=True, owner=user1.profile, available=1) bucket.save() InvestmentStockConfiguration( quantity=1, stock=stock1, bucket=bucket, start="2016-06-06", end="2016-06-08", ).save() InvestmentStockConfiguration(quantity=1, stock=stock1, bucket=bucket, start="2016-06-08").save() InvestmentStockConfiguration(quantity=1, stock=stock2, bucket=bucket, start="2016-06-06").save() assert bucket.get_stock_configs().count() == 2 assert bucket.get_stock_configs("2016-06-06").count() == 2 assert bucket.get_stock_configs("2016-06-08").count() == 3
def test_investmentbucket_value_on(): """ Tests InvestmentBucket.value_on() """ user = user_helper() value_of_stock1 = 3 stock = Stock.create_new_stock(name="Name1X", ticker="TKRC") stock.daily_quote.create(value=value_of_stock1, date="2016-06-03") available = 3 bucket = InvestmentBucket(name="Bucket Test", public=True, owner=user.profile, available=available) bucket.save() InvestmentStockConfiguration( quantity=1, stock=stock, bucket=bucket, start="2016-06-08", end="2016-06-10", ).save() assert bucket.value_on() == available assert bucket.value_on(date="2016-06-08") == available + value_of_stock1 assert bucket.value_on(date="2016-07-19") == available
def request_create(request): """ Creates a fully functional environment that we can test on """ post_save.disconnect(receiver=create_stock, sender=Stock) stock = Stock(name="Google", ticker="GOOGL") stock.save() pw2 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9)) user2 = User.objects.create(username='******', password=pw2) account2 = TradingAccount(profile=user2.profile, account_name="testAccount2") account2.save() trade2 = Trade(quantity=2, account=account2, stock=stock) trade2.save() pw1 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9)) request.user = User.objects.create(username='******', password=pw1) account1 = TradingAccount(profile=request.user.profile, account_name="testAccount1") account1.save() trade1 = Trade(quantity=1, account=account1, stock=stock) trade1.save() bucket = InvestmentBucket(name="i1", public=False, available=100, owner=request.user.profile) bucket.save() InvestmentBucketDescription(text="Blabla", is_good=True, bucket=bucket).save() DailyStockQuote(value=9, date="2017-05-08", stock=stock).save() DailyStockQuote(value=10, date="2017-05-10", stock=stock).save() InvestmentStockConfiguration(stock=stock, quantity=1, bucket=bucket, start="2017-05-09").save() return request
def test_change_bucket_composition(selenium, live_server, client): """ Test selling a bucket """ user = User.objects.create_user('temporary', '*****@*****.**', 'temporary') user.save() user.userbank.create( item_id='dummy1', access_token='dummy2', institution_name='dummy3', current_balance_field=0, account_name_field="dummy4", income_field=0, expenditure_field=0 ) stock = Stock( name="Name1", ticker="poooooop" ) stock.save() stock.daily_quote.create( value=1000, date="2016-03-03" ) client.login(username='******', password='******') cookie = client.cookies['sessionid'] buck = InvestmentBucket.create_new_bucket( name="IAMATESTBUCKET", public=True, owner=user.profile) buck.save() InvestmentStockConfiguration(quantity=1, stock=stock, bucket=buck, start="2016-03-03").save() assert user.profile.owned_bucket.count() == 1 user.profile.default_acc().trade_bucket(buck, .01) selenium.get('%s%s' % (live_server, '/login')) selenium.add_cookie({ 'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/', }) selenium.get('%s%s' % (live_server, '/home')) selenium.implicitly_wait(10) edit_button = selenium.find_element_by_id("edit-comp") edit_button.click() slider = selenium.find_element_by_class_name("rc-slider-handle-2") actions = ActionChains(selenium) actions.click_and_hold(slider) actions.move_by_offset(-100, 0) actions.release(slider) actions.perform() save_composition = selenium.find_element_by_xpath("//button[contains(.,'Save')]") save_composition.click() time.sleep(1) assert buck.stocks.count() == 2
def test_has_enough_bucket(): """ Test has enough bucket """ user = user_helper() trading_account = user.profile.trading_accounts.create( account_name="spesh") buff = InvestmentBucket(name="buffet", owner=user.profile, public=False, available=0.0) buff.save() assert trading_account.has_enough_bucket(buff, 1) is False trading_account.trade_bucket(buff, 1) assert trading_account.has_enough_bucket(buff, 1) assert trading_account.has_enough_bucket(buff, 2) is False trading_account.trade_bucket(buff, 1000) assert trading_account.has_enough_bucket(buff, 1001) assert trading_account.has_enough_bucket(buff, 1002) is False trading_account.trade_bucket(buff, -1000) assert trading_account.has_enough_bucket(buff, 1) assert trading_account.has_enough_bucket(buff, 2) is False trading_account.trade_bucket(buff, -1) assert trading_account.has_enough_bucket(buff, 1) is False
def test_bucket_add_stock(selenium, live_server, client): """ Test adding stock to bucket """ user = User.objects.create_user('temporary', '*****@*****.**', 'temporary') user.save() user.userbank.create( item_id='dummy1', access_token='dummy2', institution_name='dummy3', current_balance_field=0, account_name_field="dummy4", income_field=0, expenditure_field=0 ) stock = Stock( name="Name1", ticker="poooooop" ) stock.save() stock.daily_quote.create( value=10000, date="2016-03-03" ) client.login(username='******', password='******') cookie = client.cookies['sessionid'] buck = InvestmentBucket.create_new_bucket( name="IAMATESTBUCKET", public=True, owner=user.profile) buck.save() assert user.profile.owned_bucket.count() == 1 selenium.get('%s%s' % (live_server, '/login')) selenium.add_cookie({ 'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/', }) selenium.get('%s%s' % (live_server, '/home')) selenium.implicitly_wait(30) bucket = user.profile.owned_bucket.get(name="IAMATESTBUCKET") assert bucket.get_stock_configs().count() == 0 edit_button = selenium.find_element_by_id("edit-comp") edit_button.click() stock_field = selenium.find_element_by_id("stockname") stock_field.send_keys("Name1") add_stock = selenium.find_element_by_id("add-stock") add_stock.click() save_composition = selenium.find_element_by_xpath("//button[contains(.,'Save')]") save_composition.click() assert bucket.get_stock_configs().count() == 1
def test_bucket_add_attribute(): """ Tests InvestmentBucket.add_attribute() """ user1 = User.objects.create(username='******', password="******") bucket = InvestmentBucket(name="Bucket1", public=True, owner=user1.profile, available=1) bucket.save() assert bucket.description.count() == 0 bucket.add_attribute("Some text") assert bucket.description.count() == 1 attr = bucket.description.get() assert attr.is_good assert attr.text == "Some text" bucket.add_attribute("Some more text", False) assert bucket.description.count() == 2 assert bucket.description.filter(is_good=True).count() == 1 assert bucket.description.filter(is_good=False).count() == 1
def test_add_attr_to_bucket(selenium, live_server, client): """ Test adding attr to bucket """ user = User.objects.create_user('temporary', '*****@*****.**', 'temporary') user.save() user.userbank.create( item_id='dummy1', access_token='dummy2', institution_name='dummy3', current_balance_field=0, account_name_field="dummy4", income_field=0, expenditure_field=0 ) client.login(username='******', password='******') assert user.profile.owned_bucket.count() == 0 cookie = client.cookies['sessionid'] buck = InvestmentBucket.create_new_bucket( name="IAMATESTBUCKET", public=True, owner=user.profile) buck.save() assert user.profile.owned_bucket.count() == 1 selenium.get('%s%s' % (live_server, '/login')) selenium.add_cookie({ 'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/', }) selenium.get('%s%s' % (live_server, '/home')) selenium.implicitly_wait(30) add_attr = selenium.find_element_by_id("launch-edit") add_attr.click() attr_field = selenium.find_element_by_id("name") attr_field.send_keys("poooooop") attr_field.send_keys(Keys.RETURN) time.sleep(1) bucket = user.profile.owned_bucket.get(name="IAMATESTBUCKET") assert bucket.description.get(text="poooooop").text == "poooooop" assert bucket.description.get(text="poooooop").is_good assert bucket.description.count() == 1 attr = selenium.find_element_by_id("attr") assert "poooooop" in attr.text
def test_delete_bucket(selenium, live_server, client): """ Tests deleting a bucket """ user = User.objects.create_user('temporary', '*****@*****.**', 'temporary') user.save() user.userbank.create( item_id='dummy1', access_token='dummy2', institution_name='dummy3', current_balance_field=0, account_name_field="dummy4", income_field=0, expenditure_field=0 ) client.login(username='******', password='******') assert user.profile.owned_bucket.count() == 0 cookie = client.cookies['sessionid'] buck = InvestmentBucket.create_new_bucket( name="IAMATESTBUCKET", public=True, owner=user.profile) buck.save() assert user.profile.owned_bucket.count() == 1 selenium.get('%s%s' % (live_server, '/login')) selenium.add_cookie({ 'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/', }) selenium.get('%s%s' % (live_server, '/home')) selenium.implicitly_wait(30) delete_button = selenium.find_element_by_id("delete") delete_button.click() cancel_delete = selenium.find_element_by_id("keep") cancel_delete.click() WebDriverWait(selenium, 10).until( EC.invisibility_of_element_located((By.ID, "keep")) ) assert user.profile.owned_bucket.count() == 1 delete_button.click() confirm_delete = selenium.find_element_by_id("delete2") confirm_delete.click() assert user.profile.owned_bucket.count() == 0
def test_bucket_trades_for_profile(): """ Tests InvestmentBucket.trades_for_profile() """ user1 = User.objects.create(username='******', password="******") user2 = User.objects.create(username='******', password="******") InvestmentBucket(name="B1", owner=user1.profile, public=False, available=1).save() InvestmentBucket(name="B2", owner=user1.profile, public=True, available=1).save() InvestmentBucket(name="B3", owner=user1.profile, public=False, available=1).save() InvestmentBucket(name="B4", owner=user2.profile, public=False, available=1).save() assert InvestmentBucket.accessible_buckets(user1.profile).count() == 3 assert InvestmentBucket.accessible_buckets(user2.profile).count() == 2
def test_bucket_sell_all(): """ Tests InvestmentBucket._sell_all() """ user1 = User.objects.create(username='******', password="******") stock1 = Stock(name="Name1X", ticker="TKRC") stock1.save() DailyStockQuote(date="2016-06-10", value=100.0, stock=stock1).save() bucket = InvestmentBucket(name="Bucket1", public=True, owner=user1.profile, available=10) bucket.save() cfg1 = InvestmentStockConfiguration( quantity=1, stock=stock1, bucket=bucket, start="2016-06-06", end="2016-06-08", ) cfg2 = InvestmentStockConfiguration( quantity=1, stock=stock1, bucket=bucket, start="2016-06-08", ) cfg1.save() cfg2.save() # pylint: disable=protected-access bucket._sell_all() # pylint: enable=protected-access bucket.refresh_from_db() cfg1.refresh_from_db() cfg2.refresh_from_db() assert bucket.available == 110 assert cfg1.end == datetime.date(2016, 6, 8) assert cfg2.end is not None
def test_trading_available_buckets(): """ Testing TradingAccount.available_buckets() """ user = user_helper() bucket1 = InvestmentBucket(name='b1', public=False, available=1000, owner=user.profile) bucket2 = InvestmentBucket(name='b2', public=False, available=1000, owner=user.profile) bucket1.save() bucket2.save() acc = user.profile.trading_accounts.create(account_name="acc") assert acc.available_buckets(bucket1) == 0 acc.buckettrades.create(quantity=2, stock=bucket1) assert acc.available_buckets(bucket1) == 2 acc.buckettrades.create(quantity=4, stock=bucket1) assert acc.available_buckets(bucket2) == 0 acc.buckettrades.create(quantity=3, stock=bucket2) assert acc.available_buckets(bucket1) == 6 assert acc.available_buckets(bucket2) == 3
def test_bucket_change_config(): """ Tests InvestmentBucket.change_config() """ cfg_str = namedtuple("cfg_str", ["id", "quantity"]) user1 = User.objects.create(username='******', password="******") stock1 = Stock(name="Name1X", ticker="TKRC") stock1.save() DailyStockQuote(date="2016-06-10", value=100.0, stock=stock1).save() bucket = InvestmentBucket(name="Bucket1", public=True, owner=user1.profile, available=10) bucket.save() cfg1 = InvestmentStockConfiguration( quantity=1, stock=stock1, bucket=bucket, start="2016-06-06", end="2016-06-08", ) cfg2 = InvestmentStockConfiguration( quantity=1, stock=stock1, bucket=bucket, start="2016-06-08", ) cfg1.save() cfg2.save() with pytest.raises(Exception): bucket.change_config([cfg_str(id=stock1.id, quantity=2)]) bucket.available = 1000 bucket.change_config([cfg_str(id=stock1.id, quantity=2)]) bucket.refresh_from_db() assert bucket.available == 900 assert bucket.stocks.filter(end=None).values('stock_id').annotate( sum_q=Sum('quantity')).get()['sum_q'] == 2
def test_mutation_attribute_permission(rf, snapshot): """ This submits a massive graphql query to verify all fields work """ # pylint: enable=invalid-name request = rf.post('/graphql') pw2 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9)) user2 = User.objects.create(username='******', password=pw2) pw1 = ''.join(random.choices(string.ascii_uppercase + string.digits, k=9)) request.user = User.objects.create(username='******', password=pw1) bucket = InvestmentBucket(name="i1", public=False, available=100, owner=user2.profile) bucket.save() attr = InvestmentBucketDescription(text="desc1", bucket=bucket, is_good=True) attr.save() client = Client(SCHEMA) executed = client.execute(""" mutation {{ addAttributeToBucket(desc: "{}", bucketId: "{}", isGood: true) {{ bucketAttr {{ isGood }} }} }} """.format("Test Desc", to_global_id("GInvestmentBucket", bucket.id)), context_value=request) snapshot.assert_match(executed) executed = client.execute(""" mutation {{ editAttribute(desc: "{}", idValue: "{}") {{ bucketAttr {{ isGood }} }} }} """.format("Test Desc", to_global_id("GInvestmentBucketDescription", attr.id)), context_value=request) snapshot.assert_match(executed) executed = client.execute(""" mutation {{ deleteAttribute(idValue: "{}") {{ isOk }} }} """.format(to_global_id("GInvestmentBucketDescription", attr.id)), context_value=request) snapshot.assert_match(executed) executed = client.execute(""" mutation {{ addStockToBucket(stockId: "{}", bucketId: "{}", quantity: {}) {{ bucket {{ id }} }} }} """.format(to_global_id("GStock", 1), to_global_id("GInvestmentBucket", bucket.id), 3.5), context_value=request) snapshot.assert_match(executed) assert InvestmentBucketDescription.objects.count() == 1