blob: e4db0389fba9eb1a04de3fe9586f4cd076333024 [file] [log] [blame]
// Copyright 2023 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
use std::path::{Path, PathBuf};
use tempfile::{Builder, TempDir};
use crate::{util::copy_directory, Project, Result};
/// `TestProject` copies a project to a temporary directory for tests
/// which need to write to the project directory.
///
/// The temporary directory is deleted when the `TestProject` is dropped.
pub(crate) struct TestProject {
pub project: Project,
// `TempDir` will be deleted when the `TestProject` is dropped.
project_root: TempDir,
}
impl TestProject {
/// Creates a new `TestProject` from the project at `path`
///
/// # Errors
/// Returns an error if they project can not be copied.
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
let test_project_root = Builder::new().prefix("qg-test-project").tempdir()?;
copy_directory(path, &test_project_root)?;
Ok(Self {
project: Project::load(&test_project_root)?,
project_root: test_project_root,
})
}
/// Returns a `PathBuf` to the file at the relative path `path` within
/// the `TestProject` temporary copy.
#[allow(unused)]
pub fn relative_path(&self, path: impl AsRef<Path>) -> PathBuf {
self.project_root.path().join(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_project() {
let test_project = TestProject::new("./src/test_projects/simple").unwrap();
assert_eq!(test_project.project.name(), "test-qg-project");
}
}