Skip to content

Implement assert a file matches a fixture on disk #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions src/path/fc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,24 @@ use std::fmt;
use std::fs;
use std::io::{self, Read};
use std::path;
use std::str;

use Predicate;

#[derive(Clone, Debug, PartialEq)]
pub struct FileContent(Vec<u8>);

impl FileContent {
pub fn new(path: &path::Path) -> io::Result<FileContent> {
let mut buffer = Vec::new();
fs::File::open(path)?.read_to_end(&mut buffer)?;
Ok(FileContent(buffer))
}
pub fn utf8(&self) -> Result<String, str::Utf8Error> {
str::from_utf8(&self.0).map(|s| s.to_string())
}
}

/// Predicate adaper that converts a `path` to file content predicate to byte predicate.
///
/// This is created by `pred.from_path()`.
Expand All @@ -29,11 +44,8 @@ where
P: Predicate<[u8]>,
{
fn eval(&self, path: &path::Path) -> io::Result<bool> {
let mut buffer = Vec::new();

// read the whole file
fs::File::open(path)?.read_to_end(&mut buffer)?;
Ok(self.p.eval(&buffer))
let buffer = FileContent::new(path)?;
Ok(self.p.eval(&buffer.0))
}
}

Expand Down
109 changes: 109 additions & 0 deletions src/path/fs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fmt;
use std::io;
use std::path;

use path::fc::FileContent;
use Predicate;

/// Predicate that compares file matches
#[derive(Clone, Debug)]
pub struct BinaryFilePredicate {
path: path::PathBuf,
file_content: FileContent,
}

impl BinaryFilePredicate {
fn eval(&self, path: &path::Path) -> io::Result<bool> {
let content = FileContent::new(path)?;
Ok(self.file_content == content)
}
}

impl Predicate<path::Path> for BinaryFilePredicate {
fn eval(&self, path: &path::Path) -> bool {
self.eval(path).unwrap_or(false)
}
}

impl fmt::Display for BinaryFilePredicate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "var is {}", self.path.display())
}
}

/// Creates a new `Predicate` that ensures complete equality
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use predicates::prelude::*;
///
/// let predicate_file = predicate::path::eq_file(Path::new("Cargo.toml"));
/// assert_eq!(true, predicate_file.eval(Path::new("Cargo.toml")));
/// assert_eq!(false, predicate_file.eval(Path::new("src")));
/// assert_eq!(false, predicate_file.eval(Path::new("Cargo.lock")));
/// ```
pub fn eq_file(path: &path::Path) -> BinaryFilePredicate {
let file_content = FileContent::new(path).unwrap();
BinaryFilePredicate {
path: path.to_path_buf(),
file_content,
}
}

impl BinaryFilePredicate {
/// Creates a new `Predicate` that ensures complete equality
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use predicates::prelude::*;
///
/// let predicate_file = predicate::path::eq_file(Path::new("Cargo.toml")).utf8();
/// assert_eq!(true, predicate_file.eval(Path::new("Cargo.toml")));
/// assert_eq!(false, predicate_file.eval(Path::new("Cargo.lock")));
/// assert_eq!(false, predicate_file.eval(Path::new("src")));
/// ```
pub fn utf8(self) -> StrFilePredicate {
StrFilePredicate {
path: self.path,
content: self.file_content.utf8().unwrap(),
}
}
}

/// Predicate that compares string content of files
#[derive(Debug)]
pub struct StrFilePredicate {
path: path::PathBuf,
content: String,
}

impl StrFilePredicate {
fn eval(&self, path: &path::Path) -> Option<bool> {
let content = FileContent::new(path).ok()?.utf8().ok()?;
Some(self.content == content)
}
}

impl fmt::Display for StrFilePredicate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "var is {}", self.path.display())
}
}

impl Predicate<path::Path> for StrFilePredicate {
fn eval(&self, path: &path::Path) -> bool {
self.eval(path).unwrap_or(false)
}
}
26 changes: 23 additions & 3 deletions src/path/ft.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,32 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::path;
use std::fmt;
use std::fs;
use std::io;
use std::path;

use Predicate;

#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq)]
enum FileType {
File,
Dir,
Symlink,
}

impl FileType {
fn new(path: &path::Path) -> io::Result<FileType> {
let file_type = path.metadata()?.file_type();
if file_type.is_dir() {
return Ok(FileType::Dir);
}
if path.is_file() {
return Ok(FileType::File);
}
Ok(FileType::Symlink)
}

fn eval(self, ft: &fs::FileType) -> bool {
match self {
FileType::File => ft.is_file(),
Expand All @@ -43,7 +55,7 @@ impl fmt::Display for FileType {
/// Predicate that checks the `std::fs::FileType`.
///
/// This is created by the `predicate::path::is_file`, `predicate::path::is_dir`, and `predicate::path::is_symlink`.
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct FileTypePredicate {
ft: FileType,
follow: bool,
Expand All @@ -59,6 +71,14 @@ impl FileTypePredicate {
self.follow = yes;
self
}

/// Allow to create an `FileTypePredicate` from a `path`
pub fn from_path(path: &path::Path) -> io::Result<FileTypePredicate> {
Ok(FileTypePredicate {
ft: FileType::new(path)?,
follow: true,
})
}
}

impl Predicate<path::Path> for FileTypePredicate {
Expand Down
2 changes: 2 additions & 0 deletions src/path/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ mod ft;
pub use self::ft::{is_dir, is_file, is_symlink, FileTypePredicate};
mod fc;
pub use self::fc::{FileContentPredicate, PredicateFileContentExt};
mod fs;
pub use self::fs::{eq_file, BinaryFilePredicate, StrFilePredicate};
7 changes: 4 additions & 3 deletions src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@

//! Module that contains the essentials for working with predicates.

pub use core::Predicate;
pub use boolean::PredicateBooleanExt;
pub use boxed::PredicateBoxExt;
pub use core::Predicate;
pub use name::PredicateNameExt;
pub use path::PredicateFileContentExt;
pub use str::PredicateStrExt;
pub use name::PredicateNameExt;

/// Predicate factories
pub mod predicate {
// primitive `Predicate` types
pub use constant::{always, never};
pub use function::function;
pub use ord::{eq, ge, gt, le, lt, ne};
pub use iter::{in_hash, in_iter};
pub use ord::{eq, ge, gt, le, lt, ne};

/// `str` Predicate factories
///
Expand All @@ -41,6 +41,7 @@ pub mod predicate {
///
/// This module contains predicates specific to path handling.
pub mod path {
pub use path::eq_file;
pub use path::{exists, missing};
pub use path::{is_dir, is_file, is_symlink};
}
Expand Down