reinhardt-testkit 0.2.0-rc.1

Core testing infrastructure for Reinhardt framework (no functional crate dependencies)
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
624
625
626
627
628
629
630
631
632
633
634
//! # DCL (Data Control Language) Test Fixtures
//!
//! This module provides rstest fixtures for DCL integration testing.
//!
//! ## Available Fixtures
//!
//! - `dcl_test_table` - Creates a test table name for privilege testing
//! - `test_role` - Creates a test role name
//! - `test_role_with_attrs` - Creates a role name with specific attributes
//! - `test_user` - Creates a test user name
//! - `test_user_with_password` - Creates a user name with password
//! - `dcl_tracker` - Per-instance object tracker for cleanup
//! - `test_database` - Creates a test database name
//! - `test_schema` - Creates a test schema name (PostgreSQL only)
//!
//! ## Usage
//!
//! ```rust,no_run
//! use reinhardt_testkit::fixtures::dcl::*;
//! use rstest::rstest;
//!
//! #[rstest]
//! #[tokio::test]
//! async fn test_grant_select(
//!     dcl_test_table: String,
//!     test_role: String,
//!     mut dcl_tracker: DclTracker,
//! ) {
//!     dcl_tracker.track(format!("TABLE:{}", dcl_test_table));
//!     dcl_tracker.track(format!("ROLE:{}", test_role));
//!     // After test, dcl_tracker.cleanup_list() returns tracked objects
//! }
//! ```
//!
//! ## Migration from Global State
//!
//! The previous implementation used a global `Mutex<Vec<String>>` for tracking
//! DCL objects, which caused race conditions in parallel test execution.
//! The new design uses per-instance `DclTracker` for thread-safe tracking
//! and UUID-based naming to prevent name collisions. (Fixes #870)

use reinhardt_query::prelude::{
	Alias, ColumnDef, CreateTableStatement, ForeignKey, ForeignKeyAction, Query,
};
use uuid::Uuid;

/// Per-instance tracker for DCL objects created during a test
///
/// Replaces the previous global `Mutex<Vec<String>>` approach to eliminate
/// race conditions between parallel tests. Each test gets its own tracker
/// instance through the `dcl_tracker` rstest fixture.
///
/// ## Object Format
///
/// Each tracked entry is formatted as `<TYPE>:<name>` where TYPE is one of:
/// - TABLE
/// - ROLE
/// - USER
/// - DATABASE
/// - SCHEMA
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::DclTracker;
///
/// let mut tracker = DclTracker::new();
/// tracker.track("ROLE:test_role_abc123".to_string());
/// tracker.track("TABLE:dcl_test_def456".to_string());
///
/// let objects = tracker.cleanup_list();
/// assert_eq!(objects.len(), 2);
/// ```
pub struct DclTracker {
	objects: Vec<String>,
}

impl DclTracker {
	/// Create a new empty tracker
	pub fn new() -> Self {
		Self {
			objects: Vec::new(),
		}
	}

	/// Track a DCL object for later cleanup
	pub fn track(&mut self, object_name: String) {
		self.objects.push(object_name);
	}

	/// Return all tracked objects and clear the internal list
	pub fn cleanup_list(&mut self) -> Vec<String> {
		std::mem::take(&mut self.objects)
	}
}

impl Default for DclTracker {
	fn default() -> Self {
		Self::new()
	}
}

