data_generator 0.1.119

RDF data shapes implementation in Rust
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
use data_generator::config::OutputFormat;
use data_generator::{DataGenerator, GeneratorConfig};
use srdf::{Literal, NeighsRDF, RDFFormat, ReaderMode, SRDFGraph};
use std::collections::HashMap;
use std::io::Write;
use tempfile::NamedTempFile;

/// Test that ShEx datatype constraints are passed down to generated data
#[tokio::test]
async fn test_shex_datatype_passthrough() {
    // Create a ShEx schema with specific datatypes
    let shex_schema = r#"
PREFIX ex: <http://example.org/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

ex:PersonShape {
  ex:name xsd:string ;
  ex:age xsd:integer ;
  ex:active xsd:boolean
}
"#;

    // Create temporary files
    let mut schema_file = NamedTempFile::new().unwrap();
    writeln!(schema_file, "{shex_schema}").unwrap();

    let output_file = NamedTempFile::new().unwrap();

    // Configure generator
    let mut config = GeneratorConfig::default();
    config.generation.entity_count = 5;
    config.output.path = output_file.path().to_path_buf();

    // Generate data
    let mut generator = DataGenerator::new(config).unwrap();
    generator
        .load_shex_schema(schema_file.path())
        .await
        .unwrap();
    generator.generate().await.unwrap();

    // Parse generated data
    let graph = SRDFGraph::from_path(
        output_file.path(),
        &RDFFormat::Turtle,
        None,
        &ReaderMode::Strict,
    )
    .expect("Failed to parse generated RDF");

    // Verify that generated triples respect datatypes
    let mut datatype_counts = HashMap::new();

    for triple in graph.triples().unwrap() {
        if let oxrdf::Term::Literal(lit) = &triple.object {
            let datatype = lit.datatype().to_string();
            // Remove angle brackets if present
            let clean_datatype = datatype.trim_start_matches('<').trim_end_matches('>');
            *datatype_counts
                .entry(clean_datatype.to_string())
                .or_insert(0) += 1;
        }
    }

    // Should have string, integer, and boolean literals
    assert!(datatype_counts.contains_key("http://www.w3.org/2001/XMLSchema#string"));
    assert!(datatype_counts.contains_key("http://www.w3.org/2001/XMLSchema#integer"));
    assert!(datatype_counts.contains_key("http://www.w3.org/2001/XMLSchema#boolean"));
}

/// Test that SHACL datatype constraints are passed down to generated data
#[tokio::test]
async fn test_shacl_datatype_passthrough() {
    // Create a SHACL schema with specific datatypes
    let shacl_schema = r#"
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix ex: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

ex:PersonShape a sh:NodeShape ;
    sh:targetClass ex:Person ;
    sh:property [
        sh:path ex:name ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:age ;
        sh:datatype xsd:integer ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:score ;
        sh:datatype xsd:decimal ;
        sh:minCount 0 ;
        sh:maxCount 1 ;
    ] .
"#;

    // Create temporary files
    let mut schema_file = NamedTempFile::new().unwrap();
    writeln!(schema_file, "{shacl_schema}").unwrap();

    let output_file = NamedTempFile::new().unwrap();

    // Configure generator
    let mut config = GeneratorConfig::default();
    config.generation.entity_count = 5;
    config.output.path = output_file.path().to_path_buf();

    // Generate data
    let mut generator = DataGenerator::new(config).unwrap();
    generator
        .load_shacl_schema(schema_file.path())
        .await
        .unwrap();
    generator.generate().await.unwrap();

    // Parse generated data
    let graph = SRDFGraph::from_path(
        output_file.path(),
        &RDFFormat::Turtle,
        None,
        &ReaderMode::Strict,
    )
    .expect("Failed to parse generated RDF");

    // Verify that generated triples respect datatypes
    let mut datatype_counts = HashMap::new();

    for triple in graph.triples().unwrap() {
        if let oxrdf::Term::Literal(lit) = &triple.object {
            let datatype = lit.datatype().to_string();
            // Strip angle brackets from datatype URI if present
            let clean_datatype = if datatype.starts_with('<') && datatype.ends_with('>') {
                datatype[1..datatype.len() - 1].to_string()
            } else {
                datatype
            };
            *datatype_counts.entry(clean_datatype).or_insert(0) += 1;
        }
    }

    // Should have string, integer, and decimal literals
    assert!(datatype_counts.contains_key("http://www.w3.org/2001/XMLSchema#string"));
    assert!(datatype_counts.contains_key("http://www.w3.org/2001/XMLSchema#integer"));
    assert!(datatype_counts.contains_key("http://www.w3.org/2001/XMLSchema#decimal"));
}

