|
| 1 | +import ib_async as ibi |
| 2 | +from ib_async import IB, Stock |
| 3 | +from ib_async.ticker import Ticker |
| 4 | + |
| 5 | + |
| 6 | +def test_tickNews_populates_contract_from_active_ticker(): |
| 7 | + """When a ticker is registered for the incoming reqId (the normal |
| 8 | + streaming-news flow via reqMktData), the emitted NewsTick carries the |
| 9 | + originating contract as a typed snapshot.""" |
| 10 | + ib = IB() |
| 11 | + contract = Stock("AAPL", "SMART", "USD") |
| 12 | + ib.wrapper.reqId2Ticker[1] = Ticker(contract=contract, defaults=ib.wrapper.defaults) |
| 13 | + |
| 14 | + captured: list[ibi.NewsTick] = [] |
| 15 | + ib.tickNewsEvent += captured.append |
| 16 | + |
| 17 | + ib.wrapper.tickNews( |
| 18 | + 1, |
| 19 | + 1_700_000_000, |
| 20 | + "BRFG", |
| 21 | + "BRFG$abc", |
| 22 | + "Apple announces new chip", |
| 23 | + "", |
| 24 | + ) |
| 25 | + |
| 26 | + assert len(captured) == 1 |
| 27 | + news = captured[0] |
| 28 | + assert news.headline == "Apple announces new chip" |
| 29 | + assert news.contract is not None |
| 30 | + assert news.contract.symbol == "AAPL" |
| 31 | + assert news.contract.secType == "STK" |
| 32 | + # recreate() returns a new instance so the snapshot is independent of |
| 33 | + # later mutations on the original contract. |
| 34 | + assert news.contract is not contract |
| 35 | + |
| 36 | + |
| 37 | +def test_tickNews_falls_back_to_reqId2Contract(): |
| 38 | + """When no ticker is registered but the reqId exists in the generic |
| 39 | + request-contract map, the fallback lookup still populates the contract.""" |
| 40 | + ib = IB() |
| 41 | + contract = Stock("MSFT", "SMART", "USD") |
| 42 | + ib.wrapper._reqId2Contract[42] = contract |
| 43 | + |
| 44 | + captured: list[ibi.NewsTick] = [] |
| 45 | + ib.tickNewsEvent += captured.append |
| 46 | + |
| 47 | + ib.wrapper.tickNews(42, 1_700_000_000, "BRFG", "BRFG$x", "Headline", "") |
| 48 | + |
| 49 | + assert len(captured) == 1 |
| 50 | + assert captured[0].contract is not None |
| 51 | + assert captured[0].contract.symbol == "MSFT" |
| 52 | + |
| 53 | + |
| 54 | +def test_tickNews_contract_none_when_reqId_unknown(): |
| 55 | + """When neither map knows the reqId, the NewsTick still emits with |
| 56 | + contract=None rather than raising.""" |
| 57 | + ib = IB() |
| 58 | + captured: list[ibi.NewsTick] = [] |
| 59 | + ib.tickNewsEvent += captured.append |
| 60 | + |
| 61 | + ib.wrapper.tickNews(999, 1_700_000_000, "BRFG", "BRFG$x", "Headline", "") |
| 62 | + |
| 63 | + assert len(captured) == 1 |
| 64 | + assert captured[0].contract is None |
0 commit comments