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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
#![deny(missing_docs)]
//! Simpath - or Simple Path is a small library for creating, manipulating and using Unix style
//! `Path`s.
//!
//! A `Path` is an environment variable (a String) with one or more directories specified.
//! They are usually used to find a file that resides in one of the directories.
//! On most platform the default separator character is `:` but on Windows it is `;`
//!
//! If you wish to separate entries with a different separator, it can be modified via API.
//!
#[cfg(feature = "urls")]
extern crate curl;
#[cfg(feature = "urls")]
extern crate url;

use std::env;
use std::fmt;
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::PathBuf;

#[cfg(feature = "urls")]
use curl::easy::{Handler, WriteError};
#[cfg(feature = "urls")]
use url::Url;
use std::collections::HashSet;

#[cfg(feature = "urls")]
struct Collector(Vec<u8>);

#[cfg(feature = "urls")]
impl Handler for Collector {
    fn write(&mut self, data: &[u8]) -> std::result::Result<usize, WriteError> {
        self.0.extend_from_slice(data);
        Ok(data.len())
    }
}

// Character used to separate directories in a Path Environment variable on windows is ";"
#[cfg(target_family = "windows")]
const DEFAULT_SEPARATOR_CHAR: char = ';';
// Character used to separate directories in a Path Environment variable on linux/mac/unix is ":"
#[cfg(not(target_family = "windows"))]
const DEFAULT_SEPARATOR_CHAR: char = ':';

/// `Simpath` is the struct returned when you create a new on using a named environment variable
/// which you then use to interact with the `Simpath`
#[derive(Clone, Debug)]
pub struct Simpath {
    separator: char,
    name: String,
    directories: HashSet<PathBuf>,
    #[cfg(feature = "urls")]
    urls: HashSet<Url>,
}

/// `FileType` can be used to find an entry in a path of a specific type (`Directory`, `File`, `URL`)
/// or of `Any` type
#[derive(Debug, PartialEq)]
pub enum FileType {
    /// An entry in the `Simpath` of type `File`
    File,
    /// An entry in the `Simpath` of type `Directory`
    Directory,
    /// An entry in the `Simpath` of type `Url`
    Resource,
    /// An entry in the `Simpath` of `Any` types
    Any,
}

/// `FoundType` indicates what type of entry was found
#[derive(Debug, PartialEq)]
pub enum FoundType {
    /// An entry in the `Simpath` of type `File`
    File(PathBuf),
    /// An entry in the `Simpath` of type `Directory`
    Directory(PathBuf),
    #[cfg(feature = "urls")]
    /// An entry in the `Simpath` of type `Url`
    Resource(Url),
}

/// When validating a `Simpath` there can be the following types of `PathError`s returned
pub enum PathError {
    /// The `Path` entry does not exist on the file system
    DoesNotExist(String),
    /// The `Path` entry cannot be reads
    CannotRead(String),
}

impl Simpath {
    /// Create a new simpath, providing the name of the environment variable to initialize the
    /// search path with. If an environment variable of that name exists and it will be parsed
    /// as a ':' separated list of paths to search. Only paths detected as directories will
    /// be used, not files.
    ///
    /// If an environment variable of that name is *not* found, a new simpath will be created anyway
    /// and it can have directories added to it programatically and used in the normal fashion to
    /// search for files
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let search_path = Simpath::new("PATH");
    ///     let ls_file = search_path.find("ls");
    ///     match ls_file {
    ///         Ok(found) => println!("'ls' was found at '{:?}'", found),
    ///         Err(e)   => println!("{}", e)
    ///     }
    /// }
    /// ```
    ///
    pub fn new(var_name: &str) -> Self {
        let mut search_path = Simpath {
            separator: DEFAULT_SEPARATOR_CHAR,
            name: var_name.to_string(),
            directories: HashSet::<PathBuf>::new(),
            #[cfg(feature = "urls")]
            urls: HashSet::<Url>::new(),
        };

        search_path.add_from_env_var(var_name);

        search_path
    }

