opendal/raw/tests/
utils.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::collections::HashMap;
19use std::env;
20use std::sync::LazyLock;
21
22use crate::*;
23
24/// TEST_RUNTIME is the runtime used for running tests.
25pub static TEST_RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
26    tokio::runtime::Builder::new_multi_thread()
27        .enable_all()
28        .build()
29        .unwrap()
30});
31
32/// Init a service with given scheme.
33///
34/// - Load scheme from `OPENDAL_TEST`
35/// - Construct a new Operator with given root.
36/// - Else, returns a `None` to represent no valid config for operator.
37pub fn init_test_service() -> Result<Option<Operator>> {
38    let _ = dotenvy::dotenv();
39
40    let scheme = if let Ok(v) = env::var("OPENDAL_TEST") {
41        v
42    } else {
43        return Ok(None);
44    };
45
46    let prefix = {
47        let scheme_key = scheme.replace('-', "_");
48        format!("opendal_{scheme_key}_")
49    };
50
51    let mut cfg = env::vars()
52        .filter_map(|(k, v)| {
53            k.to_lowercase()
54                .strip_prefix(&prefix)
55                .map(|k| (k.to_string(), v))
56        })
57        .collect::<HashMap<String, String>>();
58
59    // Use random root unless OPENDAL_DISABLE_RANDOM_ROOT is set to true.
60    let disable_random_root = env::var("OPENDAL_DISABLE_RANDOM_ROOT").unwrap_or_default() == "true";
61    if !disable_random_root {
62        let root = format!(
63            "{}{}/",
64            cfg.get("root").cloned().unwrap_or_else(|| "/".to_string()),
65            uuid::Uuid::new_v4()
66        );
67        cfg.insert("root".to_string(), root);
68    }
69
70    // string-based scheme uses a hyphen ('-') as the connector
71    let scheme = scheme.replace('_', "-");
72    let op = Operator::via_iter(scheme, cfg).expect("must succeed");
73
74    #[cfg(feature = "layers-chaos")]
75    let op = { op.layer(layers::ChaosLayer::new(0.1)) };
76
77    let op = op
78        .layer(layers::LoggingLayer::default())
79        .layer(layers::TimeoutLayer::new())
80        .layer(layers::RetryLayer::new().with_max_times(4));
81
82    Ok(Some(op))
83}