real_data_tests 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/Gemfile +10 -0
- data/LICENSE.txt +21 -0
- data/README.md +327 -0
- data/Rakefile +8 -0
- data/lib/real_data_tests/configuration.rb +116 -0
- data/lib/real_data_tests/data_anonymizer.rb +58 -0
- data/lib/real_data_tests/engine.rb +17 -0
- data/lib/real_data_tests/pg_dump_generator.rb +304 -0
- data/lib/real_data_tests/record_collector.rb +117 -0
- data/lib/real_data_tests/rspec_helper.rb +41 -0
- data/lib/real_data_tests/test_data_builder.rb +34 -0
- data/lib/real_data_tests/version.rb +5 -0
- data/lib/real_data_tests.rb +49 -0
- data/sig/real_data_tests.rbs +4 -0
- metadata +176 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 40264604e537da8c1f365cd1afce57fef95988d3e51d36e1c7c68c425f0e3e8b
|
4
|
+
data.tar.gz: 57d486a6a25bc26522051aa2ad2a105698e28911679b1bccf6c25e1c4dd11880
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: d7784e89db22fd3c522a9c4b60a8cca7c4c8e15bdbc86f3d20b9aa8cce4a58dbe1f1724c0355defbec3ab00f2d26e831a4351e2b5dc6fd15c97a724ed5079c95
|
7
|
+
data.tar.gz: 60ea36eb4824cb15554026431e0fd06d52ca1194417d025be3db9b9f93e093ccce8b50db48baecf4f5388e8458c76028ae687b6513f00bb1cb3c1acfb2b1637b
|
data/.rspec
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at diasks2@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/Gemfile
ADDED
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2025 Kevin Dias
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,327 @@
|
|
1
|
+
# Real Data Tests
|
2
|
+
|
3
|
+
Create realistic test data in your Rails applications by extracting real records and their associations from your PostgreSQL database.
|
4
|
+
|
5
|
+
> **Note**: This gem currently only supports PostgreSQL databases. MySQL and other database adapters are not supported.
|
6
|
+
|
7
|
+
## Why use Real Data Tests?
|
8
|
+
|
9
|
+
Testing with realistic data is crucial for catching edge cases and ensuring your application works with real-world data structures. However, creating complex test fixtures that accurately represent your data relationships can be time-consuming and error-prone.
|
10
|
+
|
11
|
+
Real Data Tests solves this by:
|
12
|
+
- Automatically analyzing and extracting real records and their associations
|
13
|
+
- Creating reusable SQL dumps that can be committed to your repository
|
14
|
+
- Making it easy to load realistic test data in your specs
|
15
|
+
- Supporting data anonymization for sensitive information
|
16
|
+
|
17
|
+
## Requirements
|
18
|
+
|
19
|
+
- Rails 5.0 or higher
|
20
|
+
- PostgreSQL database
|
21
|
+
- `pg_dump` command-line utility installed and accessible
|
22
|
+
- Database user needs sufficient permissions to run `pg_dump`
|
23
|
+
|
24
|
+
## Installation
|
25
|
+
|
26
|
+
Add this line to your application's Gemfile:
|
27
|
+
|
28
|
+
```ruby
|
29
|
+
gem 'real_data_tests'
|
30
|
+
```
|
31
|
+
|
32
|
+
And then execute:
|
33
|
+
```bash
|
34
|
+
$ bundle install
|
35
|
+
```
|
36
|
+
|
37
|
+
Or install it yourself as:
|
38
|
+
```bash
|
39
|
+
$ gem install real_data_tests
|
40
|
+
```
|
41
|
+
|
42
|
+
## Configuration
|
43
|
+
|
44
|
+
Create an initializer in your Rails application:
|
45
|
+
|
46
|
+
```ruby
|
47
|
+
# config/initializers/real_data_tests.rb
|
48
|
+
Rails.application.config.after_initialize do
|
49
|
+
RealDataTests.configure do |config|
|
50
|
+
# Directory where SQL dumps will be stored
|
51
|
+
config.dump_path = 'spec/fixtures/real_data_dumps'
|
52
|
+
|
53
|
+
# Global associations (apply to all models)
|
54
|
+
config.include_associations(
|
55
|
+
:user,
|
56
|
+
:organization,
|
57
|
+
:profile
|
58
|
+
)
|
59
|
+
|
60
|
+
# Model-specific associations
|
61
|
+
config.include_associations_for 'Patient', :visit_notes, :treatment_reports
|
62
|
+
config.include_associations_for 'Discipline', :organization, :user
|
63
|
+
|
64
|
+
# Control association loading behavior
|
65
|
+
config.limit_association 'Patient.visit_notes', 10
|
66
|
+
config.prevent_reciprocal 'VisitNoteType.visit_notes'
|
67
|
+
|
68
|
+
# Configure data anonymization
|
69
|
+
config.anonymize 'User', {
|
70
|
+
first_name: -> (_) { Faker::Name.first_name },
|
71
|
+
last_name: -> (_) { Faker::Name.last_name },
|
72
|
+
email: -> (user) { Faker::Internet.email(name: "user#{user.id}") }
|
73
|
+
}
|
74
|
+
end
|
75
|
+
end
|
76
|
+
```
|
77
|
+
|
78
|
+
## Usage
|
79
|
+
|
80
|
+
### 1. Preparing Test Data
|
81
|
+
|
82
|
+
You can create SQL dumps from your development or production database in two ways:
|
83
|
+
|
84
|
+
**From Rails console:**
|
85
|
+
```ruby
|
86
|
+
# Find a record you want to use as test data
|
87
|
+
user = User.find(1)
|
88
|
+
|
89
|
+
# Create a dump file including the user and all related records
|
90
|
+
RealDataTests.create_dump_file(user, name: "active_user_with_posts")
|
91
|
+
```
|
92
|
+
|
93
|
+
**Or from command line:**
|
94
|
+
```bash
|
95
|
+
$ bundle exec real_data_tests create_dump User 1 active_user_with_posts
|
96
|
+
```
|
97
|
+
|
98
|
+
This will:
|
99
|
+
1. Find the specified User record
|
100
|
+
2. Collect all associated records based on your configuration
|
101
|
+
3. Apply any configured anonymization rules
|
102
|
+
4. Generate a SQL dump file in your configured dump_path
|
103
|
+
|
104
|
+
### 2. Using in Tests
|
105
|
+
|
106
|
+
First, include the helper in your test setup:
|
107
|
+
|
108
|
+
```ruby
|
109
|
+
# spec/rails_helper.rb or spec/spec_helper.rb
|
110
|
+
require 'real_data_tests'
|
111
|
+
|
112
|
+
RSpec.configure do |config|
|
113
|
+
config.include RealDataTests::RSpecHelper
|
114
|
+
end
|
115
|
+
```
|
116
|
+
|
117
|
+
Then use it in your tests:
|
118
|
+
|
119
|
+
```ruby
|
120
|
+
RSpec.describe "Blog" do
|
121
|
+
it "displays user's posts correctly" do
|
122
|
+
# Load the previously created dump file
|
123
|
+
load_real_test_data("active_user_with_posts")
|
124
|
+
|
125
|
+
# Your test code here - the database now contains
|
126
|
+
# the user and all their associated records
|
127
|
+
visit user_posts_path(User.first)
|
128
|
+
expect(page).to have_content("My First Post")
|
129
|
+
end
|
130
|
+
end
|
131
|
+
```
|
132
|
+
|
133
|
+
## Association Control
|
134
|
+
|
135
|
+
Real Data Tests provides several ways to control how associations are collected and loaded.
|
136
|
+
|
137
|
+
### Global Association Filtering
|
138
|
+
|
139
|
+
You can control which associations are collected globally using either whitelist or blacklist mode:
|
140
|
+
|
141
|
+
```ruby
|
142
|
+
# Whitelist Mode - ONLY collect these associations
|
143
|
+
config.include_associations(
|
144
|
+
:user,
|
145
|
+
:organization,
|
146
|
+
:profile
|
147
|
+
)
|
148
|
+
|
149
|
+
# OR Blacklist Mode - collect all EXCEPT these associations
|
150
|
+
config.exclude_associations(
|
151
|
+
:very_large_association,
|
152
|
+
:unused_association
|
153
|
+
)
|
154
|
+
```
|
155
|
+
|
156
|
+
### Model-Specific Associations
|
157
|
+
|
158
|
+
For more granular control, you can specify which associations should be collected for specific models:
|
159
|
+
|
160
|
+
```ruby
|
161
|
+
RealDataTests.configure do |config|
|
162
|
+
# Global associations that apply to all models
|
163
|
+
config.include_associations(
|
164
|
+
:organization,
|
165
|
+
:user
|
166
|
+
)
|
167
|
+
|
168
|
+
# Model-specific associations
|
169
|
+
config.include_associations_for 'Patient',
|
170
|
+
:visit_notes,
|
171
|
+
:treatment_reports,
|
172
|
+
:patient_status
|
173
|
+
|
174
|
+
config.include_associations_for 'Discipline',
|
175
|
+
:organization, # Will collect this even though it's in global associations
|
176
|
+
:credentials,
|
177
|
+
:specialty_types
|
178
|
+
end
|
179
|
+
```
|
180
|
+
|
181
|
+
This is particularly useful when:
|
182
|
+
- Different models need different association rules
|
183
|
+
- The same association name means different things on different models
|
184
|
+
- You want to collect an association from one model but not another
|
185
|
+
- You need to maintain a clean separation of concerns in your test data
|
186
|
+
|
187
|
+
### Association Loading Control
|
188
|
+
|
189
|
+
You can further refine how associations are loaded using limits and reciprocal prevention:
|
190
|
+
|
191
|
+
```ruby
|
192
|
+
RealDataTests.configure do |config|
|
193
|
+
# Limit the number of records loaded for specific associations
|
194
|
+
config.limit_association 'Patient.visit_notes', 10
|
195
|
+
|
196
|
+
# Prevent loading associations in the reverse direction
|
197
|
+
config.prevent_reciprocal 'VisitNoteType.visit_notes'
|
198
|
+
end
|
199
|
+
```
|
200
|
+
|
201
|
+
### Best Practices for Association Control
|
202
|
+
|
203
|
+
1. **Start with Global Rules**: Define global association rules that apply to most models
|
204
|
+
2. **Add Model-Specific Rules**: Use `include_associations_for` when you need different rules for specific models
|
205
|
+
3. **Control Data Volume**: Use `limit_association` for has_many relationships that could return large numbers of records
|
206
|
+
4. **Prevent Cycles**: Use `prevent_reciprocal` to break circular references in your association chain
|
207
|
+
5. **Monitor Performance**: Watch the size of your dump files and adjust your association rules as needed
|
208
|
+
|
209
|
+
## Association Filtering
|
210
|
+
|
211
|
+
Real Data Tests provides two mutually exclusive approaches to control which associations are collected:
|
212
|
+
|
213
|
+
### Whitelist Mode
|
214
|
+
Use this when you want to ONLY collect specific associations:
|
215
|
+
```ruby
|
216
|
+
RealDataTests.configure do |config|
|
217
|
+
config.include_associations(
|
218
|
+
:user,
|
219
|
+
:profile,
|
220
|
+
:posts,
|
221
|
+
:comments
|
222
|
+
)
|
223
|
+
end
|
224
|
+
```
|
225
|
+
|
226
|
+
### Blacklist Mode
|
227
|
+
Use this when you want to collect all associations EXCEPT specific ones:
|
228
|
+
```ruby
|
229
|
+
RealDataTests.configure do |config|
|
230
|
+
config.exclude_associations(
|
231
|
+
:large_association,
|
232
|
+
:unused_association
|
233
|
+
)
|
234
|
+
end
|
235
|
+
```
|
236
|
+
|
237
|
+
> **Note**: You must choose either blacklist or whitelist mode, not both. Attempting to use both will raise an error.
|
238
|
+
|
239
|
+
## Data Anonymization
|
240
|
+
|
241
|
+
Real Data Tests uses lambdas with the Faker gem for flexible data anonymization. Each anonymization rule receives the record as an argument, allowing for dynamic value generation:
|
242
|
+
|
243
|
+
```ruby
|
244
|
+
RealDataTests.configure do |config|
|
245
|
+
config.anonymize 'User', {
|
246
|
+
# Simple value replacement
|
247
|
+
first_name: -> (_) { Faker::Name.first_name },
|
248
|
+
|
249
|
+
# Dynamic value based on record
|
250
|
+
email: -> (user) { Faker::Internet.email(name: "user#{user.id}") },
|
251
|
+
|
252
|
+
# Custom anonymization logic
|
253
|
+
full_name: -> (user) {
|
254
|
+
"#{Faker::Name.first_name} #{Faker::Name.last_name}"
|
255
|
+
}
|
256
|
+
}
|
257
|
+
end
|
258
|
+
```
|
259
|
+
|
260
|
+
### Common Faker Examples
|
261
|
+
|
262
|
+
```ruby
|
263
|
+
{
|
264
|
+
name: -> (_) { Faker::Name.name },
|
265
|
+
username: -> (_) { Faker::Internet.username },
|
266
|
+
email: -> (_) { Faker::Internet.email },
|
267
|
+
phone: -> (_) { Faker::PhoneNumber.phone_number },
|
268
|
+
address: -> (_) { Faker::Address.street_address },
|
269
|
+
company: -> (_) { Faker::Company.name },
|
270
|
+
description: -> (_) { Faker::Lorem.paragraph }
|
271
|
+
}
|
272
|
+
```
|
273
|
+
|
274
|
+
See the [Faker documentation](https://github.com/faker-ruby/faker) for a complete list of available generators.
|
275
|
+
|
276
|
+
## Database Cleaner Integration
|
277
|
+
|
278
|
+
If you're using DatabaseCleaner with models that have foreign key constraints, you'll need to handle the cleanup order carefully.
|
279
|
+
|
280
|
+
### Disable Foreign Key Constraints During Cleanup
|
281
|
+
Add this to your DatabaseCleaner configuration:
|
282
|
+
|
283
|
+
```ruby
|
284
|
+
config.append_after(:suite) do
|
285
|
+
# Disable foreign key constraints
|
286
|
+
ActiveRecord::Base.connection.execute('SET session_replication_role = replica;')
|
287
|
+
begin
|
288
|
+
# Your cleanup code here
|
289
|
+
SKIP_MODELS.each { |model| model.delete_all }
|
290
|
+
ensure
|
291
|
+
# Re-enable foreign key constraints
|
292
|
+
ActiveRecord::Base.connection.execute('SET session_replication_role = DEFAULT;')
|
293
|
+
end
|
294
|
+
end
|
295
|
+
```
|
296
|
+
|
297
|
+
## How It Works
|
298
|
+
|
299
|
+
1. **Record Collection**: The gem analyzes your ActiveRecord associations to find all related records.
|
300
|
+
2. **Dump Generation**: It creates a PostgreSQL dump file containing only the necessary records.
|
301
|
+
3. **Test Loading**: During tests, it loads the dump file into your test database.
|
302
|
+
|
303
|
+
## Best Practices
|
304
|
+
|
305
|
+
1. **Version Control**: Commit your SQL dumps to version control so all developers have access to the same test data.
|
306
|
+
2. **Meaningful Names**: Use descriptive names for your dump files that indicate the scenario they represent.
|
307
|
+
3. **Data Privacy**: Always use anonymization for sensitive data before creating dumps.
|
308
|
+
4. **Association Control**: Use association filtering to keep dumps focused and maintainable.
|
309
|
+
5. **Unique Identifiers**: Use record IDs in anonymized data to maintain uniqueness (e.g., emails).
|
310
|
+
|
311
|
+
## Development
|
312
|
+
|
313
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
314
|
+
|
315
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
316
|
+
|
317
|
+
## Contributing
|
318
|
+
|
319
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/diasks2/real_data_tests. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/diasks2/real_data_tests/blob/main/CODE_OF_CONDUCT.md).
|
320
|
+
|
321
|
+
## License
|
322
|
+
|
323
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
324
|
+
|
325
|
+
## Code of Conduct
|
326
|
+
|
327
|
+
Everyone interacting in the Real Data Tests project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/diasks2/real_data_tests/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,116 @@
|
|
1
|
+
# lib/real_data_tests/configuration.rb
|
2
|
+
module RealDataTests
|
3
|
+
class Configuration
|
4
|
+
attr_accessor :dump_path, :cleanup_models
|
5
|
+
attr_reader :association_filter_mode, :association_filter_list, :anonymization_rules,
|
6
|
+
:model_specific_associations, :association_limits, :prevent_reciprocal_loading
|
7
|
+
|
8
|
+
def initialize
|
9
|
+
@dump_path = 'spec/fixtures/real_data_dumps'
|
10
|
+
@anonymization_rules = {}
|
11
|
+
@association_filter_mode = nil
|
12
|
+
@association_filter_list = []
|
13
|
+
@model_specific_associations = {}
|
14
|
+
@cleanup_models = []
|
15
|
+
@association_limits = {}
|
16
|
+
@prevent_reciprocal_loading = {}
|
17
|
+
end
|
18
|
+
|
19
|
+
def anonymize(model_name, mappings = {})
|
20
|
+
if defined?(::Rails::Engine)
|
21
|
+
unless ::Rails::Engine.subclasses.map(&:name).include?('RealDataTests::Engine')
|
22
|
+
@delayed_anonymizations << [model_name, mappings]
|
23
|
+
return
|
24
|
+
end
|
25
|
+
end
|
26
|
+
|
27
|
+
begin
|
28
|
+
model = model_name.to_s.constantize
|
29
|
+
@anonymization_rules[model_name.to_s] = mappings
|
30
|
+
rescue => e
|
31
|
+
warn "Note: Anonymization for #{model_name} will be configured when Rails is fully initialized."
|
32
|
+
end
|
33
|
+
end
|
34
|
+
|
35
|
+
def process_delayed_anonymizations
|
36
|
+
return unless @delayed_anonymizations
|
37
|
+
|
38
|
+
@delayed_anonymizations.each do |model_name, mappings|
|
39
|
+
anonymize(model_name, mappings)
|
40
|
+
end
|
41
|
+
@delayed_anonymizations = []
|
42
|
+
end
|
43
|
+
|
44
|
+
def exclude_associations(*associations)
|
45
|
+
if @association_filter_mode == :whitelist
|
46
|
+
raise Error, "Cannot set excluded_associations when included_associations is already set"
|
47
|
+
end
|
48
|
+
|
49
|
+
@association_filter_mode = :blacklist
|
50
|
+
@association_filter_list = associations.flatten
|
51
|
+
end
|
52
|
+
|
53
|
+
def include_associations(*associations)
|
54
|
+
if @association_filter_mode == :blacklist
|
55
|
+
raise Error, "Cannot set included_associations when excluded_associations is already set"
|
56
|
+
end
|
57
|
+
@association_filter_mode = :whitelist
|
58
|
+
@association_filter_list = associations.flatten
|
59
|
+
end
|
60
|
+
|
61
|
+
# New method for model-specific association rules
|
62
|
+
def include_associations_for(model, *associations)
|
63
|
+
model_name = model.is_a?(String) ? model : model.name
|
64
|
+
@model_specific_associations[model_name] = associations.flatten
|
65
|
+
end
|
66
|
+
|
67
|
+
def should_process_association?(model, association_name)
|
68
|
+
model_name = model.is_a?(Class) ? model.name : model.class.name
|
69
|
+
|
70
|
+
# Check model-specific rules first
|
71
|
+
if @model_specific_associations.key?(model_name)
|
72
|
+
return @model_specific_associations[model_name].include?(association_name)
|
73
|
+
end
|
74
|
+
|
75
|
+
# Fall back to global rules
|
76
|
+
case @association_filter_mode
|
77
|
+
when :whitelist
|
78
|
+
@association_filter_list.include?(association_name)
|
79
|
+
when :blacklist
|
80
|
+
!@association_filter_list.include?(association_name)
|
81
|
+
else
|
82
|
+
true
|
83
|
+
end
|
84
|
+
end
|
85
|
+
|
86
|
+
def configure_cleanup(*models)
|
87
|
+
@cleanup_models = models.flatten
|
88
|
+
end
|
89
|
+
|
90
|
+
# Configure limits for specific associations
|
91
|
+
# Example: limit_association 'Patient.visit_notes', 10
|
92
|
+
def limit_association(path, limit)
|
93
|
+
@association_limits[path.to_s] = limit
|
94
|
+
end
|
95
|
+
|
96
|
+
# Prevent loading reciprocal associations
|
97
|
+
# Example: prevent_reciprocal 'VisitNoteType.visit_notes'
|
98
|
+
def prevent_reciprocal(path)
|
99
|
+
@prevent_reciprocal_loading[path.to_s] = true
|
100
|
+
end
|
101
|
+
|
102
|
+
# Get limit for a specific association
|
103
|
+
def get_association_limit(record_class, association_name)
|
104
|
+
path = "#{record_class.name}.#{association_name}"
|
105
|
+
@association_limits[path]
|
106
|
+
end
|
107
|
+
|
108
|
+
# Check if reciprocal loading should be prevented
|
109
|
+
def prevent_reciprocal?(record_class, association_name)
|
110
|
+
path = "#{record_class.name}.#{association_name}"
|
111
|
+
@prevent_reciprocal_loading[path]
|
112
|
+
end
|
113
|
+
end
|
114
|
+
|
115
|
+
class Error < StandardError; end
|
116
|
+
end
|
@@ -0,0 +1,58 @@
|
|
1
|
+
# lib/real_data_tests/data_anonymizer.rb
|
2
|
+
require 'faker'
|
3
|
+
|
4
|
+
module RealDataTests
|
5
|
+
class DataAnonymizer
|
6
|
+
def initialize(configuration)
|
7
|
+
@configuration = configuration
|
8
|
+
end
|
9
|
+
|
10
|
+
def anonymize_records(records)
|
11
|
+
records.map do |record|
|
12
|
+
anonymize_record(record)
|
13
|
+
end
|
14
|
+
end
|
15
|
+
|
16
|
+
def anonymize_record(record)
|
17
|
+
return record unless should_anonymize?(record)
|
18
|
+
|
19
|
+
anonymization_rules = @configuration.anonymization_rules[record.class.name]
|
20
|
+
|
21
|
+
anonymization_rules.each do |attribute, anonymizer|
|
22
|
+
begin
|
23
|
+
new_value = case anonymizer
|
24
|
+
when String
|
25
|
+
# Handle legacy string-based Faker calls
|
26
|
+
process_faker_string(anonymizer)
|
27
|
+
when Proc, Lambda
|
28
|
+
# Handle lambda-based anonymizers
|
29
|
+
anonymizer.call(record)
|
30
|
+
else
|
31
|
+
raise Error, "Unsupported anonymizer type: #{anonymizer.class}"
|
32
|
+
end
|
33
|
+
|
34
|
+
record.send("#{attribute}=", new_value)
|
35
|
+
rescue => e
|
36
|
+
raise Error, "Failed to anonymize #{attribute} using #{anonymizer.inspect}: #{e.message}"
|
37
|
+
end
|
38
|
+
end
|
39
|
+
|
40
|
+
record
|
41
|
+
end
|
42
|
+
|
43
|
+
private
|
44
|
+
|
45
|
+
def should_anonymize?(record)
|
46
|
+
@configuration.anonymization_rules.key?(record.class.name)
|
47
|
+
end
|
48
|
+
|
49
|
+
def process_faker_string(faker_method)
|
50
|
+
# Support legacy string format like "Faker::Name.first_name"
|
51
|
+
faker_class, faker_method = faker_method.split('::')[1..].join('::').split('.')
|
52
|
+
faker_class = Object.const_get("Faker::#{faker_class}")
|
53
|
+
faker_class.send(faker_method)
|
54
|
+
rescue => e
|
55
|
+
raise Error, "Failed to process Faker method '#{faker_method}': #{e.message}"
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|
@@ -0,0 +1,17 @@
|
|
1
|
+
require 'rails'
|
2
|
+
|
3
|
+
module RealDataTests
|
4
|
+
class Engine < ::Rails::Engine
|
5
|
+
isolate_namespace RealDataTests
|
6
|
+
|
7
|
+
config.before_configuration do
|
8
|
+
RealDataTests.configuration
|
9
|
+
end
|
10
|
+
|
11
|
+
initializer 'real_data_tests.initialize' do |app|
|
12
|
+
if RealDataTests.configuration
|
13
|
+
RealDataTests.configuration.process_delayed_anonymizations
|
14
|
+
end
|
15
|
+
end
|
16
|
+
end
|
17
|
+
end
|