    /// Create a new simpath, providing the name of the environment variable to initialize the
    /// search path with and the separator character for this search path to be used from here on.
    /// If an environment variable of that name exists and it will be parsed as a list of paths to
    /// search. Only paths detected as directories will be used, not files.
    ///
    /// If an environment variable of that name is *not* found, a new simpath will be created anyway
    /// and it can have directories added to it programatically and used in the normal fashion to
    /// search for files.
    ///
    /// In all cases, the separator char for this search path will be set to `separator` from here on.
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    /// use std::env;
    ///
    /// fn main() {
    ///     env::set_var("TEST", "/,.,~");
    ///     let search_path = Simpath::new("TEST");
    ///     let two = search_path.find(".");
    ///     match two {
    ///         Ok(found) => println!("'.' was found at '{:?}'", found),
    ///         Err(e)   => println!("{}", e)
    ///     }
    /// }
    /// ```
    pub fn new_with_separator(var_name: &str, separator: char) -> Self {
        let mut search_path = Simpath {
            separator,
            name: var_name.to_string(),
            directories: HashSet::<PathBuf>::new(),
            #[cfg(feature = "urls")]
            urls: HashSet::<Url>::new(),
        };

        search_path.add_from_env_var(var_name);

        search_path
    }

    /// Get the currently set separator character that is used when parsing entries from an environment
    /// variable
    pub fn separator(&self) -> char {
        self.separator
    }

    /// Get the name associated with the simpath. Note that this could be an empty String
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let search_path = Simpath::new("PATH");
    ///     println!("Directories in Search Path: {:?}", search_path.name());
    /// }
    /// ```
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the list of directories that are included in the Search Path
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let search_path = Simpath::new("PATH");
    ///     println!("Directories in Search Path: {:?}", search_path.directories());
    /// }
    /// ```
    pub fn directories(&self) -> &HashSet<PathBuf> {
        &self.directories
    }

    #[cfg(feature = "urls")]
    /// Get the list of URLs that are included in the Search Path
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    /// use std::env;
    ///
    /// fn main() {
    ///     env::set_var("TEST", "http://ibm.com,https://hp.com");
    ///     let search_path = Simpath::new("TEST");
    ///     println!("URLs in Search Path: {:?}", search_path.urls());
    /// }
    /// ```
    pub fn urls(&self) -> &HashSet<Url> {
        &self.urls
    }

    /// Try to find a file or resource by name (not full path) on a search path.
    /// Searching for a file could cause errors, so Result<FoundType, io::Error> is returned
    /// If it is found `Ok(FoundType)` is returned indicating where the resource/file can be found.
    /// If it is not found then `Err` is returned.
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let search_path = Simpath::new("PATH");
    ///     match search_path.find("my-file") {
    ///         Ok(_found_dir) => println!("Didn't expect that!!"),
    ///         Err(e)         => println!("{}", e.to_string())
    ///     }
    /// }
    /// ```
    pub fn find(&self, file_name: &str) -> Result<FoundType, Error> {
        self.find_type(file_name, FileType::Any)
    }

    /// find an entry of a specific `FileType` in a `Path`
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     use simpath::FileType;
    ///     let search_path = Simpath::new("PATH");
    ///     match search_path.find_type("my-file", FileType::Directory) {
    ///         Ok(_found_dir) => println!("Didn't expect that!!"),
    ///         Err(e)         => println!("{}", e.to_string())
    ///     }
    /// }
    /// ```
    pub fn find_type(&self, file_name: &str, file_type: FileType) -> Result<FoundType, Error> {
        if file_type == FileType::File || file_type == FileType::Directory || file_type == FileType::Any {
            for search_dir in &self.directories {
                for entry in fs::read_dir(search_dir)? {
                    let file = entry?;
                    if let Some(filename) = file.file_name().to_str() {
                        if filename == file_name {
                            let found_filetype = file.metadata()?.file_type();
                            match file_type {
                                FileType::Any => return Ok(FoundType::File(file.path())),
                                FileType::Directory if found_filetype.is_dir() => return Ok(FoundType::Directory(file.path())),
                                FileType::File if found_filetype.is_file() || found_filetype.is_symlink() => return Ok(FoundType::File(file.path())),
                                _ => { /* keep looking */ }
                            }
                        }
                    }
                }
            }
        }

        #[cfg(feature = "urls")]
            // Look for a URL that ends with '/file_name'
        if file_type == FileType::Resource || file_type == FileType::Any {
            for url in &self.urls {
                let mut segments = url.path_segments()
                    .ok_or_else(|| Error::new(ErrorKind::NotFound, "Could not get path segments"))?;
                if segments.next_back() == Some(file_name) {
                    return Ok(FoundType::Resource(url.clone()));
                }
            }
        }

        Err(Error::new(ErrorKind::NotFound,
                       format!("Could not find type '{:?}' called '{}' in search path '{}'",
                               file_type, file_name, self.name)))
    }

