2025-03-07 17:35:55 -05:00
|
|
|
require "test_helper"
|
|
|
|
|
2025-04-14 11:40:34 -04:00
|
|
|
class Holding::PortfolioCacheTest < ActiveSupport::TestCase
|
|
|
|
include EntriesTestHelper, ProviderTestHelper
|
2025-03-07 17:35:55 -05:00
|
|
|
|
|
|
|
setup do
|
2025-03-17 11:54:53 -04:00
|
|
|
@provider = mock
|
|
|
|
Security.stubs(:provider).returns(@provider)
|
|
|
|
|
|
|
|
@account = families(:empty).accounts.create!(
|
|
|
|
name: "Test Brokerage",
|
|
|
|
balance: 10000,
|
|
|
|
currency: "USD",
|
|
|
|
accountable: Investment.new
|
|
|
|
)
|
|
|
|
|
|
|
|
@security = Security.create!(name: "Test Security", ticker: "TEST", exchange_operating_mic: "TEST")
|
|
|
|
|
2025-04-14 11:40:34 -04:00
|
|
|
@trade = create_trade(@security, account: @account, qty: 1, date: 2.days.ago.to_date, price: 210.23).trade
|
2025-03-07 17:35:55 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
test "gets price from DB if available" do
|
2025-03-17 11:54:53 -04:00
|
|
|
db_price = 210
|
2025-03-07 17:35:55 -05:00
|
|
|
|
2025-03-17 11:54:53 -04:00
|
|
|
Security::Price.create!(
|
|
|
|
security: @security,
|
|
|
|
date: Date.current,
|
|
|
|
price: db_price
|
|
|
|
)
|
|
|
|
|
2025-04-14 11:40:34 -04:00
|
|
|
cache = Holding::PortfolioCache.new(@account)
|
2025-03-17 11:54:53 -04:00
|
|
|
assert_equal db_price, cache.get_price(@security.id, Date.current).price
|
2025-03-07 17:35:55 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
test "if no price from db, try getting the price from trades" do
|
2025-03-17 11:54:53 -04:00
|
|
|
Security::Price.destroy_all
|
2025-03-07 17:35:55 -05:00
|
|
|
|
2025-04-14 11:40:34 -04:00
|
|
|
cache = Holding::PortfolioCache.new(@account)
|
2025-03-17 11:54:53 -04:00
|
|
|
assert_equal @trade.price, cache.get_price(@security.id, @trade.entry.date).price
|
2025-03-07 17:35:55 -05:00
|
|
|
end
|
|
|
|
|
2025-05-15 10:19:56 -04:00
|
|
|
test "if no price from db or trades, search holdings" do
|
2025-03-17 11:54:53 -04:00
|
|
|
Security::Price.delete_all
|
2025-04-14 11:40:34 -04:00
|
|
|
Entry.delete_all
|
2025-03-07 17:35:55 -05:00
|
|
|
|
2025-04-14 11:40:34 -04:00
|
|
|
holding = Holding.create!(
|
2025-03-17 11:54:53 -04:00
|
|
|
security: @security,
|
|
|
|
account: @account,
|
|
|
|
date: Date.current,
|
|
|
|
qty: 1,
|
|
|
|
price: 250,
|
|
|
|
amount: 250 * 1,
|
|
|
|
currency: "USD"
|
|
|
|
)
|
2025-03-07 17:35:55 -05:00
|
|
|
|
2025-04-14 11:40:34 -04:00
|
|
|
cache = Holding::PortfolioCache.new(@account, use_holdings: true)
|
2025-03-17 11:54:53 -04:00
|
|
|
assert_equal holding.price, cache.get_price(@security.id, holding.date).price
|
2025-03-07 17:35:55 -05:00
|
|
|
end
|
|
|
|
end
|