Replace RandomTempDir with tempdir::Tempdir (#7624)

* Remove GuardedTempResult

* Remove RandomTempPath

* ethcore does not depend on devtools
This commit is contained in:
Marek Kotewicz 2018-01-19 17:32:53 +01:00 committed by GitHub
parent 5859db59c8
commit f43e355254
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 165 additions and 346 deletions

8
Cargo.lock generated
View File

@ -442,7 +442,6 @@ dependencies = [
"ethash 1.9.0",
"ethcore-bloom-journal 0.1.0",
"ethcore-bytes 0.1.0",
"ethcore-devtools 1.9.0",
"ethcore-io 1.9.0",
"ethcore-logger 1.9.0",
"ethcore-miner 1.9.0",
@ -488,6 +487,7 @@ dependencies = [
"stats 0.1.0",
"stop-guard 0.1.0",
"table 0.1.0",
"tempdir 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.38 (registry+https://github.com/rust-lang/crates.io-index)",
"triehash 0.1.0",
"unexpected 0.1.0",
@ -511,9 +511,6 @@ version = "0.1.0"
[[package]]
name = "ethcore-devtools"
version = "1.9.0"
dependencies = [
"rand 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ethcore-io"
@ -1918,7 +1915,6 @@ dependencies = [
"env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore 1.9.0",
"ethcore-bytes 0.1.0",
"ethcore-devtools 1.9.0",
"ethcore-io 1.9.0",
"ethcore-light 1.9.0",
"ethcore-logger 1.9.0",
@ -1971,6 +1967,7 @@ dependencies = [
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"tempdir 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.38 (registry+https://github.com/rust-lang/crates.io-index)",
"toml 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
@ -2161,6 +2158,7 @@ dependencies = [
"serde_derive 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"stats 0.1.0",
"tempdir 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.38 (registry+https://github.com/rust-lang/crates.io-index)",
"tiny-keccak 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"tokio-timer 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",

View File

@ -34,7 +34,6 @@ jsonrpc-core = { git = "https://github.com/paritytech/jsonrpc.git", branch = "pa
ethsync = { path = "sync" }
ethcore = { path = "ethcore" }
ethcore-bytes = { path = "util/bytes" }
ethcore-devtools = { path = "devtools" }
ethcore-io = { path = "util/io" }
ethcore-light = { path = "ethcore/light" }
ethcore-logger = { path = "logger" }
@ -76,6 +75,7 @@ rustc_version = "0.2"
[dev-dependencies]
pretty_assertions = "0.1"
ipnetwork = "0.12.6"
tempdir = "0.3"
[target.'cfg(windows)'.dependencies]
winapi = "0.2"

View File

@ -5,12 +5,3 @@ license = "GPL-3.0"
name = "ethcore-devtools"
version = "1.9.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
rand = "0.3"
[features]
[lib]
path = "src/lib.rs"
test = true

View File

@ -16,9 +16,4 @@
//! dev-tools
extern crate rand;
mod random_path;
pub mod http_client;
pub use random_path::*;

View File

@ -1,148 +0,0 @@
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Random path
use std::path::*;
use std::fs;
use std::env;
use std::ops::{Deref, DerefMut};
use rand::random;
pub struct RandomTempPath {
path: PathBuf,
pub panic_on_drop_failure: bool,
}
pub fn random_filename() -> String {
random_str(8)
}
pub fn random_str(len: usize) -> String {
(0..len).map(|_| ((random::<f32>() * 26.0) as u8 + 97) as char).collect()
}
impl RandomTempPath {
pub fn new() -> RandomTempPath {
let mut dir = env::temp_dir();
dir.push(random_filename());
RandomTempPath {
path: dir.clone(),
panic_on_drop_failure: true,
}
}
pub fn create_dir() -> RandomTempPath {
let mut dir = env::temp_dir();
dir.push(random_filename());
fs::create_dir_all(dir.as_path()).unwrap();
RandomTempPath {
path: dir.clone(),
panic_on_drop_failure: true,
}
}
pub fn as_path(&self) -> &PathBuf {
&self.path
}
pub fn as_str(&self) -> &str {
self.path.to_str().unwrap()
}
pub fn new_in(&self, name: &str) -> String {
let mut path = self.path.clone();
path.push(name);
path.to_str().unwrap().to_owned()
}
}
impl AsRef<Path> for RandomTempPath {
fn as_ref(&self) -> &Path {
self.as_path()
}
}
impl Deref for RandomTempPath {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.as_path()
}
}
impl Drop for RandomTempPath {
fn drop(&mut self) {
if let Err(_) = fs::remove_dir_all(&self) {
if let Err(e) = fs::remove_file(&self) {
if self.panic_on_drop_failure {
panic!("Failed to remove temp directory. Here's what prevented this from happening: ({})", e);
}
}
}
}
}
pub struct GuardedTempResult<T> {
pub result: Option<T>,
pub _temp: RandomTempPath,
}
impl<T> GuardedTempResult<T> {
pub fn reference(&self) -> &T {
self.result.as_ref().unwrap()
}
pub fn reference_mut(&mut self) -> &mut T {
self.result.as_mut().unwrap()
}
pub fn take(&mut self) -> T {
self.result.take().unwrap()
}
}
impl<T> Deref for GuardedTempResult<T> {
type Target = T;
fn deref(&self) -> &T { self.result.as_ref().unwrap() }
}
impl<T> DerefMut for GuardedTempResult<T> {
fn deref_mut(&mut self) -> &mut T { self.result.as_mut().unwrap() }
}
#[test]
fn creates_dir() {
let temp = RandomTempPath::create_dir();
assert!(fs::metadata(temp.as_path()).unwrap().is_dir());
}
#[test]
fn destroys_dir() {
let path_buf = {
let temp = RandomTempPath::create_dir();
assert!(fs::metadata(temp.as_path()).unwrap().is_dir());
let path_buf = temp.as_path().to_path_buf();
path_buf
};
assert!(fs::metadata(&path_buf).is_err());
}
#[test]
fn provides_random() {
let temp = RandomTempPath::create_dir();
assert!(temp.as_path().to_str().is_some());
}

View File

@ -19,7 +19,6 @@ ethcore-bytes = { path = "../util/bytes" }
hashdb = { path = "../util/hashdb" }
memorydb = { path = "../util/memorydb" }
patricia-trie = { path = "../util/patricia_trie" }
ethcore-devtools = { path = "../devtools" }
ethcore-io = { path = "../util/io" }
ethcore-logger = { path = "../logger" }
ethcore-miner = { path = "../miner" }
@ -69,6 +68,7 @@ triehash = { path = "../util/triehash" }
semantic_version = { path = "../util/semantic_version" }
unexpected = { path = "../util/unexpected" }
journaldb = { path = "../util/journaldb" }
tempdir = "0.3"
[dev-dependencies]
native-contracts = { path = "native_contracts", features = ["test_contracts"] }

View File

@ -370,29 +370,29 @@ mod tests {
use account_provider::DappId;
use std::collections::HashMap;
use ethjson::misc::AccountMeta;
use devtools::RandomTempPath;
use tempdir::TempDir;
#[test]
fn should_save_and_reload_address_book() {
let path = RandomTempPath::create_dir();
let mut b = AddressBook::new(&path);
let tempdir = TempDir::new("").unwrap();
let mut b = AddressBook::new(tempdir.path());
b.set_name(1.into(), "One".to_owned());
b.set_meta(1.into(), "{1:1}".to_owned());
let b = AddressBook::new(&path);
let b = AddressBook::new(tempdir.path());
assert_eq!(b.get(), hash_map![1.into() => AccountMeta{name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None}]);
}
#[test]
fn should_remove_address() {
let path = RandomTempPath::create_dir();
let mut b = AddressBook::new(&path);
let tempdir = TempDir::new("").unwrap();
let mut b = AddressBook::new(tempdir.path());
b.set_name(1.into(), "One".to_owned());
b.set_name(2.into(), "Two".to_owned());
b.set_name(3.into(), "Three".to_owned());
b.remove(2.into());
let b = AddressBook::new(&path);
let b = AddressBook::new(tempdir.path());
assert_eq!(b.get(), hash_map![
1.into() => AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None},
3.into() => AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}
@ -402,14 +402,14 @@ mod tests {
#[test]
fn should_save_and_reload_dapps_settings() {
// given
let path = RandomTempPath::create_dir();
let mut b = DappsSettingsStore::new(&path);
let tempdir = TempDir::new("").unwrap();
let mut b = DappsSettingsStore::new(tempdir.path());
// when
b.set_accounts("dappOne".into(), Some(vec![1.into(), 2.into()]));
// then
let b = DappsSettingsStore::new(&path);
let b = DappsSettingsStore::new(tempdir.path());
assert_eq!(b.settings(), hash_map![
"dappOne".into() => DappsSettings {
accounts: Some(vec![1.into(), 2.into()]),
@ -440,8 +440,8 @@ mod tests {
#[test]
fn should_store_dapps_policy() {
// given
let path = RandomTempPath::create_dir();
let mut store = DappsSettingsStore::new(&path);
let tempdir = TempDir::new("").unwrap();
let mut store = DappsSettingsStore::new(tempdir.path());
// Test default policy
assert_eq!(store.policy(), NewDappsPolicy::AllAccounts {
@ -452,7 +452,7 @@ mod tests {
store.set_policy(NewDappsPolicy::Whitelist(vec![1.into(), 2.into()]));
// then
let store = DappsSettingsStore::new(&path);
let store = DappsSettingsStore::new(tempdir.path());
assert_eq!(store.policy.clone(), hash_map![
"default".into() => NewDappsPolicy::Whitelist(vec![1.into(), 2.into()])
]);

View File

@ -31,7 +31,7 @@ use kvdb_rocksdb::{Database, DatabaseConfig};
use bytes::Bytes;
use rlp::*;
use ethkey::{Generator, Random};
use devtools::*;
use tempdir::TempDir;
use transaction::{self, Transaction, LocalizedTransaction, PendingTransaction, SignedTransaction, Action};
use blockchain::TreeRoute;
use client::{
@ -352,15 +352,12 @@ impl TestBlockChainClient {
}
}
pub fn get_temp_state_db() -> GuardedTempResult<StateDB> {
let temp = RandomTempPath::new();
let db = Database::open(&DatabaseConfig::with_columns(NUM_COLUMNS), temp.as_str()).unwrap();
pub fn get_temp_state_db() -> (StateDB, TempDir) {
let tempdir = TempDir::new("").unwrap();
let db = Database::open(&DatabaseConfig::with_columns(NUM_COLUMNS), tempdir.path().to_str().unwrap()).unwrap();
let journal_db = journaldb::new(Arc::new(db), journaldb::Algorithm::EarlyMerge, COL_STATE);
let state_db = StateDB::new(journal_db, 1024 * 1024);
GuardedTempResult {
_temp: temp,
result: Some(state_db)
}
(state_db, tempdir)
}
impl MiningBlockChainClient for TestBlockChainClient {
@ -373,8 +370,8 @@ impl MiningBlockChainClient for TestBlockChainClient {
fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock {
let engine = &*self.spec.engine;
let genesis_header = self.spec.genesis_header();
let mut db_result = get_temp_state_db();
let db = self.spec.ensure_db_good(db_result.take(), &Default::default()).unwrap();
let (state_db, _tempdir) = get_temp_state_db();
let db = self.spec.ensure_db_good(state_db, &Default::default()).unwrap();
let last_hashes = vec![genesis_header.hash()];
let mut open_block = OpenBlock::new(

View File

@ -62,7 +62,6 @@ extern crate common_types as types;
extern crate crypto;
extern crate ethash;
extern crate ethcore_bloom_journal as bloom_journal;
extern crate ethcore_devtools as devtools;
extern crate ethcore_io as io;
extern crate ethcore_bytes as bytes;
extern crate ethcore_logger;
@ -126,6 +125,8 @@ extern crate evm;
#[cfg(feature = "jit" )]
extern crate evmjit;
extern crate tempdir;
pub extern crate ethstore;
pub mod account_provider;

View File

@ -221,28 +221,19 @@ impl IoHandler<ClientIoMessage> for ClientIoHandler {
#[cfg(test)]
mod tests {
use std::{time, thread};
use super::*;
use tests::helpers::*;
use devtools::*;
use client::ClientConfig;
use std::sync::Arc;
use miner::Miner;
use tempdir::TempDir;
#[test]
fn it_can_be_started() {
let temp_path = RandomTempPath::new();
let path = temp_path.as_path().to_owned();
let client_path = {
let mut path = path.to_owned();
path.push("client");
path
};
let snapshot_path = {
let mut path = path.to_owned();
path.push("snapshot");
path
};
let tempdir = TempDir::new("").unwrap();
let client_path = tempdir.path().join("client");
let snapshot_path = tempdir.path().join("snapshot");
let spec = get_test_spec();
let service = ClientService::start(
@ -250,11 +241,11 @@ mod tests {
&spec,
&client_path,
&snapshot_path,
&path,
tempdir.path(),
Arc::new(Miner::with_spec(&spec)),
);
assert!(service.is_ok());
drop(service.unwrap());
::std::thread::park_timeout(::std::time::Duration::from_millis(100));
thread::park_timeout(time::Duration::from_millis(100));
}
}

View File

@ -341,7 +341,7 @@ impl SnapshotReader for LooseReader {
#[cfg(test)]
mod tests {
use devtools::RandomTempPath;
use tempdir::TempDir;
use hash::keccak;
use snapshot::ManifestData;
@ -352,8 +352,9 @@ mod tests {
#[test]
fn packed_write_and_read() {
let path = RandomTempPath::new();
let mut writer = PackedWriter::new(path.as_path()).unwrap();
let tempdir = TempDir::new("").unwrap();
let path = tempdir.path().join("packed");
let mut writer = PackedWriter::new(&path).unwrap();
let mut state_hashes = Vec::new();
let mut block_hashes = Vec::new();
@ -381,7 +382,7 @@ mod tests {
writer.finish(manifest.clone()).unwrap();
let reader = PackedReader::new(path.as_path()).unwrap().unwrap();
let reader = PackedReader::new(&path).unwrap().unwrap();
assert_eq!(reader.manifest(), &manifest);
for hash in manifest.state_hashes.iter().chain(&manifest.block_hashes) {
@ -391,8 +392,8 @@ mod tests {
#[test]
fn loose_write_and_read() {
let path = RandomTempPath::new();
let mut writer = LooseWriter::new(path.as_path().into()).unwrap();
let tempdir = TempDir::new("").unwrap();
let mut writer = LooseWriter::new(tempdir.path().into()).unwrap();
let mut state_hashes = Vec::new();
let mut block_hashes = Vec::new();
@ -420,7 +421,7 @@ mod tests {
writer.finish(manifest.clone()).unwrap();
let reader = LooseReader::new(path.as_path().into()).unwrap();
let reader = LooseReader::new(tempdir.path().into()).unwrap();
assert_eq!(reader.manifest(), &manifest);
for hash in manifest.state_hashes.iter().chain(&manifest.block_hashes) {

View File

@ -623,12 +623,12 @@ mod tests {
use std::sync::Arc;
use service::ClientIoMessage;
use io::{IoService};
use devtools::RandomTempPath;
use tests::helpers::get_test_spec;
use journaldb::Algorithm;
use error::Error;
use snapshot::{ManifestData, RestorationStatus, SnapshotService};
use super::*;
use tempdir::TempDir;
struct NoopDBRestore;
impl DatabaseRestore for NoopDBRestore {
@ -642,11 +642,8 @@ mod tests {
let service = IoService::<ClientIoMessage>::start().unwrap();
let spec = get_test_spec();
let dir = RandomTempPath::new();
let mut dir = dir.as_path().to_owned();
let mut client_db = dir.clone();
dir.push("snapshot");
client_db.push("client");
let tempdir = TempDir::new("").unwrap();
let dir = tempdir.path().join("snapshot");
let snapshot_params = ServiceParams {
engine: spec.engine.clone(),
@ -685,7 +682,7 @@ mod tests {
use kvdb_rocksdb::DatabaseConfig;
let spec = get_test_spec();
let dir = RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let state_hashes: Vec<_> = (0..5).map(|_| H256::random()).collect();
let block_hashes: Vec<_> = (0..5).map(|_| H256::random()).collect();
@ -703,7 +700,7 @@ mod tests {
block_hash: H256::default(),
},
pruning: Algorithm::Archive,
db_path: dir.as_path().to_owned(),
db_path: tempdir.path().to_owned(),
db_config: &db_config,
writer: None,
genesis: &gb,

View File

@ -28,7 +28,7 @@ use engines::EthEngine;
use snapshot::{StateRebuilder};
use snapshot::io::{SnapshotReader, PackedWriter, PackedReader};
use devtools::{RandomTempPath, GuardedTempResult};
use tempdir::TempDir;
use rand::Rng;
use kvdb::{KeyValueDB, DBValue};
@ -137,22 +137,20 @@ pub fn compare_dbs(one: &HashDB, two: &HashDB) {
/// Take a snapshot from the given client into a temporary file.
/// Return a snapshot reader for it.
pub fn snap(client: &Client) -> GuardedTempResult<Box<SnapshotReader>> {
pub fn snap(client: &Client) -> (Box<SnapshotReader>, TempDir) {
use ids::BlockId;
let dir = RandomTempPath::new();
let writer = PackedWriter::new(dir.as_path()).unwrap();
let tempdir = TempDir::new("").unwrap();
let path = tempdir.path().join("file");
let writer = PackedWriter::new(&path).unwrap();
let progress = Default::default();
let hash = client.chain_info().best_block_hash;
client.take_snapshot(writer, BlockId::Hash(hash), &progress).unwrap();
let reader = PackedReader::new(dir.as_path()).unwrap().unwrap();
let reader = PackedReader::new(&path).unwrap().unwrap();
GuardedTempResult {
result: Some(Box::new(reader)),
_temp: dir,
}
(Box::new(reader), tempdir)
}
/// Restore a snapshot into a given database. This will read chunks from the given reader

View File

@ -236,14 +236,14 @@ fn fixed_to_contract_only() {
// 6, 7, 8 prove finality for transition at 6.
// 3 beyond gets us to 11.
assert_eq!(client.chain_info().best_block_number, 11);
let reader = snapshot_helpers::snap(&*client);
let (reader, _tempdir) = snapshot_helpers::snap(&*client);
let new_db = kvdb_memorydb::create(::db::NUM_COLUMNS.unwrap_or(0));
let spec = spec_fixed_to_contract();
// ensure fresh engine's step matches.
for _ in 0..11 { spec.engine.step() }
snapshot_helpers::restore(Arc::new(new_db), &*spec.engine, &**reader, &spec.genesis_block()).unwrap();
snapshot_helpers::restore(Arc::new(new_db), &*spec.engine, &*reader, &spec.genesis_block()).unwrap();
}
#[test]
@ -269,10 +269,10 @@ fn fixed_to_contract_to_contract() {
]);
assert_eq!(client.chain_info().best_block_number, 16);
let reader = snapshot_helpers::snap(&*client);
let (reader, _tempdir) = snapshot_helpers::snap(&*client);
let new_db = kvdb_memorydb::create(::db::NUM_COLUMNS.unwrap_or(0));
let spec = spec_fixed_to_contract();
for _ in 0..16 { spec.engine.step() }
snapshot_helpers::restore(Arc::new(new_db), &*spec.engine, &**reader, &spec.genesis_block()).unwrap();
snapshot_helpers::restore(Arc::new(new_db), &*spec.engine, &*reader, &spec.genesis_block()).unwrap();
}

View File

@ -16,7 +16,9 @@
//! PoW block chunker and rebuilder tests.
use devtools::RandomTempPath;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use tempdir::TempDir;
use error::Error;
use blockchain::generator::{ChainGenerator, ChainIterator, BlockFinalizer};
@ -29,9 +31,6 @@ use snappy;
use kvdb::{KeyValueDB, DBTransaction};
use kvdb_memorydb;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
const SNAPSHOT_MODE: ::snapshot::PowSnapshot = ::snapshot::PowSnapshot { blocks: 30000, max_restore_blocks: 30000 };
fn chunk_and_restore(amount: u64) {
@ -40,9 +39,8 @@ fn chunk_and_restore(amount: u64) {
let genesis = canon_chain.generate(&mut finalizer).unwrap();
let engine = ::spec::Spec::new_test().engine;
let new_path = RandomTempPath::create_dir();
let mut snapshot_path = new_path.as_path().to_owned();
snapshot_path.push("SNAP");
let tempdir = TempDir::new("").unwrap();
let snapshot_path = tempdir.path().join("SNAP");
let old_db = Arc::new(kvdb_memorydb::create(::db::NUM_COLUMNS.unwrap_or(0)));
let bc = BlockChain::new(Default::default(), &genesis, old_db.clone());

View File

@ -18,6 +18,7 @@
use std::sync::Arc;
use tempdir::TempDir;
use client::{BlockChainClient, Client};
use ids::BlockId;
use snapshot::service::{Service, ServiceParams};
@ -25,7 +26,6 @@ use snapshot::{self, ManifestData, SnapshotService};
use spec::Spec;
use tests::helpers::generate_dummy_client_with_spec_and_data;
use devtools::RandomTempPath;
use io::IoChannel;
use kvdb_rocksdb::{Database, DatabaseConfig};
@ -46,12 +46,9 @@ fn restored_is_equivalent() {
let client = generate_dummy_client_with_spec_and_data(Spec::new_null, NUM_BLOCKS, TX_PER, &gas_prices);
let path = RandomTempPath::create_dir();
let mut path = path.as_path().clone();
let mut client_db = path.clone();
client_db.push("client_db");
path.push("snapshot");
let tempdir = TempDir::new("").unwrap();
let client_db = tempdir.path().join("client_db");
let path = tempdir.path().join("snapshot");
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Database::open(&db_config, client_db.to_str().unwrap()).unwrap();
@ -106,20 +103,19 @@ fn restored_is_equivalent() {
#[test]
fn guards_delete_folders() {
let spec = Spec::new_null();
let path = RandomTempPath::create_dir();
let mut path = path.as_path().clone();
let tempdir = TempDir::new("").unwrap();
let service_params = ServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
db_config: DatabaseConfig::with_columns(::db::NUM_COLUMNS),
pruning: ::journaldb::Algorithm::Archive,
channel: IoChannel::disconnected(),
snapshot_root: path.clone(),
snapshot_root: tempdir.path().to_owned(),
db_restore: Arc::new(NoopDBRestore),
};
let service = Service::new(service_params).unwrap();
path.push("restoration");
let path = tempdir.path().join("restoration");
let manifest = ManifestData {
version: 2,

View File

@ -16,6 +16,10 @@
//! State snapshotting tests.
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use hash::{KECCAK_NULL_RLP, keccak};
use basic_account::BasicAccount;
use snapshot::account;
use snapshot::{chunk_state, Error as SnapshotError, Progress, StateRebuilder};
@ -30,11 +34,7 @@ use journaldb::{self, Algorithm};
use kvdb_rocksdb::{Database, DatabaseConfig};
use memorydb::MemoryDB;
use parking_lot::Mutex;
use devtools::RandomTempPath;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use hash::{KECCAK_NULL_RLP, keccak};
use tempdir::TempDir;
#[test]
fn snap_and_restore() {
@ -47,9 +47,8 @@ fn snap_and_restore() {
producer.tick(&mut rng, &mut old_db);
}
let snap_dir = RandomTempPath::create_dir();
let mut snap_file = snap_dir.as_path().to_owned();
snap_file.push("SNAP");
let tempdir = TempDir::new("").unwrap();
let snap_file = tempdir.path().join("SNAP");
let state_root = producer.state_root();
let writer = Mutex::new(PackedWriter::new(&snap_file).unwrap());
@ -65,8 +64,7 @@ fn snap_and_restore() {
block_hash: H256::default(),
}).unwrap();
let mut db_path = snap_dir.as_path().to_owned();
db_path.push("db");
let db_path = tempdir.path().join("db");
let db = {
let new_db = Arc::new(Database::open(&db_cfg, &db_path.to_string_lossy()).unwrap());
let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::OverlayRecent);
@ -131,9 +129,9 @@ fn get_code_from_prev_chunk() {
let chunk1 = make_chunk(acc.clone(), h1);
let chunk2 = make_chunk(acc, h2);
let db_path = RandomTempPath::create_dir();
let tempdir = TempDir::new("").unwrap();
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let new_db = Arc::new(Database::open(&db_cfg, &db_path.to_string_lossy()).unwrap());
let new_db = Arc::new(Database::open(&db_cfg, tempdir.path().to_str().unwrap()).unwrap());
{
let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::OverlayRecent);
@ -160,9 +158,8 @@ fn checks_flag() {
producer.tick(&mut rng, &mut old_db);
}
let snap_dir = RandomTempPath::create_dir();
let mut snap_file = snap_dir.as_path().to_owned();
snap_file.push("SNAP");
let tempdir = TempDir::new("").unwrap();
let snap_file = tempdir.path().join("SNAP");
let state_root = producer.state_root();
let writer = Mutex::new(PackedWriter::new(&snap_file).unwrap());
@ -178,8 +175,8 @@ fn checks_flag() {
block_hash: H256::default(),
}).unwrap();
let mut db_path = snap_dir.as_path().to_owned();
db_path.push("db");
let tempdir = TempDir::new("").unwrap();
let db_path = tempdir.path().join("db");
{
let new_db = Arc::new(Database::open(&db_cfg, &db_path.to_string_lossy()).unwrap());
let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::OverlayRecent);

View File

@ -27,20 +27,20 @@ use tests::helpers::*;
use types::filter::Filter;
use ethereum_types::{U256, Address};
use kvdb_rocksdb::{Database, DatabaseConfig};
use devtools::*;
use miner::Miner;
use spec::Spec;
use views::BlockView;
use ethkey::KeyPair;
use transaction::{PendingTransaction, Transaction, Action, Condition};
use miner::MinerService;
use tempdir::TempDir;
#[test]
fn imports_from_empty() {
let dir = RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let spec = get_test_spec();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, dir.as_path().to_str().unwrap()).unwrap());
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
ClientConfig::default(),
@ -55,10 +55,10 @@ fn imports_from_empty() {
#[test]
fn should_return_registrar() {
let dir = RandomTempPath::new();
let spec = ethereum::new_morden(&dir);
let tempdir = TempDir::new("").unwrap();
let spec = ethereum::new_morden(&tempdir.path().to_owned());
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, dir.as_path().to_str().unwrap()).unwrap());
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
ClientConfig::default(),
@ -85,10 +85,10 @@ fn returns_state_root_basic() {
#[test]
fn imports_good_block() {
let dir = RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let spec = get_test_spec();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, dir.as_path().to_str().unwrap()).unwrap());
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
ClientConfig::default(),
@ -110,10 +110,10 @@ fn imports_good_block() {
#[test]
fn query_none_block() {
let dir = RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let spec = get_test_spec();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, dir.as_path().to_str().unwrap()).unwrap());
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
ClientConfig::default(),
@ -261,11 +261,11 @@ fn can_mine() {
#[test]
fn change_history_size() {
let dir = RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let test_spec = Spec::new_null();
let mut config = ClientConfig::default();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, dir.as_path().to_str().unwrap()).unwrap());
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
config.history = 2;
let address = Address::random();

View File

@ -16,6 +16,7 @@
//! Client tests of tracing
use tempdir::TempDir;
use ethkey::KeyPair;
use hash::keccak;
use block::*;
@ -24,7 +25,6 @@ use io::*;
use spec::*;
use client::*;
use tests::helpers::*;
use devtools::RandomTempPath;
use client::{BlockChainClient, Client, ClientConfig};
use kvdb_rocksdb::{Database, DatabaseConfig};
use std::sync::Arc;
@ -37,7 +37,7 @@ use trace::trace::Action::Reward;
#[test]
fn can_trace_block_and_uncle_reward() {
let dir = RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let spec = Spec::new_test_with_reward();
let engine = &*spec.engine;
@ -45,7 +45,7 @@ fn can_trace_block_and_uncle_reward() {
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let mut client_config = ClientConfig::default();
client_config.tracing.enabled = true;
let client_db = Arc::new(Database::open(&db_config, dir.as_path().to_str().unwrap()).unwrap());
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
client_config,
&spec,

View File

@ -1137,10 +1137,10 @@ impl Configuration {
#[cfg(test)]
mod tests {
use std::io::Write;
use std::fs::{File, create_dir};
use std::fs::File;
use std::str::FromStr;
use devtools::{RandomTempPath};
use tempdir::TempDir;
use ethcore::client::{VMType, BlockId};
use ethcore::miner::MinerOptions;
use miner::transaction_queue::PrioritizationStrategy;
@ -1630,37 +1630,33 @@ mod tests {
#[test]
fn should_parse_dapp_opening() {
// given
let temp = RandomTempPath::new();
let name = temp.file_name().unwrap().to_str().unwrap();
create_dir(temp.as_str().to_owned()).unwrap();
let tempdir = TempDir::new("").unwrap();
// when
let conf0 = parse(&["parity", "dapp", temp.to_str().unwrap()]);
let conf0 = parse(&["parity", "dapp", tempdir.path().to_str().unwrap()]);
// then
assert_eq!(conf0.dapp_to_open(), Ok(Some(name.into())));
assert_eq!(conf0.dapp_to_open(), Ok(Some(tempdir.path().file_name().unwrap().to_str().unwrap().into())));
let extra_dapps = conf0.dapps_config().extra_dapps;
assert_eq!(extra_dapps, vec![temp.to_owned()]);
assert_eq!(extra_dapps, vec![tempdir.path().to_owned()]);
}
#[test]
fn should_not_bail_on_empty_line_in_reserved_peers() {
let temp = RandomTempPath::new();
create_dir(temp.as_str().to_owned()).unwrap();
let filename = temp.as_str().to_owned() + "/peers";
File::create(filename.clone()).unwrap().write_all(b" \n\t\n").unwrap();
let args = vec!["parity", "--reserved-peers", &filename];
let tempdir = TempDir::new("").unwrap();
let filename = tempdir.path().join("peers");
File::create(&filename).unwrap().write_all(b" \n\t\n").unwrap();
let args = vec!["parity", "--reserved-peers", filename.to_str().unwrap()];
let conf = Configuration::parse(&args, None).unwrap();
assert!(conf.init_reserved_nodes().is_ok());
}
#[test]
fn should_ignore_comments_in_reserved_peers() {
let temp = RandomTempPath::new();
create_dir(temp.as_str().to_owned()).unwrap();
let filename = temp.as_str().to_owned() + "/peers_comments";
File::create(filename.clone()).unwrap().write_all(b"# Sample comment\nenode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@172.0.0.1:30303\n").unwrap();
let args = vec!["parity", "--reserved-peers", &filename];
let tempdir = TempDir::new("").unwrap();
let filename = tempdir.path().join("peers_comments");
File::create(&filename).unwrap().write_all(b"# Sample comment\nenode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@172.0.0.1:30303\n").unwrap();
let args = vec!["parity", "--reserved-peers", filename.to_str().unwrap()];
let conf = Configuration::parse(&args, None).unwrap();
let reserved_nodes = conf.init_reserved_nodes();
assert!(reserved_nodes.is_ok());

View File

@ -328,7 +328,7 @@ mod tests {
use std::time::Duration;
use std::fs::File;
use std::io::Write;
use devtools::RandomTempPath;
use tempdir::TempDir;
use ethereum_types::U256;
use ethcore::client::{Mode, BlockId};
use ethcore::miner::PendingSet;
@ -417,15 +417,17 @@ mod tests {
#[test]
fn test_password() {
let path = RandomTempPath::new();
let mut file = File::create(path.as_path()).unwrap();
let tempdir = TempDir::new("").unwrap();
let path = tempdir.path().join("file");
let mut file = File::create(&path).unwrap();
file.write_all(b"a bc ").unwrap();
assert_eq!(password_from_file(path.as_str().into()).unwrap().as_bytes(), b"a bc");
assert_eq!(password_from_file(path.to_str().unwrap().into()).unwrap().as_bytes(), b"a bc");
}
#[test]
fn test_password_multiline() {
let path = RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let path = tempdir.path().join("file");
let mut file = File::create(path.as_path()).unwrap();
file.write_all(br#" password with trailing whitespace
those passwords should be
@ -433,7 +435,7 @@ ignored
but the first password is trimmed
"#).unwrap();
assert_eq!(&password_from_file(path.as_str().into()).unwrap(), "password with trailing whitespace");
assert_eq!(&password_from_file(path.to_str().unwrap().into()).unwrap(), "password with trailing whitespace");
}
#[test]

View File

@ -48,7 +48,6 @@ extern crate toml;
extern crate ethcore;
extern crate ethcore_bytes as bytes;
extern crate ethcore_devtools as devtools;
extern crate ethcore_io as io;
extern crate ethcore_light as light;
extern crate ethcore_logger;
@ -97,6 +96,9 @@ extern crate pretty_assertions;
#[cfg(windows)] extern crate ws2_32;
#[cfg(windows)] extern crate winapi;
#[cfg(test)]
extern crate tempdir;
mod account;
mod blockchain;
mod cache;

View File

@ -23,6 +23,7 @@ semver = "0.6"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
tempdir = "0.3"
time = "0.1"
tiny-keccak = "1.3"
tokio-timer = "0.1"

View File

@ -225,11 +225,10 @@ impl<T: TimeProvider> AuthCodes<T> {
#[cfg(test)]
mod tests {
use devtools;
use std::io::{Read, Write};
use std::{time, fs};
use std::cell::Cell;
use tempdir::TempDir;
use hash::keccak;
use ethereum_types::H256;
@ -303,15 +302,16 @@ mod tests {
#[test]
fn should_read_old_format_from_file() {
// given
let path = devtools::RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let file_path = tempdir.path().join("file");
let code = "23521352asdfasdfadf";
{
let mut file = fs::File::create(&path).unwrap();
let mut file = fs::File::create(&file_path).unwrap();
file.write_all(b"a\n23521352asdfasdfadf\nb\n").unwrap();
}
// when
let mut authcodes = AuthCodes::from_file(&path).unwrap();
let mut authcodes = AuthCodes::from_file(&file_path).unwrap();
let time = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
// then
@ -321,7 +321,8 @@ mod tests {
#[test]
fn should_remove_old_unused_tokens() {
// given
let path = devtools::RandomTempPath::new();
let tempdir = TempDir::new("").unwrap();
let file_path = tempdir.path().join("file");
let code1 = "11111111asdfasdf111";
let code2 = "22222222asdfasdf222";
let code3 = "33333333asdfasdf333";
@ -338,11 +339,11 @@ mod tests {
let new_code = codes.generate_new().unwrap().replace('-', "");
codes.clear_garbage();
codes.to_file(&path).unwrap();
codes.to_file(&file_path).unwrap();
// then
let mut content = String::new();
let mut file = fs::File::open(&path).unwrap();
let mut file = fs::File::open(&file_path).unwrap();
file.read_to_string(&mut content).unwrap();
assert_eq!(content, format!("{};100;10000100\n{};100;100\n{};10000100", code1, code2, new_code));

View File

@ -90,6 +90,8 @@ extern crate macros;
#[cfg(test)]
extern crate kvdb_memorydb;
extern crate tempdir;
pub extern crate jsonrpc_ws_server as ws;
mod authcodes;

View File

@ -15,8 +15,9 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use tempdir::TempDir;
use devtools::RandomTempPath;
use parity_reactor::{EventLoop, TokioRemote};
use authcodes::AuthCodes;
@ -54,18 +55,20 @@ impl<T> Deref for Server<T> {
/// Struct representing authcodes
pub struct GuardedAuthCodes {
authcodes: AuthCodes,
_tempdir: TempDir,
/// The path to the mock authcodes
pub path: RandomTempPath,
pub path: PathBuf,
}
impl GuardedAuthCodes {
pub fn new() -> Self {
let mut path = RandomTempPath::new();
path.panic_on_drop_failure = false;
let tempdir = TempDir::new("").unwrap();
let path = tempdir.path().join("file");
GuardedAuthCodes {
authcodes: AuthCodes::from_file(&path).unwrap(),
path: path,
_tempdir: tempdir,
path,
}
}
}

View File

@ -19,7 +19,7 @@ use std::sync::Arc;
use ethcore::account_provider::{AccountProvider, AccountProviderSettings};
use ethstore::EthStore;
use ethstore::accounts_dir::RootDiskDirectory;
use devtools::RandomTempPath;
use tempdir::TempDir;
use jsonrpc_core::IoHandler;
use v1::{ParityAccounts, ParityAccountsClient};
@ -275,8 +275,8 @@ fn should_be_able_to_remove_address() {
#[test]
fn rpc_parity_new_vault() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
let request = r#"{"jsonrpc": "2.0", "method": "parity_newVault", "params":["vault1", "password1"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
@ -288,8 +288,8 @@ fn rpc_parity_new_vault() {
#[test]
fn rpc_parity_open_vault() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
assert!(tester.accounts.create_vault("vault1", "password1").is_ok());
assert!(tester.accounts.close_vault("vault1").is_ok());
@ -302,8 +302,8 @@ fn rpc_parity_open_vault() {
#[test]
fn rpc_parity_close_vault() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
assert!(tester.accounts.create_vault("vault1", "password1").is_ok());
@ -315,8 +315,8 @@ fn rpc_parity_close_vault() {
#[test]
fn rpc_parity_change_vault_password() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
assert!(tester.accounts.create_vault("vault1", "password1").is_ok());
@ -328,8 +328,8 @@ fn rpc_parity_change_vault_password() {
#[test]
fn rpc_parity_change_vault() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
let (address, _) = tester.accounts.new_account_and_public("root_password").unwrap();
assert!(tester.accounts.create_vault("vault1", "password1").is_ok());
@ -342,8 +342,8 @@ fn rpc_parity_change_vault() {
#[test]
fn rpc_parity_vault_adds_vault_field_to_acount_meta() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
let (address1, _) = tester.accounts.new_account_and_public("root_password1").unwrap();
let uuid1 = tester.accounts.account_meta(address1.clone()).unwrap().uuid.unwrap();
@ -366,8 +366,8 @@ fn rpc_parity_vault_adds_vault_field_to_acount_meta() {
#[test]
fn rpc_parity_list_vaults() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
assert!(tester.accounts.create_vault("vault1", "password1").is_ok());
assert!(tester.accounts.create_vault("vault2", "password2").is_ok());
@ -383,8 +383,8 @@ fn rpc_parity_list_vaults() {
#[test]
fn rpc_parity_list_opened_vaults() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
assert!(tester.accounts.create_vault("vault1", "password1").is_ok());
assert!(tester.accounts.create_vault("vault2", "password2").is_ok());
@ -402,8 +402,8 @@ fn rpc_parity_list_opened_vaults() {
#[test]
fn rpc_parity_get_set_vault_meta() {
let temp_path = RandomTempPath::new();
let tester = setup_with_vaults_support(temp_path.as_str());
let tempdir = TempDir::new("").unwrap();
let tester = setup_with_vaults_support(tempdir.path().to_str().unwrap());
assert!(tester.accounts.create_vault("vault1", "password1").is_ok());

View File

@ -37,7 +37,7 @@ mod tests {
authcodes.to_file(&authcodes.path).unwrap();
let connect = Rpc::connect(&format!("ws://127.0.0.1:{}", port - 1),
authcodes.path.as_path());
&authcodes.path);
let _ = connect.map(|conn| {
assert!(matches!(&conn, &Err(RpcError::WsError(_))));
@ -64,7 +64,7 @@ mod tests {
authcodes.to_file(&authcodes.path).unwrap();
let connect = Rpc::connect(&format!("ws://127.0.0.1:{}", port),
authcodes.path.as_path());
&authcodes.path);
let _ = connect.map(|conn| {
assert!(conn.is_ok())