    /// Add an to the search path.
    ///
    /// if "urls" feature is enabled:
    ///     If it parses as as web Url it will be added to the list of
    ///     base Urls to search, otherwise it will be added to the list of directories to search.
    /// if "urls" feature is *not* enabled:
    ///     It is assumed to be a directory and added using `add_directory()`
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let mut search_path = Simpath::new("PATH");
    ///     search_path.add(".");
    ///
    /// #[cfg(feature = "urls")]
    ///     search_path.add("http://ibm.com");
    ///
    ///     println!("{}", search_path);
    /// }
    /// ```
    pub fn add(&mut self, entry: &str) {
        #[cfg(not(feature = "urls"))]
            self.add_directory(entry);

        #[cfg(feature = "urls")]
        match Url::parse(entry) {
            Ok(url) => {
                match url.scheme() {
                    #[cfg(feature = "urls")]
                    "http" | "https" => self.add_url(&url),
                    "file" => self.add_directory(url.path()),
                    _ => self.add_directory(entry)
                }
            }
            Err(_) => self.add_directory(entry) /* default to being a directory path */
        }
    }

    /// Add a directory to the list of directories to search for files.
    /// If the directory passed does not exist, or is not a directory, or cannot be read then it
    /// will be ignored.
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let mut search_path = Simpath::new("PATH");
    ///     search_path.add_directory(".");
    ///     println!("Directories in Search Path: {:?}", search_path.directories());
    /// }
    /// ```
    pub fn add_directory(&mut self, dir: &str) {
        let path = PathBuf::from(dir);
        if path.exists() && path.is_dir() && path.read_dir().is_ok() {
            if let Ok(canonical) = path.canonicalize() {
                self.directories.insert(canonical);
            }
        }
    }

    #[cfg(feature = "urls")]
    /// Add a Url to the list of Base Urls to be used when searching for resources.
    ///
    /// ```
    /// extern crate simpath;
    /// extern crate url;
    ///
    /// use simpath::Simpath;
    /// use url::Url;
    ///
    /// fn main() {
    ///     let mut search_path = Simpath::new("WEB");
    ///     search_path.add_url(&Url::parse("http://ibm.com").unwrap());
    ///     println!("Urls in Search Path: {:?}", search_path.urls());
    /// }
    /// ```
    pub fn add_url(&mut self, url: &Url) {
        self.urls.insert(url.clone());
    }

    /// Check if a search path contains an entry
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let mut search_path = Simpath::new("FakeEnvVar");
    ///     if search_path.contains(".") {
    ///         println!("Well that's a surprise!");
    ///     }
    /// }
    /// ```
    pub fn contains(&self, entry: &str) -> bool {
        if let Ok(canonical) = PathBuf::from(entry).canonicalize() {
            if self.directories.contains(&canonical) {
                return true;
            }
        }

        #[cfg(feature = "urls")]
        if let Ok(url_entry) = Url::parse(entry) {
            return self.urls.contains(&url_entry);
        }

        false
    }