/// rstest fixture providing a per-instance DCL object tracker
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::{dcl_tracker, DclTracker};
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_with_tracker(mut dcl_tracker: DclTracker) {
///     dcl_tracker.track("ROLE:my_role".to_string());
///     let cleanup = dcl_tracker.cleanup_list();
///     assert_eq!(cleanup.len(), 1);
/// }
/// ```
#[rstest::fixture]
pub fn dcl_tracker() -> DclTracker {
	DclTracker::new()
}

/// Generate a short unique suffix from UUID for naming.
/// Uses the last 12 characters (random portion) of UUID v7 to ensure
/// uniqueness even when called within the same millisecond.
fn unique_suffix() -> String {
	let s = Uuid::now_v7().simple().to_string();
	s[s.len() - 12..].to_string()
}

/// Create a test table for DCL privilege testing
///
/// Returns a unique table name using UUID-based suffix.
///
/// # Table Schema
///
/// ```text
/// dcl_test_<uuid> (
///     id BIGINT PRIMARY KEY,
///     name VARCHAR(100) NOT NULL,
///     value TEXT,
///     created_at TIMESTAMP
/// )
/// ```
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::dcl_test_table;
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_table_operations(dcl_test_table: String) {
///     assert!(dcl_test_table.starts_with("dcl_test_"));
/// }
/// ```
pub fn dcl_test_table() -> String {
	format!("dcl_test_{}", unique_suffix())
}

/// Create a test role name
///
/// Returns a unique role name using UUID-based suffix.
///
/// # Naming Convention
///
/// Format: `test_role_<uuid>`
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::test_role;
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_role_creation(test_role: String) {
///     assert!(test_role.starts_with("test_role_"));
/// }
/// ```
pub fn test_role() -> String {
	format!("test_role_{}", unique_suffix())
}

/// Create a test role with specific attributes
///
/// Returns a tuple of (role_name, attributes) where attributes is a comma-separated
/// string of role attributes (e.g., "LOGIN,CREATEDB").
///
/// # Supported Attributes
///
/// - PostgreSQL: LOGIN, NOLOGIN, CREATEDB, NOCREATEDB, CREATEROLE, NOCREATEROLE,
///   SUPERUSER, NOSUPERUSER, INHERIT, NOINHERIT, REPLICATION, NOREPLICATION
/// - MySQL: (none - MySQL doesn't support role attributes)
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::test_role_with_attrs;
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_role_with_attributes(test_role_with_attrs: (String, String)) {
///     let (role_name, attrs) = test_role_with_attrs;
///     assert!(role_name.starts_with("test_role_attrs_"));
///     assert!(attrs.contains("LOGIN"));
/// }
/// ```
pub fn test_role_with_attrs() -> (String, String) {
	let role_name = format!("test_role_attrs_{}", unique_suffix());
	let attributes = "LOGIN,CREATEDB".to_string();
	(role_name, attributes)
}

/// Create a test user name
///
/// Returns a unique user name using UUID-based suffix.
///
/// # Naming Convention
///
/// Format: `test_user_<uuid>`
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::test_user;
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_user_creation(test_user: String) {
///     assert!(test_user.starts_with("test_user_"));
/// }
/// ```
pub fn test_user() -> String {
	format!("test_user_{}", unique_suffix())
}

/// Create a test user with password
///
/// Returns a tuple of (username, password).
///
/// # Password
///
/// The password is auto-generated and unique for each test.
///
/// # Security Note
///
/// **WARNING**: These passwords are for testing only. Never use in production.
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::test_user_with_password;
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_user_auth(test_user_with_password: (String, String)) {
///     let (username, password) = test_user_with_password;
///     assert!(username.starts_with("test_user_pass_"));
///     assert!(!password.is_empty());
/// }
/// ```
pub fn test_user_with_password() -> (String, String) {
	let suffix = unique_suffix();
	let user_name = format!("test_user_pass_{}", suffix);
	let password = format!("test_password_{}", suffix);
	(user_name, password)
}

/// Create a test database name
///
/// Returns a unique database name using UUID-based suffix.
///
/// # Naming Convention
///
/// Format: `test_db_<uuid>`
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::test_database;
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_database_creation(test_database: String) {
///     assert!(test_database.starts_with("test_db_"));
/// }
/// ```
pub fn test_database() -> String {
	format!("test_db_{}", unique_suffix())
}

/// Create a test schema name (PostgreSQL only)
///
/// Returns a unique schema name using UUID-based suffix.
///
/// # Naming Convention
///
/// Format: `test_schema_<uuid>`
///
/// # Database Support
///
/// - PostgreSQL: Supported
/// - MySQL: Not supported (use CREATE DATABASE instead)
/// - SQLite: Not supported
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::test_schema;
/// use rstest::rstest;
///
/// #[rstest]
/// fn test_schema_creation(test_schema: String) {
///     assert!(test_schema.starts_with("test_schema_"));
/// }
/// ```
pub fn test_schema() -> String {
	format!("test_schema_{}", unique_suffix())
}

/// Generate reinhardt-query `CreateTableStatement` for DCL test table
///
/// Returns a table creation statement that can be built into SQL for any backend.
///
/// # Schema
///
/// ```text
/// dcl_test_<uuid> (
///     id BIGINT PRIMARY KEY,
///     name VARCHAR(100) NOT NULL,
///     value TEXT,
///     created_at TIMESTAMP
/// )
/// ```
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::dcl_test_table_stmt;
/// use reinhardt_query::prelude::{PostgresQueryBuilder, MySqlQueryBuilder, QueryStatementBuilder};
///
/// #[test]
/// fn test_table_sql_generation() {
///     let stmt = dcl_test_table_stmt();
///
///     let sql = stmt.to_string(PostgresQueryBuilder::new());
///     assert!(sql.contains("CREATE TABLE"));
///
///     let sql = stmt.to_string(MySqlQueryBuilder::new());
///     assert!(sql.contains("CREATE TABLE"));
/// }
/// ```
pub fn dcl_test_table_stmt() -> CreateTableStatement {
	let table_name = dcl_test_table();

	let mut stmt = Query::create_table();
	stmt.table(Alias::new(&table_name))
		.col(
			ColumnDef::new(Alias::new("id"))
				.big_integer()
				.not_null(true)
				.primary_key(true),
		)
		.col(
			ColumnDef::new(Alias::new("name"))
				.string_len(100)
				.not_null(true),
		)
		.col(ColumnDef::new(Alias::new("value")).text())
		.col(ColumnDef::new(Alias::new("created_at")).timestamp());
	stmt.take()
}

/// Generate reinhardt-query `CreateTableStatement` for DCL test table with foreign key
///
/// Returns a table creation statement with a foreign key constraint for testing
/// privilege management on related tables.
///
/// # Schema
///
/// ```text
/// dcl_test_parent_<uuid> (
///     id BIGINT PRIMARY KEY,
///     name VARCHAR(100) NOT NULL
/// )
///
/// dcl_test_child_<uuid> (
///     id BIGINT PRIMARY KEY,
///     parent_id BIGINT NOT NULL,
///     value TEXT,
///     FOREIGN KEY (parent_id) REFERENCES dcl_test_parent(id) ON DELETE CASCADE
/// )
/// ```
///
/// # Returns
///
/// A tuple of (parent_table_stmt, child_table_stmt, parent_name, child_name)
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::dcl::dcl_test_table_with_fk;
/// use reinhardt_query::prelude::{PostgresQueryBuilder, QueryStatementBuilder};
///
/// #[test]
/// fn test_foreign_key_table() {
///     let (parent_stmt, child_stmt, parent_name, child_name) = dcl_test_table_with_fk();
///
///     let sql = child_stmt.to_string(PostgresQueryBuilder::new());
///     assert!(sql.contains("FOREIGN KEY"));
/// }
/// ```
pub fn dcl_test_table_with_fk() -> (CreateTableStatement, CreateTableStatement, String, String) {
	// Use same suffix for parent and child to make the relationship clear
	let suffix = unique_suffix();
	let parent_name = format!("dcl_test_parent_{}", suffix);
	let child_name = format!("dcl_test_child_{}", suffix);

	let mut parent_stmt = Query::create_table();
	parent_stmt
		.table(Alias::new(&parent_name))
		.col(
			ColumnDef::new(Alias::new("id"))
				.big_integer()
				.not_null(true)
				.primary_key(true),
		)
		.col(
			ColumnDef::new(Alias::new("name"))
				.string_len(100)
				.not_null(true),
		);

	let mut fk = ForeignKey::create();
	fk.name(Alias::new(format!("fk_{}_parent", child_name)))
		.from_tbl(Alias::new(&child_name))
		.from_col(Alias::new("parent_id"))
		.to_tbl(Alias::new(&parent_name))
		.to_col(Alias::new("id"))
		.on_delete(ForeignKeyAction::Cascade)
		.on_update(ForeignKeyAction::Cascade);

	let mut child_stmt = Query::create_table();
	child_stmt
		.table(Alias::new(&child_name))
		.col(
			ColumnDef::new(Alias::new("id"))
				.big_integer()
				.not_null(true)
				.primary_key(true),
		)
		.col(
			ColumnDef::new(Alias::new("parent_id"))
				.big_integer()
				.not_null(true),
		)
		.col(ColumnDef::new(Alias::new("value")).text())
		.foreign_key_from_builder(&mut fk);

	(
		parent_stmt.take(),
		child_stmt.take(),
		parent_name,
		child_name,
	)
}

#[cfg(test)]
mod tests {
	use super::*;
	use reinhardt_query::prelude::{
		MySqlQueryBuilder, PostgresQueryBuilder, QueryStatementBuilder,
	};
	use rstest::rstest;

	#[rstest]
	fn test_dcl_test_table_format() {
		// Arrange & Act
		let table = dcl_test_table();

		// Assert
		assert!(table.starts_with("dcl_test_"));
	}

	#[rstest]
	fn test_dcl_test_table_uniqueness() {
		// Arrange & Act
		let table1 = dcl_test_table();
		let table2 = dcl_test_table();

		// Assert
		assert_ne!(table1, table2, "Each call must generate a unique name");
	}

	#[rstest]
	fn test_test_role_format() {
		// Arrange & Act
		let role = test_role();

		// Assert
		assert!(role.starts_with("test_role_"));
	}

	#[rstest]
	fn test_test_role_with_attrs_format() {
		// Arrange & Act
		let (role, attrs) = test_role_with_attrs();

		// Assert
		assert!(role.starts_with("test_role_attrs_"));
		assert_eq!(attrs, "LOGIN,CREATEDB");
	}

	#[rstest]
	fn test_test_user_format() {
		// Arrange & Act
		let user = test_user();

		// Assert
		assert!(user.starts_with("test_user_"));
	}

	#[rstest]
	fn test_test_user_with_password_format() {
		// Arrange & Act
		let (user, pass) = test_user_with_password();

		// Assert
		assert!(user.starts_with("test_user_pass_"));
		assert!(pass.starts_with("test_password_"));
	}

	#[rstest]
	fn test_test_database_format() {
		// Arrange & Act
		let db = test_database();

		// Assert
		assert!(db.starts_with("test_db_"));
	}

	#[rstest]
	fn test_test_schema_format() {
		// Arrange & Act
		let schema = test_schema();

		// Assert
		assert!(schema.starts_with("test_schema_"));
	}

	#[rstest]
	fn test_dcl_tracker_tracks_objects() {
		// Arrange
		let mut tracker = DclTracker::new();
		let role = test_role();
		let user = test_user();
		let table = dcl_test_table();

		// Act
		tracker.track(format!("ROLE:{}", role));
		tracker.track(format!("USER:{}", user));
		tracker.track(format!("TABLE:{}", table));

		let cleanup = tracker.cleanup_list();

		// Assert
		assert_eq!(cleanup.len(), 3);
		assert!(cleanup.iter().any(|o| o.starts_with("ROLE:")));
		assert!(cleanup.iter().any(|o| o.starts_with("USER:")));
		assert!(cleanup.iter().any(|o| o.starts_with("TABLE:")));
	}

	#[rstest]
	fn test_dcl_tracker_clears_after_cleanup() {
		// Arrange
		let mut tracker = DclTracker::new();
		tracker.track(format!("ROLE:{}", test_role()));
		tracker.track(format!("USER:{}", test_user()));

		// Act
		let cleanup1 = tracker.cleanup_list();
		let cleanup2 = tracker.cleanup_list();

		// Assert
		assert_eq!(cleanup1.len(), 2);
		assert_eq!(cleanup2.len(), 0);
	}

	#[rstest]
	fn test_dcl_test_table_stmt_generates_valid_sql() {
		// Arrange & Act
		let stmt = dcl_test_table_stmt();

		// Assert
		assert!(
			stmt.to_string(PostgresQueryBuilder::new())
				.contains("CREATE TABLE")
		);
		assert!(
			stmt.to_string(MySqlQueryBuilder::new())
				.contains("CREATE TABLE")
		);
	}

	#[rstest]
	fn test_dcl_test_table_with_fk_format() {
		// Arrange & Act
		let (parent_stmt, child_stmt, parent_name, child_name) = dcl_test_table_with_fk();

		// Assert
		assert!(parent_name.starts_with("dcl_test_parent_"));
		assert!(child_name.starts_with("dcl_test_child_"));

		let parent_sql = parent_stmt.to_string(PostgresQueryBuilder::new());
		assert!(parent_sql.contains("CREATE TABLE"));
		assert!(parent_sql.contains(&parent_name));

		let child_sql = child_stmt.to_string(PostgresQueryBuilder::new());
		assert!(child_sql.contains("CREATE TABLE"));
		assert!(child_sql.contains(&child_name));
		assert!(child_sql.contains("FOREIGN KEY"));
	}

	#[rstest]
	fn test_dcl_test_table_with_fk_uses_same_suffix() {
		// Arrange & Act
		let (_parent_stmt, _child_stmt, parent_name, child_name) = dcl_test_table_with_fk();

		// Assert - parent and child share the same suffix
		let parent_suffix = parent_name.strip_prefix("dcl_test_parent_").unwrap();
		let child_suffix = child_name.strip_prefix("dcl_test_child_").unwrap();
		assert_eq!(parent_suffix, child_suffix);
	}
}