/// Test that ShEx cardinality constraints are passed down to generated data
#[tokio::test]
async fn test_shex_cardinality_passthrough() {
    // Create a ShEx schema with cardinality constraints
    let shex_schema = r#"
PREFIX ex: <http://example.org/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

ex:PersonShape {
  ex:name xsd:string {1,1} ;      # exactly one name
  ex:email xsd:string {0,2} ;     # zero to two emails  
  ex:phone xsd:string *           # zero or more phones
}
"#;

    // Create temporary files
    let mut schema_file = NamedTempFile::new().unwrap();
    writeln!(schema_file, "{shex_schema}").unwrap();

    let output_file = NamedTempFile::new().unwrap();

    // Configure generator
    let mut config = GeneratorConfig::default();
    config.generation.entity_count = 10; // More entities for better cardinality testing
    config.output.path = output_file.path().to_path_buf();

    // Generate data
    let mut generator = DataGenerator::new(config).unwrap();
    generator
        .load_shex_schema(schema_file.path())
        .await
        .unwrap();
    generator.generate().await.unwrap();

    // Parse generated data
    let graph = SRDFGraph::from_path(
        output_file.path(),
        &RDFFormat::Turtle,
        None,
        &ReaderMode::Strict,
    )
    .expect("Failed to parse generated RDF");

    // Count properties per entity to verify cardinality
    let mut entity_properties: HashMap<String, HashMap<String, u32>> = HashMap::new();

    for triple in graph.triples().unwrap() {
        let subject = triple.subject.to_string();
        let predicate = triple.predicate.to_string();

        entity_properties
            .entry(subject)
            .or_default()
            .entry(predicate)
            .and_modify(|count| *count += 1)
            .or_insert(1);
    }

    // Verify cardinality constraints for each entity
    for properties in entity_properties.values() {
        // Each entity should have exactly 1 name
        if let Some(&name_count) = properties.get("http://example.org/name") {
            assert_eq!(name_count, 1, "Entity should have exactly 1 name");
        }

        // Each entity should have 0-2 emails
        if let Some(&email_count) = properties.get("http://example.org/email") {
            assert!(email_count <= 2, "Entity should have at most 2 emails");
        }

        // Phone count can be any number (0 or more)
        // No assertion needed for * cardinality
    }
}