    /// Add entries to the search path, by reading them from an environment variable.
    ///
    /// The environment variable should have a set of entries separated by the separator character.
    /// By default the separator char is `":"` (on non-windows platforms) and `";"` (on windows)
    /// but it can be modified after creation of search path.
    ///
    /// The environment variable is parsed using the separator char set at the time this function
    /// is called.
    ///
    /// To be added each entry must exist and be readable.
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    ///
    /// fn main() {
    ///     let mut search_path = Simpath::new("MyPathName");
    ///     search_path.add_from_env_var("PATH");
    ///     if search_path.contains(".") {
    ///         println!("'.' was in your 'PATH' and has been added to the search path called '{}'",
    ///                  search_path.name());
    ///     }
    /// }
    /// ```
    pub fn add_from_env_var(&mut self, var_name: &str) {
        if let Ok(var_string) = env::var(var_name) {
            for part in var_string.split(self.separator) {
                self.add(part);
            }
        }
    }

    /// Add entries to the search path, by reading them from an environment variable.
    ///
    /// The environment variable should have a set of entries separated by the specified
    /// separator character.
    ///
    /// To be added each entry must exist and be readable.
    ///
    /// NOTE: The separator char is only used while parsing the specified environment variable and
    /// *does not* modify the separator character in use in the Simpath after this function completes.
    ///
    /// ```
    /// extern crate simpath;
    /// use simpath::Simpath;
    /// use std::env;
    ///
    /// fn main() {
    ///     let mut search_path = Simpath::new("MyPathName");
    ///     env::set_var("TEST", "/,.,~");
    ///     search_path.add_from_env_var_with_separator("TEST", ',');
    ///     if search_path.contains(".") {
    ///         println!("'.' was in your 'TEST' environment variable and has been added to the search path called '{}'",
    ///                  search_path.name());
    ///     }
    /// }
    /// ```
    pub fn add_from_env_var_with_separator(&mut self, var_name: &str, separator: char) {
        if let Ok(var_string) = env::var(var_name) {
            for part in var_string.split(separator) {
                self.add_directory(part);
            }
        }
    }
}

impl fmt::Display for Simpath {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Search Path '{}': Directories: {:?}", self.name, self.directories)?;

        #[cfg(feature = "urls")]
        write!(f, ", URLs: {:?}", self.urls)?;

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use std::env;
    use std::fs;
    use std::io::Write;

    use super::{DEFAULT_SEPARATOR_CHAR, FileType};

    use super::Simpath;

    #[test]
    fn can_create() {
        Simpath::new("PATH");
    }

    #[test]
    fn can_create_with_separator() {
        Simpath::new_with_separator("PATH", ':');
    }

    #[test]
    fn name_is_saved() {
        let path = Simpath::new("MyName");
        assert_eq!(path.name(), "MyName");
    }

    #[test]
    fn find_non_existant_file() {
        let path = Simpath::new("MyName");
        assert!(path.find("no_such_file").is_err());
    }

    #[test]
    fn display_empty_path() {
        let path = Simpath::new("MyName");
        println!("{}", path);
    }

    #[test]
    fn directory_is_added() {
        let mut path = Simpath::new("MyName");
        assert!(path.directories().is_empty());
        path.add_directory(".");
        let cwd = env::current_dir()
            .expect("Could not get current working directory").to_string_lossy().to_string();
        assert!(path.contains(&cwd));
    }

    #[test]
    fn cannot_add_same_dir_twice() {
        let mut path = Simpath::new("MyName");
        assert!(path.directories().is_empty());
        path.add_directory(".");
        path.add_directory(".");
        assert_eq!(path.directories().len(), 1);
    }

    #[test]
    fn cant_add_non_dir() {
        let mut path = Simpath::new("MyName");
        assert!(path.directories().is_empty());
        path.add_directory("no-such-dir");
        assert_eq!(path.contains("no-such-dir"), false);
    }

