Replace test implementations with mockall #29

Merged
wojtek merged 2 commits from 27---replace-test-implementations-with-mockall into main 2023-04-12 20:55:41 +02:00
Showing only changes of commit 5efc3ab0c5 - Show all commits

View File

@ -6,9 +6,13 @@ use std::path::{Path, PathBuf};
use serde::de::DeserializeOwned;
use serde::Serialize;
#[cfg(test)]
use mockall::automock;
use super::{Database, DatabaseRead, DatabaseWrite};
/// Trait for the JSON database backend.
#[cfg_attr(test, automock)]
pub trait JsonDatabaseBackend {
/// Read the JSON string from the backend.
fn read(&self) -> Result<String, std::io::Error>;
@ -81,25 +85,12 @@ impl JsonDatabaseBackend for JsonDatabaseFileBackend {
#[cfg(test)]
mod tests {
use mockall::predicate;
use super::*;
use crate::{tests::COLLECTION, Artist, TrackFormat};
struct JsonDatabaseTestBackend {
json: String,
}
impl JsonDatabaseBackend for JsonDatabaseTestBackend {
fn read(&self) -> Result<String, std::io::Error> {
Ok(self.json.clone())
}
fn write(&mut self, json: &str) -> Result<(), std::io::Error> {
assert_eq!(json, self.json);
Ok(())
}
}
fn artist_to_json(artist: &Artist) -> String {
let album_artist = &artist.id.name;
@ -167,9 +158,14 @@ mod tests {
#[test]
fn write() {
let write_data = COLLECTION.to_owned();
let backend = JsonDatabaseTestBackend {
json: artists_to_json(&write_data),
};
let input = artists_to_json(&write_data);
let mut backend = MockJsonDatabaseBackend::new();
backend
.expect_write()
.with(predicate::eq(input))
.times(1)
.return_once(|_| Ok(()));
JsonDatabase::new(Box::new(backend))
.write(&write_data)
@ -179,9 +175,10 @@ mod tests {
#[test]
fn read() {
let expected = COLLECTION.to_owned();
let backend = JsonDatabaseTestBackend {
json: artists_to_json(&expected),
};
let result = Ok(artists_to_json(&expected));
let mut backend = MockJsonDatabaseBackend::new();
backend.expect_read().times(1).return_once(|| result);
let mut read_data: Vec<Artist> = vec![];
JsonDatabase::new(Box::new(backend))
@ -194,9 +191,17 @@ mod tests {
#[test]
fn reverse() {
let expected = COLLECTION.to_owned();
let backend = JsonDatabaseTestBackend {
json: artists_to_json(&expected),
};
let input = artists_to_json(&expected);
let result = Ok(input.clone());
let mut backend = MockJsonDatabaseBackend::new();
backend
.expect_write()
.with(predicate::eq(input))
.times(1)
.return_once(|_| Ok(()));
backend.expect_read().times(1).return_once(|| result);
let mut database = JsonDatabase::new(Box::new(backend));
let write_data = COLLECTION.to_owned();