rpytest-core 0.1.2

Core types and abstractions for rpytest
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! Request and response types for the IPC protocol.

use serde::{Deserialize, Serialize};

/// Current protocol version. Increment when breaking changes are made.
pub const PROTOCOL_VERSION: u32 = 1;

/// Test node information returned from daemon.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TestNodeInfo {
    /// Unique node ID (pytest format).
    pub node_id: String,
    /// File path relative to repo root.
    pub file_path: String,
    /// Line number where test is defined.
    pub lineno: Option<u32>,
    /// Test function/method name.
    pub name: String,
    /// Parent class name (if method).
    pub class_name: Option<String>,
    /// Markers attached to this test.
    pub markers: Vec<String>,
    /// Whether test is marked as skip.
    pub skip: bool,
    /// Whether test is marked as xfail.
    pub xfail: bool,
}

/// Commands sent from CLI to daemon.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Request {
    /// Initialize a repository context within the daemon.
    InitContext {
        /// Protocol version for compatibility checking.
        protocol_version: u32,
        /// Absolute path to the repository root.
        repo_path: String,
        /// Optional path to Python interpreter.
        python_path: Option<String>,
        /// Execution mode: "embedded", "subprocess", or "auto".
        #[serde(default)]
        execution_mode: Option<String>,
    },

    /// Collect tests for a repository context.
    Collect {
        /// Context identifier returned from InitContext.
        context_id: String,
        /// Force full re-collection even if cache is valid.
        force: bool,
    },

    /// Run a set of tests.
    Run {
        /// Context identifier.
        context_id: String,
        /// List of test node IDs to run.
        node_ids: Vec<String>,
        /// Number of parallel workers (None = auto).
        workers: Option<u32>,
        /// Stop after N failures.
        maxfail: Option<u32>,
    },

    /// List tests matching filters (without running).
    List {
        /// Context identifier.
        context_id: String,
        /// Keyword expression filter.
        keyword: Option<String>,
        /// Marker expression filter.
        marker: Option<String>,
    },

    /// Get detailed inventory with full test metadata.
    GetInventory {
        /// Context identifier.
        context_id: String,
    },

    /// Get worker pool status.
    GetWorkerStatus {
        /// Context identifier.
        context_id: String,
    },

    /// Configure worker pool.
    ConfigureWorkers {
        /// Context identifier.
        context_id: String,
        /// Number of workers to maintain.
        num_workers: u32,
    },

    /// Shutdown the daemon or a specific context.
    Shutdown {
        /// If Some, shutdown only this context. If None, shutdown entire daemon.
        context_id: Option<String>,
    },

    /// Health check / ping.
    Ping,

    /// Start a streaming run (returns run_id, results come via GetRunProgress).
    RunStream {
        /// Context identifier.
        context_id: String,
        /// List of test node IDs to run.
        node_ids: Vec<String>,
        /// Number of parallel workers (None = auto).
        workers: Option<u32>,
        /// Stop after N failures.
        maxfail: Option<u32>,
    },

    /// Get progress and results from a streaming run.
    GetRunProgress {
        /// Context identifier.
        context_id: String,
        /// Run identifier from RunStream response.
        run_id: String,
    },

    // --- Phase 5: Flakiness ---
    /// Get flakiness report for all tracked tests.
    GetFlakinessReport {
        /// Context identifier.
        context_id: String,
    },

    /// Get flakiness info for a specific test.
    GetTestFlakiness {
        /// Context identifier.
        context_id: String,
        /// Test node ID.
        node_id: String,
    },

    /// Configure auto-rerun behavior.
    ConfigureRerun {
        /// Context identifier.
        context_id: String,
        /// Enable auto-rerun.
        enabled: bool,
        /// Maximum reruns per test.
        max_reruns: u32,
        /// Only rerun known flaky tests.
        only_flaky: bool,
        /// Delay between reruns in milliseconds.
        delay_ms: u32,
    },

    /// Get current rerun configuration.
    GetRerunConfig {
        /// Context identifier.
        context_id: String,
    },

    /// Run tests with auto-rerun enabled.
    RunWithRerun {
        /// Context identifier.
        context_id: String,
        /// List of test node IDs to run.
        node_ids: Vec<String>,
        /// Number of parallel workers (None = auto).
        workers: Option<u32>,
        /// Stop after N failures.
        maxfail: Option<u32>,
    },

    // --- Phase 5: Fixtures ---
    /// Configure session fixture reuse.
    ConfigureFixtureReuse {
        /// Context identifier.
        context_id: String,
        /// Enable fixture reuse.
        enabled: bool,
        /// Max fixture age in seconds.
        max_age_seconds: f64,
        /// Teardown on conftest.py changes.
        teardown_on_conftest_change: bool,
    },

    /// Get fixture configuration.
    GetFixtureConfig {
        /// Context identifier.
        context_id: String,
    },

    /// Get session status.
    GetSessionStatus {
        /// Context identifier.
        context_id: String,
    },

    // --- Phase 5: Sharding ---
    /// Get tests for a specific shard.
    GetShard {
        /// Context identifier.
        context_id: String,
        /// Tests to shard (empty = all inventory).
        node_ids: Vec<String>,
        /// This shard's index (0-based).
        shard_index: u32,
        /// Total number of shards.
        total_shards: u32,
        /// Sharding strategy.
        strategy: String,
    },

    /// Get sharding distribution info.
    GetShardInfo {
        /// Context identifier.
        context_id: String,
        /// Tests to shard (empty = all inventory).
        node_ids: Vec<String>,
        /// Total number of shards.
        total_shards: u32,
        /// Sharding strategy.
        strategy: String,
    },
}

