agplatform 0.4.1

Platform providing env, fs, request and process infrastructure for production and testing
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
#[cfg(any(feature = "process", feature = "request"))]
mod gate;
pub mod test_env;
#[cfg(feature = "fs")]
pub mod test_fs;
#[cfg(feature = "process")]
pub mod test_process;
#[cfg(feature = "request")]
pub mod test_request;

use crate::Platform;
use crate::TestEnv;

/// The root directory of a new [`TestEnv`], `TestFs` and `TestProcess`.
#[cfg(unix)]
pub const ROOT: &str = "/";
/// The root directory of a new [`TestEnv`], `TestFs` and `TestProcess`.
#[cfg(windows)]
pub const ROOT: &str = "C:\\";

/// Enabled by the `testing` feature flag.
///
/// The test platform is a memory-only but fully functional mock
/// implementation of the [`Platform`] trait. It is used in tests to be
/// passed where `impl Platform` is expected.
///
/// # Examples
///
/// ```rust
/// use agplatform::Platform;
/// use agplatform::test_platform::test_platform;
///
/// fn do_something(platform: &impl Platform) {}
///
/// let test_platform = test_platform();
/// do_something(&test_platform);
/// ```
pub struct TestPlatform {
    pub env: TestEnv,
    #[cfg(feature = "fs")]
    pub fs: crate::TestFs,
    #[cfg(feature = "process")]
    pub process: crate::TestProcess,
    #[cfg(feature = "request")]
    pub request: crate::TestRequest,
}

impl TestPlatform {
    /// Creates a test platform with the specified test environment.
    ///
    /// Like in production, its current directory becomes that of the file
    /// system and process interfaces and its variables configure the
    /// request interface. Its variables are the environment inherited by
    /// the commands of the process interface, so they are not recorded as
    /// changes in `TestCall::vars`.
    ///
    /// See [`crate::TestEnv`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{Platform, Env};
    /// use agplatform::test_platform::test_platform;
    ///
    /// let test_env = agplatform::TestEnv::new().with_args(vec!["arg1", "arg2"]);
    /// let test_platform = test_platform().with_env(test_env);
    /// assert_eq!(test_platform.env().args().collect::<Vec<_>>(), &["arg1", "arg2"]);
    /// ```
    pub fn with_env(mut self, env: TestEnv) -> Self {
        #[cfg(feature = "fs")]
        self.fs.set_env(env.shared().clone());
        #[cfg(feature = "process")]
        self.process.set_env(env.shared().clone());
        #[cfg(feature = "request")]
        self.request.set_env(env.shared().clone());
        self.env = env;
        self
    }

    /// Enabled by the `fs` feature flag.
    ///
    /// Creates a test platform with the specified test file system, whose
    /// current directory is set to that of the environment.
    ///
    /// See [`crate::TestFs`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{Platform, Fs};
    /// use agplatform::test_platform::test_platform;
    ///
    /// let test_fs = agplatform::TestFs::new();
    /// let test_platform = test_platform().with_fs(test_fs);
    /// ```
    #[cfg(feature = "fs")]
    pub fn with_fs(mut self, mut fs: crate::TestFs) -> Self {
        fs.set_env(self.env.shared().clone());
        self.fs = fs;
        self
    }

    /// Enabled by the `process` feature flag.
    ///
    /// Creates a test platform with the specified test process interface,
    /// whose current directory is set to that of the environment.
    ///
    /// See [`crate::TestProcess`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::Platform;
    /// use agplatform::test_platform::test_platform;
    ///
    /// let test_process = agplatform::TestProcess::new();
    /// let test_platform = test_platform().with_process(test_process);
    /// ```
    #[cfg(feature = "process")]
    pub fn with_process(mut self, mut process: crate::TestProcess) -> Self {
        process.set_env(self.env.shared().clone());
        self.process = process;
        self
    }

    /// Enabled by the `request` feature flag.
    ///
    /// Creates a test platform with the specified test request interface,
    /// configured by the variables of the environment.
    ///
    /// See [`crate::TestRequest`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::Platform;
    /// use agplatform::test_platform::test_platform;
    ///
    /// let test_request = agplatform::TestRequest::new();
    /// let test_platform = test_platform().with_request(test_request);
    /// ```
    #[cfg(feature = "request")]
    pub fn with_request(mut self, mut request: crate::TestRequest) -> Self {
        request.set_env(self.env.shared().clone());
        self.request = request;
        self
    }
}

