tank-tests 0.47.0

Test suite for drivers of Tank: the Rust data layer. This is intended to be used by drivers to implement common unit tests.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#![allow(unused_imports)]
use rust_decimal::Decimal;
use std::{collections::BTreeMap, pin::pin, str::FromStr, sync::LazyLock};
use tank::{
    AsValue, Driver, DynQuery, Entity, Executor, FixedDecimal, Query, QueryResult, RawQuery,
    Result, RowsAffected, Sql, SqlWriter, Value,
    stream::{StreamExt, TryStreamExt},
};
use time::macros::datetime;
use tokio::sync::Mutex;
use uuid::{Uuid, uuid};

static MUTEX: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

#[derive(Entity, Debug, PartialEq)]
#[tank(schema = "trading", name = "trade_execution", primary_key = ("trade_id", "execution_time"))]
pub struct Trade {
    #[tank(name = "trade_id")]
    pub trade: u64,
    #[tank(name = "order_id", default = uuid!("241d362d-797e-4769-b3f6-412440c8cf68").as_value())]
    pub order: Uuid,
    /// Ticker symbol
    pub symbol: String,
    #[cfg(not(feature = "disable-arrays"))]
    pub isin: [char; 12],
    pub price: FixedDecimal<18, 4>,
    pub quantity: u32,
    pub execution_time: time::PrimitiveDateTime,
    pub currency: Option<String>,
    pub is_internalized: bool,
    /// Exchange
    pub venue: Option<String>,
    #[cfg(not(feature = "disable-lists"))]
    pub child_trade_ids: Option<Vec<i64>>,
    pub metadata: Option<Box<[u8]>>,
    #[cfg(not(feature = "disable-maps"))]
    pub tags: Option<BTreeMap<String, String>>,
}

pub async fn trade_simple(executor: &mut impl Executor) -> Result<()> {
    let _lock = MUTEX.lock().await;

    // Setup
    Trade::drop_table(executor, true, false).await?;
    Trade::create_table(executor, false, true).await?;

    // Trade object
    let trade = Trade {
        trade: 46923,
        order: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
        symbol: "RIVN".to_string(),
        #[cfg(not(feature = "disable-arrays"))]
        isin: std::array::from_fn(|i| "US76954A1034".chars().nth(i).unwrap()),
        price: Decimal::new(1226, 2).into(), // 12.26
        quantity: 500,
        execution_time: datetime!(2025-06-07 14:32:00).into(),
        currency: Some("USD".into()),
        is_internalized: true,
        venue: Some("NASDAQ".into()),
        #[cfg(not(feature = "disable-lists"))]
        child_trade_ids: vec![36209, 85320].into(),
        metadata: b"Metadata Bytes".to_vec().into_boxed_slice().into(),
        #[cfg(not(feature = "disable-maps"))]
        tags: BTreeMap::from_iter([
            ("source".into(), "internal".into()),
            ("strategy".into(), "scalping".into()),
        ])
        .into(),
    };

    // Expect to find no trades
    let result = Trade::find_one(executor, trade.primary_key_expr()).await?;
    assert!(result.is_none(), "Expected no trades at this time");
    assert_eq!(
        Trade::find_many(executor, true, None)
            .map(Result::unwrap)
            .count()
            .await,
        0
    );

    // Save a trade
    trade.save(executor).await?;

    // Expect to find the only trade
    let result = Trade::find_one(executor, trade.primary_key_expr()).await?;
    assert!(
        result.is_some(),
        "Expected Trade::find_one to return some result",
    );
    let result = result.unwrap();
    assert_eq!(result.trade, 46923);
    assert_eq!(
        result.order,
        Uuid::from_str("550e8400-e29b-41d4-a716-446655440000").unwrap()
    );
    assert_eq!(result.symbol, "RIVN");
    #[cfg(not(feature = "disable-arrays"))]
    assert_eq!(
        result
            .isin
            .iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>()
            .join(""),
        "US76954A1034"
    );
    assert_eq!(result.price, Decimal::new(1226, 2).into());
    assert_eq!(result.quantity, 500);
    assert_eq!(result.execution_time, datetime!(2025-06-07 14:32:00));
    assert_eq!(result.currency, Some("USD".into()));
    assert_eq!(result.is_internalized, true);
    assert_eq!(result.venue, Some("NASDAQ".into()));
    #[cfg(not(feature = "disable-lists"))]
    assert_eq!(result.child_trade_ids, Some(vec![36209, 85320]));
    assert_eq!(
        result.metadata,
        Some(b"Metadata Bytes".to_vec().into_boxed_slice())
    );
    #[cfg(not(feature = "disable-maps"))]
    let Some(tags) = result.tags else {
        unreachable!("Tag is expected");
    };
    #[cfg(not(feature = "disable-maps"))]
    assert_eq!(tags.len(), 2);
    #[cfg(not(feature = "disable-maps"))]
    assert_eq!(
        tags,
        BTreeMap::from_iter([
            ("source".into(), "internal".into()),
            ("strategy".into(), "scalping".into())
        ])
    );

    assert_eq!(
        Trade::find_many(executor, true, None)
            .map(Result::unwrap)
            .count()
            .await,
        1
    );
    Ok(())
}