/// Test that SHACL cardinality constraints are passed down to generated data
#[tokio::test]
async fn test_shacl_cardinality_passthrough() {
    // Create a SHACL schema with cardinality constraints
    let shacl_schema = r#"
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix ex: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

ex:PersonShape a sh:NodeShape ;
    sh:targetClass ex:Person ;
    sh:property [
        sh:path ex:name ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:email ;
        sh:datatype xsd:string ;
        sh:minCount 0 ;
        sh:maxCount 3 ;
    ] ;
    sh:property [
        sh:path ex:hobby ;
        sh:datatype xsd:string ;
        sh:minCount 2 ;
        sh:maxCount 5 ;
    ] .
"#;

    // Create temporary files
    let mut schema_file = NamedTempFile::new().unwrap();
    writeln!(schema_file, "{shacl_schema}").unwrap();

    let output_file = NamedTempFile::new().unwrap();

    // Configure generator
    let mut config = GeneratorConfig::default();
    config.generation.entity_count = 8;
    config.output.path = output_file.path().to_path_buf();

    // Generate data
    let mut generator = DataGenerator::new(config).unwrap();
    generator
        .load_shacl_schema(schema_file.path())
        .await
        .unwrap();
    generator.generate().await.unwrap();

    // Parse generated data
    let graph = SRDFGraph::from_path(
        output_file.path(),
        &RDFFormat::Turtle,
        None,
        &ReaderMode::Strict,
    )
    .expect("Failed to parse generated RDF");

    // Count properties per entity to verify cardinality
    let mut entity_properties: HashMap<String, HashMap<String, u32>> = HashMap::new();

    for triple in graph.triples().unwrap() {
        let subject = triple.subject.to_string();
        let predicate = triple.predicate.to_string();

        entity_properties
            .entry(subject)
            .or_default()
            .entry(predicate)
            .and_modify(|count| *count += 1)
            .or_insert(1);
    }

    // Verify cardinality constraints for each entity
    for properties in entity_properties.values() {
        // Each entity should have exactly 1 name
        if let Some(&name_count) = properties.get("http://example.org/name") {
            assert_eq!(name_count, 1, "Entity should have exactly 1 name");
        }

        // Each entity should have 0-3 emails
        if let Some(&email_count) = properties.get("http://example.org/email") {
            assert!(email_count <= 3, "Entity should have at most 3 emails");
        }

        // Each entity should have 2-5 hobbies
        if let Some(&hobby_count) = properties.get("http://example.org/hobby") {
            assert!(
                (2..=5).contains(&hobby_count),
                "Entity should have 2-5 hobbies"
            );
        }
    }
}

/// Test that ShEx shape references are passed down correctly
#[tokio::test]
async fn test_shex_shape_reference_passthrough() {
    // Create a ShEx schema with shape references
    let shex_schema = r#"
PREFIX ex: <http://example.org/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

ex:PersonShape {
  ex:name xsd:string ;
  ex:address @ex:AddressShape
}

ex:AddressShape {
  ex:street xsd:string ;
  ex:city xsd:string ;
  ex:country xsd:string
}
"#;

    // Create temporary files
    let mut schema_file = NamedTempFile::new().unwrap();
    writeln!(schema_file, "{shex_schema}").unwrap();

    let output_file = NamedTempFile::new().unwrap();

    // Configure generator
    let mut config = GeneratorConfig::default();
    config.generation.entity_count = 3;
    config.output.format = OutputFormat::Turtle;
    config.output.path = output_file.path().to_path_buf();

    // Generate data
    let mut generator = DataGenerator::new(config).unwrap();
    generator
        .load_shex_schema(schema_file.path())
        .await
        .unwrap();
    generator.generate().await.unwrap();

    // Read and validate generated data
    let generated_data = std::fs::read_to_string(output_file.path()).unwrap();
    let graph = SRDFGraph::from_str(
        &generated_data,
        &RDFFormat::Turtle,
        None,
        &ReaderMode::Strict,
    )
    .unwrap();

    // Check that we have both person and address data
    let triples = graph.triples().unwrap();
    let mut has_person_name = false;
    let mut has_address_street = false;
    let mut has_address_city = false;

    for triple in triples {
        let predicate = triple.predicate.to_string();
        match predicate.as_str() {
            "<http://example.org/name>" => has_person_name = true,
            "<http://example.org/street>" => has_address_street = true,
            "<http://example.org/city>" => has_address_city = true,
            _ => {}
        }
    }

    assert!(has_person_name, "Should have person names");
    assert!(has_address_street, "Should have address streets");
    assert!(has_address_city, "Should have address cities");
}