/// Responses sent from daemon to CLI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Response {
    /// Context successfully initialized.
    ContextReady {
        /// Protocol version for compatibility checking.
        protocol_version: u32,
        /// Unique context identifier.
        context_id: String,
        /// Hash of the current inventory for cache validation.
        inventory_hash: String,
    },

    /// Collection completed.
    CollectionComplete {
        /// Number of test nodes collected.
        node_count: usize,
        /// Collection duration in milliseconds.
        duration_ms: u64,
    },

    /// List of test node IDs matching the query.
    TestList {
        /// Matching node IDs.
        node_ids: Vec<String>,
    },

    /// Detailed inventory data.
    InventoryData {
        /// Inventory hash for cache validation.
        hash: String,
        /// Collection timestamp (Unix epoch ms).
        collected_at: u64,
        /// Test nodes with metadata.
        nodes: Vec<TestNodeInfo>,
    },

    /// Run completed.
    RunComplete {
        /// Total tests run.
        total: usize,
        /// Tests passed.
        passed: usize,
        /// Tests failed.
        failed: usize,
        /// Tests skipped.
        skipped: usize,
        /// Tests errored.
        errors: usize,
        /// Total duration in milliseconds.
        duration_ms: u64,
    },

    /// Worker pool status.
    WorkerStatus {
        /// Number of active workers.
        active_workers: u32,
        /// Number of idle workers.
        idle_workers: u32,
        /// Total tests executed by pool.
        tests_executed: u64,
        /// Average test duration in milliseconds.
        avg_test_duration_ms: u64,
    },

    /// Worker configuration acknowledged.
    WorkerConfigAck {
        /// New number of workers.
        num_workers: u32,
    },

    /// Shutdown acknowledged.
    ShutdownAck,

    /// Pong response to ping.
    Pong,

    /// Streaming run started.
    RunStarted {
        /// Unique run identifier for polling progress.
        run_id: String,
        /// Total tests to run.
        total_tests: usize,
    },

    /// Progress update with any completed test results.
    RunProgress {
        /// Run identifier.
        run_id: String,
        /// Total tests in this run.
        total: usize,
        /// Tests completed so far.
        completed: usize,
        /// Tests currently running.
        running: usize,
        /// Whether the run is complete.
        done: bool,
        /// Newly completed test results since last poll.
        results: Vec<TestResultInfo>,
    },

    /// Error response.
    Error {
        /// Error category.
        code: ErrorCode,
        /// Human-readable error message.
        message: String,
    },

    // --- Phase 5: Flakiness Responses ---
    /// Flakiness report for tracked tests.
    FlakinessReport {
        /// Tests identified as flaky.
        flaky_tests: Vec<FlakinessInfo>,
        /// Tests with some failures but not flaky.
        unstable_tests: Vec<FlakinessInfo>,
        /// Count of stable tests.
        stable_count: usize,
        /// Total tests tracked.
        total_tracked: usize,
    },

    /// Flakiness info for a single test.
    TestFlakiness {
        /// Test node ID.
        node_id: String,
        /// Failure rate (0.0-1.0).
        failure_rate: f64,
        /// Whether test is considered flaky.
        is_flaky: bool,
        /// Number of outcome flips.
        flaky_streak: u32,
        /// Consecutive failures.
        consecutive_failures: u32,
        /// Consecutive passes.
        consecutive_passes: u32,
        /// Total runs.
        total_runs: u32,
        /// Recent outcomes.
        recent_outcomes: Vec<String>,
    },

    /// Rerun configuration.
    RerunConfig {
        /// Whether enabled.
        enabled: bool,
        /// Max reruns per test.
        max_reruns: u32,
        /// Only rerun known flaky.
        only_flaky: bool,
        /// Delay between reruns ms.
        delay_ms: u32,
    },

    // --- Phase 5: Fixture Responses ---
    /// Fixture configuration.
    FixtureConfig {
        /// Whether enabled.
        enabled: bool,
        /// Max fixture age seconds.
        max_fixture_age_seconds: f64,
        /// Teardown on conftest change.
        teardown_on_conftest_change: bool,
        /// Teardown on test file change.
        teardown_on_test_file_change: bool,
        /// Scopes to reuse.
        scopes_to_reuse: Vec<String>,
    },

    /// Session status.
    SessionStatus {
        /// Session ID.
        session_id: String,
        /// Repo path.
        repo_path: String,
        /// Creation timestamp.
        created_at: f64,
        /// Last run timestamp.
        last_run_at: f64,
        /// Total runs.
        total_runs: u32,
        /// Whether enabled.
        enabled: bool,
    },

    // --- Phase 5: Sharding Responses ---
    /// Tests assigned to a shard.
    ShardedTests {
        /// Shard index.
        shard_index: u32,
        /// Total shards.
        total_shards: u32,
        /// Node IDs in this shard.
        node_ids: Vec<String>,
    },

    /// Sharding distribution info.
    ShardInfo {
        /// Strategy used.
        strategy: String,
        /// Total shards.
        total_shards: u32,
        /// Total tests.
        total_tests: usize,
        /// Test counts per shard.
        shard_test_counts: Vec<usize>,
        /// Duration estimates per shard.
        shard_durations_ms: Vec<u64>,
        /// Count imbalance percentage.
        count_imbalance_percent: f64,
        /// Duration imbalance percentage.
        duration_imbalance_percent: f64,
        /// Estimated wall time.
        estimated_wall_time_ms: u64,
    },

    /// Generic config acknowledgment.
    ConfigAck {
        /// Config type.
        config_type: String,
        /// The configuration.
        config: serde_json::Value,
    },
}