    #[test]
    fn find_dir_from_env_variable() {
        // Create a temp dir for test
        let temp_dir = tempdir::TempDir::new("simpath").unwrap().into_path();
        let mut parent_dir = temp_dir.clone();
        parent_dir.pop();

        // Create a ENV path that includes that dir
        let var_name = "MyPath";
        env::set_var(var_name, &parent_dir);

        // create a simpath from the env var
        let path = Simpath::new(var_name);

        // Check that simpath can find the temp_dir
        let temp_dir_name = format!("{}.{}",
                                    temp_dir.file_stem().unwrap().to_str().unwrap(),
                                    temp_dir.extension().unwrap().to_str().unwrap());
        assert!(path.find_type(&temp_dir_name, FileType::Directory).is_ok(),
                "Could not find the simpath temp directory in Path set from env var");

        // clean-up
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn find_file_from_env_variable() {
        // Create a temp dir for test
        let temp_dir = tempdir::TempDir::new("simpath").unwrap().into_path();

        // Create a ENV path that includes the path to the temp dir
        let var_name = "MYPATH";
        env::set_var(var_name, &temp_dir);

        // create a simpath from the env var
        let path = Simpath::new(var_name);

        // Create a file in the directory
        let temp_filename = "testfile";
        let temp_file_path = format!("{}/{}", temp_dir.display(), temp_filename);
        let mut file = fs::File::create(&temp_file_path).unwrap();
        file.write_all(b"test file contents").unwrap();

        // Check that simpath can find the file
        assert!(path.find_type(temp_filename, FileType::File).is_ok(),
                "Could not find 'testfile' in Path set from env var");

        // clean-up
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[cfg(unix)]
    #[test]
    fn find_link_from_env_variable() {
        // Create a temp dir for test
        let temp_dir = tempdir::TempDir::new("simpath").unwrap().into_path();

        // Create a ENV path that includes the path to the temp dir
        let var_name = "MYPATH";
        env::set_var(var_name, &temp_dir);

        // create a simpath from the env var
        let path = Simpath::new(var_name);

        // Create a file in the directory
        let temp_filename = "testfile";
        let temp_file_path = format!("{}/{}", temp_dir.display(), temp_filename);
        let mut file = fs::File::create(&temp_file_path).unwrap();
        file.write_all(b"test file contents").unwrap();

        // Create a link to the file
        let temp_linkname = "testlink";
        let temp_link_path = format!("{}/{}", temp_dir.display(), temp_linkname);
        std::os::unix::fs::symlink(temp_file_path, temp_link_path).expect("Could not create symlink");

        // Check that simpath can find the file
        assert!(path.find_type(temp_linkname, FileType::File).is_ok(),
                "Could not find 'testlink' in Path set from env var");

        // clean-up
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn find_dir_using_any_from_env_variable() {
        // Create a temp dir for test
        let temp_dir = tempdir::TempDir::new("simpath").unwrap().into_path();

        // Create a ENV path that includes that dir
        let var_name = "MyPath";
        env::set_var(var_name, &temp_dir);

        // create a simpath from the env var
        let path = Simpath::new(var_name);

        // Create a file in the directory
        let temp_filename = "testfile";
        let temp_file_path = format!("{}/{}", temp_dir.display(), temp_filename);
        let mut file = fs::File::create(&temp_file_path).unwrap();
        file.write_all(b"test file contents").unwrap();

        // Check that simpath can find it
        assert!(path.find(temp_filename).is_ok(),
                "Could not find the 'testfile' in Path set from env var");

        // clean-up
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn single_add_from_env_variable() {
        let var_name = "MyPath";
        env::set_var(var_name, ".");
        let path = Simpath::new(var_name);
        assert!(path.contains(&env::current_dir()
            .expect("Could not get current working directory").to_string_lossy().to_string()));
    }

    #[test]
    fn multiple_add_from_env_variable() {
        let var_name = "MyPath";
        env::set_var(var_name, format!(".{}/", DEFAULT_SEPARATOR_CHAR));
        let path = Simpath::new(var_name);
        assert!(path.contains(&env::current_dir()
            .expect("Could not get current working directory").to_string_lossy().to_string()));
        assert!(path.contains("/"));
    }

    #[test]
    fn multiple_add_from_env_variable_separator() {
        let var_name = "MyPath";
        env::set_var(var_name, ".,/");
        let path = Simpath::new_with_separator(var_name, ',');
        assert!(path.contains(&env::current_dir()
            .expect("Could not get current working directory").to_string_lossy().to_string()));
        assert!(path.contains("/"));
    }

    #[test]
    fn display_a_simpath_with_entries() {
        let var_name = "MyPath";
        env::set_var(var_name, format!(".{}/", DEFAULT_SEPARATOR_CHAR));
        let path = Simpath::new(var_name);
        println!("Simpath can be printed: {}", path);
    }

    #[test]
    fn entry_does_not_exist() {
        let var_name = "MyPath";
        env::set_var(var_name, "/foo");
        let path = Simpath::new(var_name);
        assert_eq!(path.directories().len(), 0);
    }

    #[test]
    fn one_entry_does_not_exist() {
        let var_name = "MyPath";
        env::set_var(var_name, format!(".{}/foo", DEFAULT_SEPARATOR_CHAR));
        let path = Simpath::new(var_name);
        assert_eq!(path.directories().len(), 1);
        assert!(!path.contains("/foo"));
    }

    #[cfg(feature = "urls")]
    mod url_tests {
        use std::env;
        use url::Url;
        use super::super::FileType;
        use super::Simpath;

        const BASE_URL: &str = "https://www.ibm.com";
        const EXISTING_RESOURCE: &str = "es-es";

        #[test]
        fn create_from_env() {
            let var_name = "MyPath";
            env::set_var(var_name, BASE_URL);
            let path = Simpath::new_with_separator(var_name, ',');
            assert_eq!(path.urls().len(), 1);
            assert_eq!(path.directories().len(), 0);
            assert!(path.urls().contains(&Url::parse(BASE_URL)
                .expect("Could not parse URL")));
        }

        #[test]
        fn add_url_that_exists() {
            let mut path = Simpath::new_with_separator("test", ',');
            path.add_url(&Url::parse(BASE_URL).expect("Could not parse Url"));
            assert_eq!(path.urls().len(), 1);
            assert_eq!(path.directories().len(), 0);
            assert!(path.urls().contains(&Url::parse(BASE_URL)
                .expect("Could not parse URL")));
        }

        #[test]
        fn cannot_add_same_url_twice() {
            let mut path = Simpath::new_with_separator("test", ',');
            path.add_url(&Url::parse(BASE_URL).expect("Could not parse Url"));
            path.add_url(&Url::parse(BASE_URL).expect("Could not parse Url"));
            assert_eq!(path.urls().len(), 1);
            assert_eq!(path.directories().len(), 0);
            assert!(path.urls().contains(&Url::parse(BASE_URL)
                .expect("Could not parse URL")));
        }

        #[test]
        fn find_resource_not_exist() {
            let mut search_path = Simpath::new("TEST");
            search_path.add_url(&Url::parse(BASE_URL).expect("Could not parse Url"));
            assert!(search_path.find_type("/no-way-this-exists", FileType::Resource).is_err(),
                    "should not find the resource");
        }

        #[test]
        fn find_existing_resource() {
            let mut search_path = Simpath::new("TEST");
            search_path.add_url(&Url::parse(BASE_URL).expect("Could not parse Url")
                .join(EXISTING_RESOURCE).expect("Could not join to Url"));
            search_path.find_type(EXISTING_RESOURCE, FileType::Resource).expect("Could not find resource");
        }

        #[test]
        fn contains_url_that_exists() {
            let var_name = "MyPath";
            env::set_var(var_name, BASE_URL);
            let path = Simpath::new_with_separator(var_name, ',');
            assert!(path.contains(BASE_URL));
        }

        #[test]
        fn display_path_with_directory_and_url() {
            let var_name = "MyPath";
            env::set_var(var_name, format!("~,{}", BASE_URL));
            let path = Simpath::new_with_separator(var_name, ',');
            println!("{}", path);
        }
    }
}