impl Platform for TestPlatform {
    /// Returns a reference to the test environment.
    ///
    /// See [`crate::Platform::env`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{Env, Platform};
    /// use agplatform::test_platform::test_platform;
    ///
    /// let platform = test_platform();
    /// let env = platform.env();
    /// ```
    fn env(&self) -> &(impl crate::Env + use<>) {
        &self.env
    }

    /// Returns a reference to the test file system.
    ///
    /// See [`crate::Platform::fs`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{Fs, Platform};
    /// use agplatform::test_platform::test_platform;
    ///
    /// let platform = test_platform();
    /// let fs = platform.fs();
    /// ```
    #[cfg(feature = "fs")]
    fn fs(&self) -> &(impl crate::Fs + use<>) {
        &self.fs
    }

    /// Returns a reference to the test process interface.
    ///
    /// See [`crate::Platform::process`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{Platform, Process};
    /// use agplatform::test_platform::test_platform;
    ///
    /// let platform = test_platform();
    /// let process = platform.process();
    /// ```
    #[cfg(feature = "process")]
    fn process(&self) -> &(impl crate::Process + use<>) {
        &self.process
    }

    /// Returns a reference to the test request interface.
    ///
    /// See [`crate::Platform::request`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{Platform, Request};
    /// use agplatform::test_platform::test_platform;
    ///
    /// let platform = test_platform();
    /// let request = platform.request();
    /// ```
    #[cfg(feature = "request")]
    fn request(&self) -> &(impl crate::Request + use<>) {
        &self.request
    }
}