pub async fn trade_multiple(executor: &mut impl Executor) -> Result<()> {
    let _lock = MUTEX.lock().await;

    // Setup
    Trade::drop_table(executor, false, false).await?;
    Trade::create_table(executor, false, true).await?;

    // Trade objects
    let trades = vec![
        Trade {
            trade: 10001,
            order: Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),
            symbol: "AAPL".to_string(),
            #[cfg(not(feature = "disable-arrays"))]
            isin: std::array::from_fn(|i| "US0378331005".chars().nth(i).unwrap()),
            price: Decimal::new(15000, 2).into(),
            quantity: 10,
            execution_time: datetime!(2025-06-01 09:00:00).into(),
            currency: Some("USD".into()),
            is_internalized: false,
            venue: Some("NASDAQ".into()),
            #[cfg(not(feature = "disable-lists"))]
            child_trade_ids: Some(vec![101, 102]),
            metadata: Some(b"First execution".to_vec().into_boxed_slice()),
            #[cfg(not(feature = "disable-maps"))]
            tags: Some(BTreeMap::from_iter([
                ("source".into(), "algo".into()),
                ("strategy".into(), "momentum".into()),
            ])),
        },
        Trade {
            trade: 10002,
            order: Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap(),
            symbol: "GOOG".to_string(),
            #[cfg(not(feature = "disable-arrays"))]
            isin: std::array::from_fn(|i| "US02079K3059".chars().nth(i).unwrap()),
            price: Decimal::new(280000, 3).into(), // 280.000
            quantity: 5,
            execution_time: datetime!(2025-06-02 10:15:30).into(),
            currency: Some("USD".into()),
            is_internalized: true,
            venue: Some("NYSE".into()),
            #[cfg(not(feature = "disable-lists"))]
            child_trade_ids: None,
            metadata: Some(b"Second execution".to_vec().into_boxed_slice()),
            #[cfg(not(feature = "disable-maps"))]
            tags: Some(BTreeMap::from_iter([
                ("source".into(), "internal".into()),
                ("strategy".into(), "mean_reversion".into()),
            ])),
        },
        Trade {
            trade: 10003,
            order: Uuid::parse_str("33333333-3333-3333-3333-333333333333").unwrap(),
            symbol: "MSFT".to_string(),
            #[cfg(not(feature = "disable-arrays"))]
            isin: std::array::from_fn(|i| "US5949181045".chars().nth(i).unwrap()),
            price: Decimal::new(32567, 2).into(), // 325.67
            quantity: 20,
            execution_time: datetime!(2025-06-03 11:45:00).into(),
            currency: Some("USD".into()),
            is_internalized: false,
            venue: Some("BATS".into()),
            #[cfg(not(feature = "disable-lists"))]
            child_trade_ids: Some(vec![301]),
            metadata: Some(b"Third execution".to_vec().into_boxed_slice()),
            #[cfg(not(feature = "disable-maps"))]
            tags: Some(BTreeMap::from_iter([
                ("sourcev".into(), "external".into()),
                ("strategy".into(), "arbitrage".into()),
            ])),
        },
        Trade {
            trade: 10004,
            order: Uuid::parse_str("44444444-4444-4444-4444-444444444444").unwrap(),
            symbol: "TSLA".to_string(),
            #[cfg(not(feature = "disable-arrays"))]
            isin: std::array::from_fn(|i| "US88160R1014".chars().nth(i).unwrap()),
            price: Decimal::new(62000, 2).into(), // 620.00
            quantity: 15,
            execution_time: datetime!(2025-06-04 14:00:00).into(),
            currency: Some("USD".into()),
            is_internalized: true,
            venue: Some("CBOE".into()),
            #[cfg(not(feature = "disable-lists"))]
            child_trade_ids: None,
            metadata: None,
            #[cfg(not(feature = "disable-maps"))]
            tags: Some(BTreeMap::from_iter([
                ("source".into(), "manual".into()),
                ("strategy".into(), "news_event".into()),
            ])),
        },
        Trade {
            trade: 10005,
            order: Uuid::parse_str("55555555-5555-5555-5555-555555555555").unwrap(),
            symbol: "AMZN".to_string(),
            #[cfg(not(feature = "disable-arrays"))]
            isin: std::array::from_fn(|i| "US0231351067".chars().nth(i).unwrap()),
            price: Decimal::new(134899, 3).into(), // 1348.99
            quantity: 8,
            execution_time: datetime!(2025-06-05 16:30:00).into(),
            currency: Some("USD".into()),
            is_internalized: false,
            venue: Some("NASDAQ".into()),
            #[cfg(not(feature = "disable-lists"))]
            child_trade_ids: Some(vec![501, 502, 503]),
            metadata: Some(b"Fifth execution".to_vec().into_boxed_slice()),
            #[cfg(not(feature = "disable-maps"))]
            tags: Some(BTreeMap::from_iter([
                ("source".into(), "internal".into()),
                ("strategy".into(), "scalping".into()),
            ])),
        },
    ];

    // Insert 5 trades
    let affected = Trade::insert_many(executor, &trades).await?;
    if let Some(affected) = affected.rows_affected {
        assert_eq!(affected, 5);
    }

    // Find 5 trades
    let data = Trade::find_many(executor, true, None)
        .try_collect::<Vec<_>>()
        .await?;
    assert_eq!(data.len(), 5, "Expect to find 5 trades");

    // Verify data integrity
    for (i, expected) in trades.iter().enumerate() {
        let actual_a = &trades[i];
        let actual_b = Trade::find_one(executor, expected.primary_key_expr()).await?;
        let Some(actual_b) = actual_b else {
            panic!("Trade {} not found", expected.trade);
        };

        assert_eq!(actual_a.trade, expected.trade);
        assert_eq!(actual_b.trade, expected.trade);

        assert_eq!(actual_a.order, expected.order);
        assert_eq!(actual_b.order, expected.order);

        assert_eq!(actual_a.symbol, expected.symbol);
        assert_eq!(actual_b.symbol, expected.symbol);

        assert_eq!(actual_a.price, expected.price);
        assert_eq!(actual_b.price, expected.price);

        assert_eq!(actual_a.quantity, expected.quantity);
        assert_eq!(actual_b.quantity, expected.quantity);

        assert_eq!(actual_a.execution_time, expected.execution_time);
        assert_eq!(actual_b.execution_time, expected.execution_time);

        assert_eq!(actual_a.currency, expected.currency);
        assert_eq!(actual_b.currency, expected.currency);

        assert_eq!(actual_a.is_internalized, expected.is_internalized);
        assert_eq!(actual_b.is_internalized, expected.is_internalized);

        assert_eq!(actual_a.venue, expected.venue);
        assert_eq!(actual_b.venue, expected.venue);

        #[cfg(not(feature = "disable-lists"))]
        assert_eq!(actual_a.child_trade_ids, expected.child_trade_ids);
        #[cfg(not(feature = "disable-lists"))]
        assert_eq!(actual_b.child_trade_ids, expected.child_trade_ids);

        assert_eq!(actual_a.metadata, expected.metadata);
        assert_eq!(actual_b.metadata, expected.metadata);

        #[cfg(not(feature = "disable-maps"))]
        assert_eq!(actual_a.tags, expected.tags);
        #[cfg(not(feature = "disable-maps"))]
        assert_eq!(actual_b.tags, expected.tags);
    }

    // Multiple statements
    #[cfg(not(feature = "disable-multiple-statements"))]
    {
        let writer = executor.driver().sql_writer();
        let mut query = DynQuery::default();
        writer.write_delete(&mut query, Trade::table(), true);
        writer.write_insert(
            &mut query,
            Sql.insert_into(Trade::table()).values(&[Trade {
                trade: 10002,
                order: Uuid::parse_str("895dc048-be92-4a55-afbf-38a60936e844").unwrap(),
                symbol: "RIVN".to_string(),
                #[cfg(not(feature = "disable-arrays"))]
                isin: std::array::from_fn(|i| "US76954A1034".chars().nth(i).unwrap()),
                price: Decimal::new(1345, 2).into(),
                quantity: 3200,
                execution_time: datetime!(2025-06-01 10:15:30).into(),
                currency: Some("USD".into()),
                is_internalized: true,
                venue: Some("NASDAQ".into()),
                #[cfg(not(feature = "disable-lists"))]
                child_trade_ids: Some(vec![201]),
                metadata: Some(
                    b"desc: \"Crossed with internal liquidity\", id:'\\X696E7465726E616C'"
                        .to_vec()
                        .into_boxed_slice(),
                ),
                #[cfg(not(feature = "disable-maps"))]
                tags: Some(BTreeMap::from_iter([
                    ("source".into(), "internal".into()),
                    ("strategy".into(), "arbitrage".into()),
                    ("risk_limit".into(), "high".into()),
                ])),
            }]),
        );
        writer.write_select(
            &mut query,
            Sql.select(Trade::columns())
                .from(Trade::table())
                .where_expr(true),
        );
        let mut stream = pin!(executor.run(query));
        let Some(QueryResult::Affected(RowsAffected { rows_affected, .. })) =
            stream.try_next().await?
        else {
            panic!("Could not get the result of the first query");
        };
        if let Some(rows_affected) = rows_affected {
            assert_eq!(rows_affected, 5);
        }
        let Some(QueryResult::Affected(RowsAffected { rows_affected, .. })) =
            stream.try_next().await?
        else {
            panic!("Could not get the result of the first statement");
        };
        if let Some(rows_affected) = rows_affected {
            assert_eq!(rows_affected, 1);
        }
        let Some(QueryResult::Row(row)) = stream.try_next().await? else {
            panic!("Could not get the result of the second statement");
        };
        let trade = Trade::from_row(row)?;
        assert!(stream.try_next().await?.is_none());
        assert_eq!(
            trade,
            Trade {
                trade: 10002,
                order: Uuid::parse_str("895dc048-be92-4a55-afbf-38a60936e844").unwrap(),
                symbol: "RIVN".to_string(),
                #[cfg(not(feature = "disable-arrays"))]
                isin: std::array::from_fn(|i| "US76954A1034".chars().nth(i).unwrap()),
                price: Decimal::new(1345, 2).into(),
                quantity: 3200,
                execution_time: datetime!(2025-06-01 10:15:30).into(),
                currency: Some("USD".into()),
                is_internalized: true,
                venue: Some("NASDAQ".into()),
                #[cfg(not(feature = "disable-lists"))]
                child_trade_ids: Some(vec![201]),
                metadata: Some(
                    b"desc: \"Crossed with internal liquidity\", id:'\\X696E7465726E616C'"
                        .to_vec()
                        .into_boxed_slice(),
                ),
                #[cfg(not(feature = "disable-maps"))]
                tags: Some(BTreeMap::from_iter([
                    ("source".into(), "internal".into()),
                    ("strategy".into(), "arbitrage".into()),
                    ("risk_limit".into(), "high".into()),
                ])),
            }
        );
    }
    Ok(())
}