/// Test that SHACL node shape references are passed down correctly
#[tokio::test]
async fn test_shacl_shape_reference_passthrough() {
    // Create a SHACL schema with shape references
    let shacl_schema = r#"
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix ex: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

ex:PersonShape a sh:NodeShape ;
    sh:targetClass ex:Person ;
    sh:property [
        sh:path ex:name ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:address ;
        sh:node ex:AddressShape ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] .

ex:AddressShape a sh:NodeShape ;
    sh:property [
        sh:path ex:street ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:city ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] .
"#;

    // Create temporary files
    let mut schema_file = NamedTempFile::new().unwrap();
    writeln!(schema_file, "{shacl_schema}").unwrap();

    let output_file = NamedTempFile::new().unwrap();

    // Configure generator
    let mut config = GeneratorConfig::default();
    config.generation.entity_count = 3;
    config.output.format = OutputFormat::Turtle;
    config.output.path = output_file.path().to_path_buf();

    // Generate data
    let mut generator = DataGenerator::new(config).unwrap();
    generator
        .load_shacl_schema(schema_file.path())
        .await
        .unwrap();
    generator.generate().await.unwrap();

    // Read and validate generated data
    let generated_data = std::fs::read_to_string(output_file.path()).unwrap();
    let graph = SRDFGraph::from_str(
        &generated_data,
        &RDFFormat::Turtle,
        None,
        &ReaderMode::Strict,
    )
    .unwrap();

    // Check that we have both person and address data
    let triples = graph.triples().unwrap();
    let mut has_person_name = false;
    let mut has_address_street = false;
    let mut has_address_city = false;

    for triple in triples {
        let predicate = triple.predicate.to_string();
        match predicate.as_str() {
            "<http://example.org/name>" => has_person_name = true,
            "<http://example.org/street>" => has_address_street = true,
            "<http://example.org/city>" => has_address_city = true,
            _ => {}
        }
    }

    assert!(has_person_name, "Should have person names");
    assert!(has_address_street, "Should have address streets");
    assert!(has_address_city, "Should have address cities");
}

/// Test that SHACL value constraints are passed down correctly
#[tokio::test]
async fn test_shacl_value_constraints_passthrough() {
    // Create a SHACL schema with basic supported constraints
    let shacl_schema = r#"
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix ex: <http://example.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

ex:PersonShape a sh:NodeShape ;
    sh:targetClass ex:Person ;
    sh:property [
        sh:path ex:name ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:age ;
        sh:datatype xsd:integer ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] ;
    sh:property [
        sh:path ex:status ;
        sh:datatype xsd:string ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] .
"#;

    // Create temporary files
    let mut schema_file = NamedTempFile::new().unwrap();
    writeln!(schema_file, "{shacl_schema}").unwrap();

    let output_file = NamedTempFile::new().unwrap();

    // Configure generator
    let mut config = GeneratorConfig::default();
    config.generation.entity_count = 5;
    config.output.format = OutputFormat::Turtle;
    config.output.path = output_file.path().to_path_buf();

    // Generate data
    let mut generator = DataGenerator::new(config).unwrap();
    generator
        .load_shacl_schema(schema_file.path())
        .await
        .unwrap();
    generator.generate().await.unwrap();

    // Read and validate generated data
    let generated_data = std::fs::read_to_string(output_file.path()).unwrap();
    let graph = SRDFGraph::from_str(
        &generated_data,
        &RDFFormat::Turtle,
        None,
        &ReaderMode::Strict,
    )
    .unwrap();

    // Verify that generated values respect constraints
    let triples = graph.triples().unwrap();

    for triple in triples {
        let predicate = triple.predicate.to_string();
        let object = triple.object;

        match predicate.as_str() {
            "http://example.org/name" => {
                if let oxrdf::Term::Literal(literal) = object {
                    let value = literal.lexical_form();
                    assert!(
                        value.len() >= 2 && value.len() <= 50,
                        "Name length should be between 2 and 50 characters, got: {value}"
                    );
                }
            }
            "http://example.org/age" => {
                if let oxrdf::Term::Literal(literal) = object {
                    let value: i32 = literal.lexical_form().parse().unwrap();
                    assert!(
                        (0..=150).contains(&value),
                        "Age should be between 0 and 150, got: {value}"
                    );
                }
            }
            "http://example.org/status" => {
                if let oxrdf::Term::Literal(literal) = object {
                    let value = literal.lexical_form();
                    assert!(
                        ["active", "inactive", "pending"].contains(&value),
                        "Status should be one of active/inactive/pending, got: {value}"
                    );
                }
            }
            _ => {}
        }
    }
}