/// Individual test result info for streaming.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TestResultInfo {
    /// Test node ID.
    pub node_id: String,
    /// Test outcome.
    pub outcome: String,
    /// Duration in milliseconds.
    pub duration_ms: u64,
    /// Optional failure message.
    pub message: Option<String>,
}

/// Flakiness info for a test.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FlakinessInfo {
    /// Test node ID.
    pub node_id: String,
    /// Failure rate (0.0-1.0).
    pub failure_rate: f64,
    /// Number of outcome flips.
    pub flaky_streak: u32,
    /// Total runs.
    pub total_runs: u32,
    /// Consecutive failures.
    pub consecutive_failures: u32,
    /// Consecutive passes.
    pub consecutive_passes: u32,
}

/// Error codes for categorizing failures.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
    /// Context not found or not initialized.
    ContextNotFound,
    /// Collection failed (syntax error, import error, etc.).
    CollectionFailed,
    /// Invalid request parameters.
    InvalidRequest,
    /// Internal daemon error.
    InternalError,
    /// Operation timed out.
    Timeout,
    /// Python interpreter not found or invalid.
    PythonNotFound,
    /// Protocol version mismatch between CLI and daemon.
    VersionMismatch,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request_roundtrip() {
        let requests = vec![
            Request::InitContext {
                protocol_version: PROTOCOL_VERSION,
                repo_path: "/path/to/repo".to_string(),
                python_path: Some("/usr/bin/python3".to_string()),
                execution_mode: Some("auto".to_string()),
            },
            Request::Collect {
                context_id: "ctx-123".to_string(),
                force: true,
            },
            Request::Run {
                context_id: "ctx-123".to_string(),
                node_ids: vec!["test_foo.py::test_bar".to_string()],
                workers: Some(4),
                maxfail: Some(1),
            },
            Request::List {
                context_id: "ctx-123".to_string(),
                keyword: Some("auth".to_string()),
                marker: None,
            },
            Request::GetInventory {
                context_id: "ctx-123".to_string(),
            },
            Request::Shutdown {
                context_id: Some("ctx-123".to_string()),
            },
            Request::Ping,
            Request::RunStream {
                context_id: "ctx-123".to_string(),
                node_ids: vec!["test_foo.py::test_bar".to_string()],
                workers: Some(4),
                maxfail: None,
            },
            Request::GetRunProgress {
                context_id: "ctx-123".to_string(),
                run_id: "run-123".to_string(),
            },
        ];

        for req in requests {
            let encoded = rmp_serde::to_vec(&req).unwrap();
            let decoded: Request = rmp_serde::from_slice(&encoded).unwrap();
            assert_eq!(req, decoded);
        }
    }

    #[test]
    fn response_roundtrip() {
        let responses = vec![
            Response::ContextReady {
                protocol_version: PROTOCOL_VERSION,
                context_id: "ctx-123".to_string(),
                inventory_hash: "abc123".to_string(),
            },
            Response::CollectionComplete {
                node_count: 42,
                duration_ms: 150,
            },
            Response::TestList {
                node_ids: vec!["test_a".to_string(), "test_b".to_string()],
            },
            Response::InventoryData {
                hash: "abc123".to_string(),
                collected_at: 1234567890,
                nodes: vec![TestNodeInfo {
                    node_id: "test.py::test_func".to_string(),
                    file_path: "test.py".to_string(),
                    lineno: Some(10),
                    name: "test_func".to_string(),
                    class_name: None,
                    markers: vec!["slow".to_string()],
                    skip: false,
                    xfail: false,
                }],
            },
            Response::RunComplete {
                total: 10,
                passed: 8,
                failed: 1,
                skipped: 1,
                errors: 0,
                duration_ms: 5000,
            },
            Response::ShutdownAck,
            Response::Pong,
            Response::RunStarted {
                run_id: "run-123".to_string(),
                total_tests: 10,
            },
            Response::RunProgress {
                run_id: "run-123".to_string(),
                total: 10,
                completed: 5,
                running: 2,
                done: false,
                results: vec![TestResultInfo {
                    node_id: "test.py::test_foo".to_string(),
                    outcome: "passed".to_string(),
                    duration_ms: 100,
                    message: None,
                }],
            },
            Response::Error {
                code: ErrorCode::ContextNotFound,
                message: "Context not found".to_string(),
            },
        ];

        for resp in responses {
            let encoded = rmp_serde::to_vec(&resp).unwrap();
            let decoded: Response = rmp_serde::from_slice(&encoded).unwrap();
            assert_eq!(resp, decoded);
        }
    }
}