/// Returns an instance of [`TestPlatform`] that implements the
/// [`Platform`] trait via the mock implementations, sharing its
/// [`TestEnv`].
///
/// # Examples
///
/// ```rust
/// use agplatform::Platform;
/// use agplatform::test_platform::test_platform;
///
/// fn do_something(platform: &impl Platform) {}
///
/// let test_platform = test_platform();
/// do_something(&test_platform);
/// ```
pub fn test_platform() -> TestPlatform {
    TestPlatform {
        env: TestEnv::new(),
        #[cfg(feature = "fs")]
        fs: crate::TestFs::new(),
        #[cfg(feature = "process")]
        process: crate::TestProcess::new(),
        #[cfg(feature = "request")]
        request: crate::TestRequest::new(),
    }
    .with_env(TestEnv::new())
}

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

    #[cfg(all(unix, any(feature = "fs", feature = "process")))]
    const HOME: &str = "/home";
    #[cfg(all(windows, any(feature = "fs", feature = "process")))]
    const HOME: &str = "C:\\home";

    #[cfg(feature = "request")]
    fn reqwest_env(https_proxy: &str) -> crate::request::ReqwestEnv {
        crate::request::ReqwestEnv::new(&[("HTTPS_PROXY".to_string(), https_proxy.to_string())])
    }

    mod test_platform {
        use super::*;

        mod with_env {
            use super::*;

            #[test]
            fn with_env_should_set_custom_test_environment() {
                let test_env = TestEnv::new()
                    .with_args(vec!["arg1", "arg2"])
                    .with_current_dir("/home")
                    .with_current_exe("/tmp/project/app")
                    .with_home_dir("/home/user")
                    .with_tmp_dir("/tmp")
                    .with_vars(vec![("KEY1", "value1"), ("KEY2", "value2")]);
                let p = test_platform().with_env(test_env);
                let e = p.env();

                assert_eq!(e.args().collect::<Vec<_>>(), &["arg1", "arg2"]);
                assert_eq!(e.current_dir(), std::path::Path::new("/home"));
                assert_eq!(e.set_current_dir("/tmp"), std::path::Path::new("/home"));
                assert_eq!(e.current_dir(), std::path::Path::new("/tmp"));
                assert_eq!(e.current_exe(), std::path::Path::new("/tmp/project/app"));
                assert_eq!(e.home_dir(), std::path::Path::new("/home/user"));
                assert_eq!(e.tmp_dir(), std::path::Path::new("/tmp"));
                assert_eq!(e.var("KEY1").as_deref(), Some("value1"));
                assert_eq!(e.var("KEY2").as_deref(), Some("value2"));
                assert_eq!(e.var("NON_EXISTENT_KEY"), None);
                assert_eq!(e.set_var("NON_EXISTENT_KEY", "value"), None);
                assert_eq!(e.remove_var("NON_EXISTENT_KEY"), Some("value".to_string()));
                assert_eq!(e.set_var("KEY1", "new_value"), Some("value1".to_string()));
                assert_eq!(
                    e.vars().collect::<Vec<_>>(),
                    vec![
                        ("KEY1".to_string(), "new_value".to_string()),
                        ("KEY2".to_string(), "value2".to_string())
                    ]
                );
            }

            #[cfg(feature = "request")]
            #[test]
            fn with_env_should_pass_proxy_variables_to_request() {
                let test_env = TestEnv::new().with_vars(vec![("HTTPS_PROXY", "http://proxy")]);

                let test_platform = test_platform().with_env(test_env);

                assert_eq!(
                    test_platform.request.clients.reqwest_env(),
                    reqwest_env("http://proxy")
                );
            }

            #[cfg(feature = "fs")]
            #[test]
            fn with_env_should_set_current_dir_of_fs() {
                use crate::Fs;

                // GIVEN a platform with a file system
                let test_platform = test_platform().with_fs(crate::TestFs::new());

                // WHEN an environment with another current directory is set
                let test_platform = test_platform.with_env(TestEnv::new().with_current_dir(HOME));

                // THEN relative fs paths resolve against it
                test_platform.fs().create_dir_all(HOME).unwrap();
                assert_eq!(
                    test_platform.fs().canonicalize(".").unwrap(),
                    std::path::Path::new(HOME)
                );
            }

            #[cfg(feature = "process")]
            #[test]
            fn with_env_should_set_current_dir_of_process() {
                let test_platform = test_platform()
                    .with_process(crate::TestProcess::new())
                    .with_env(TestEnv::new().with_current_dir(HOME));

                assert_eq!(
                    test_platform.process.current_dir(),
                    std::path::Path::new(HOME)
                );
            }

            #[cfg(feature = "process")]
            #[test]
            fn with_env_should_not_record_vars_as_process_changes() {
                use crate::CommandExt;

                // GIVEN a platform with an environment holding a variable
                let test_platform =
                    test_platform().with_env(TestEnv::new().with_vars(vec![("KEY", "value")]));
                test_platform.process.set_output(
                    "git",
                    crate::CommandOutput {
                        status: Some(0),
                        ..Default::default()
                    },
                );

                // WHEN running a command
                std::process::Command::new("git")
                    .run(test_platform.process())
                    .unwrap();

                // THEN the variable is inherited rather than changed
                assert_eq!(test_platform.process.call_details()[0].vars, []);
            }
        }

        #[cfg(feature = "process")]
        mod with_process {
            use super::*;

            #[test]
            fn with_process_should_take_current_dir_of_env() {
                let test_platform = test_platform()
                    .with_env(TestEnv::new().with_current_dir(HOME))
                    .with_process(crate::TestProcess::new());

                assert_eq!(
                    test_platform.process.current_dir(),
                    std::path::Path::new(HOME)
                );
            }
        }

        #[cfg(feature = "request")]
        mod with_request {
            use super::*;

            #[test]
            fn with_request_should_pass_proxy_variables_of_env() {
                let test_env = TestEnv::new().with_vars(vec![("HTTPS_PROXY", "http://proxy")]);

                let test_platform = test_platform()
                    .with_env(test_env)
                    .with_request(crate::TestRequest::new());

                assert_eq!(
                    test_platform.request.clients.reqwest_env(),
                    reqwest_env("http://proxy")
                );
            }
        }

        #[cfg(feature = "fs")]
        mod with_fs {
            use super::*;
            use crate::Fs;

            #[test]
            fn with_fs_should_set_custom_test_filesystem() {
                let test_fs = crate::TestFs::new();
                let test_platform = test_platform().with_fs(test_fs);
                test_platform.env().set_current_dir("/tmp");
                test_platform.fs().create_dir_all("/tmp").unwrap();
                test_platform.fs().write("/tmp/file.txt", "hello").unwrap();

                assert_eq!(
                    test_platform.fs().read("/tmp/file.txt").unwrap(),
                    vec![b'h', b'e', b'l', b'l', b'o'],
                );
                assert_eq!(
                    test_platform.fs().read_to_string("/tmp/file.txt").unwrap(),
                    "hello",
                );
            }

            #[test]
            fn with_fs_should_take_current_dir_of_env() {
                // GIVEN a platform with an environment with a current directory
                let test_platform = test_platform().with_env(TestEnv::new().with_current_dir(HOME));

                // WHEN a file system is set
                let test_platform = test_platform.with_fs(crate::TestFs::new());

                // THEN relative fs paths resolve against the current directory
                test_platform.fs().create_dir_all(HOME).unwrap();
                assert_eq!(
                    test_platform.fs().canonicalize(".").unwrap(),
                    std::path::Path::new(HOME)
                );
            }
        }

        mod platform {
            use super::*;

            mod env {
                use super::*;

                #[test]
                fn env_set_var_should_update_env() {
                    let test_platform = test_platform();

                    test_platform.env().set_var("KEY", "value");

                    assert_eq!(test_platform.env.var("KEY").as_deref(), Some("value"));
                }

                #[cfg(all(feature = "fs", feature = "process"))]
                #[test]
                fn env_set_current_dir_should_update_fs_and_process() {
                    use crate::Fs;

                    // GIVEN an existing directory
                    let test_platform = test_platform();
                    test_platform.fs().create_dir_all("/tmp").unwrap();

                    #[cfg(unix)]
                    const CURRENT_DIR: &str = "/tmp";
                    #[cfg(windows)]
                    const CURRENT_DIR: &str = "C:\\tmp";

                    // WHEN it becomes the current directory
                    test_platform.env().set_current_dir(CURRENT_DIR);

                    // THEN relative fs paths resolve against it
                    assert_eq!(
                        test_platform.fs().canonicalize(".").unwrap(),
                        std::path::Path::new(CURRENT_DIR)
                    );
                    assert_eq!(
                        test_platform.env.current_dir(),
                        std::path::Path::new(CURRENT_DIR)
                    );
                    assert_eq!(
                        test_platform.process.current_dir(),
                        std::path::Path::new(CURRENT_DIR)
                    );
                }

                #[cfg(all(feature = "fs", feature = "process"))]
                #[test]
                fn env_set_current_dir_relative_should_pass_resolved_dir_to_fs_and_process() {
                    use crate::Fs;

                    // GIVEN a platform in an existing directory
                    let test_platform =
                        test_platform().with_env(TestEnv::new().with_current_dir(HOME));
                    test_platform.fs().create_dir_all(HOME).unwrap();
                    let expected = std::path::Path::new(HOME).join("a");
                    test_platform.fs().create_dir_all("a").unwrap();

                    // WHEN a relative directory becomes the current directory
                    test_platform.env().set_current_dir("b/../a/.");

                    // THEN the env, fs and process resolve it against the previous one
                    assert_eq!(test_platform.env.current_dir(), expected);
                    assert_eq!(test_platform.fs().canonicalize(".").unwrap(), expected);
                    assert_eq!(test_platform.process.current_dir(), expected);
                }

                #[cfg(feature = "process")]
                #[test]
                fn env_set_and_remove_var_should_be_applied_to_commands() {
                    use crate::CommandExt;

                    // GIVEN a platform with variables set and removed
                    let test_platform = test_platform();
                    test_platform.process.set_output(
                        "git",
                        crate::CommandOutput {
                            status: Some(0),
                            ..Default::default()
                        },
                    );
                    test_platform.env().set_var("SET", "value");
                    test_platform.env().remove_var("REMOVED");

                    // WHEN running a command
                    std::process::Command::new("git")
                        .run(test_platform.process())
                        .unwrap();

                    // THEN the changes are applied to it
                    assert_eq!(
                        test_platform.process.call_details()[0].vars,
                        [
                            ("SET".to_string(), Some("value".to_string())),
                            ("REMOVED".to_string(), None)
                        ]
                    );
                }

                #[cfg(feature = "request")]
                #[test]
                fn env_set_and_remove_var_should_update_request_proxy_variables() {
                    let test_platform = test_platform();

                    test_platform.env().set_var("HTTPS_PROXY", "http://proxy");
                    let set = test_platform.request.clients.reqwest_env();
                    test_platform.env().remove_var("HTTPS_PROXY");

                    assert_eq!(set, reqwest_env("http://proxy"));
                    assert_eq!(
                        test_platform.request.clients.reqwest_env(),
                        crate::request::ReqwestEnv::default()
                    );
                }

                #[cfg(feature = "fs")]
                #[test]
                fn env_set_current_dir_should_be_seen_by_platform_shared_in_arc() {
                    use crate::Fs;
                    use std::sync::Arc;

                    // GIVEN a platform shared with another thread
                    let platform =
                        Arc::new(test_platform().with_env(TestEnv::new().with_current_dir(HOME)));
                    platform.fs().create_dir_all("a").unwrap();
                    let shared = platform.clone();

                    // WHEN the other thread changes the current directory
                    std::thread::spawn(move || shared.env().set_current_dir("a"))
                        .join()
                        .unwrap();

                    // THEN relative paths resolve against it
                    assert_eq!(
                        platform.fs().canonicalize(".").unwrap(),
                        std::path::Path::new(HOME).join("a")
                    );
                }
            }
        }
    }
}