1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Integration test driver for Materialize.

#![warn(missing_docs)]

use std::fs::File;
use std::io::{self, Read};
use std::path::Path;

use anyhow::{anyhow, Context};
use itertools::Itertools;

use ore::display::DisplayExt;

use self::error::{ErrorLocation, PosError};
use self::parser::LineReader;

mod action;
mod error;
mod format;
mod parser;
mod util;

pub use self::action::Config;
pub use self::error::Error;

/// Runs a testdrive script stored in a file.
pub async fn run_file(config: &Config, filename: &Path) -> Result<(), Error> {
    let mut file =
        File::open(filename).with_context(|| format!("opening {}", filename.display()))?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)
        .with_context(|| format!("reading {}", filename.display()))?;
    run_string(config, filename, &contents).await
}

/// Runs a testdrive script from the standard input.
pub async fn run_stdin(config: &Config) -> Result<(), Error> {
    let mut contents = String::new();
    io::stdin()
        .read_to_string(&mut contents)
        .context("reading <stdin>")?;
    run_string(config, Path::new("<stdin>"), &contents).await
}

/// Runs a testdrive script stored in a string.
///
/// The script in `contents` is used verbatim. The provided `filename` is used
/// only as output in error messages and such. No attempt is made to read
/// `filename`.
pub async fn run_string(config: &Config, filename: &Path, contents: &str) -> Result<(), Error> {
    println!("--- {}", filename.display());

    let mut line_reader = LineReader::new(contents);
    run_line_reader(config, &mut line_reader)
        .await
        .map_err(|e| {
            let location = e.pos.map(|pos| {
                let (line, col) = line_reader.line_col(pos);
                ErrorLocation::new(filename, contents, line, col)
            });
            Error::new(e.source, location)
        })
}

async fn run_line_reader(
    config: &Config,
    line_reader: &mut LineReader<'_>,
) -> Result<(), PosError> {
    // TODO(benesch): consider sharing state between files, to avoid
    // reconnections for every file. For now it's nice to not open any
    // connections until after parsing.
    let cmds = parser::parse(line_reader)?;
    let mut cmds_exec = cmds.clone();
    // Extract number of executions
    let mut execution_count = 1;
    if let Some(command) = cmds_exec.iter_mut().find(|el| {
        if let parser::Command::Builtin(c) = &el.command {
            if c.name == "set-execution-count" {
                return true;
            }
        }
        false
    }) {
        if let parser::Command::Builtin(c) = &mut command.command {
            let count = c.args.string("count").unwrap_or_default();
            execution_count = count.parse::<u32>().unwrap_or(1);
        }
    };
    println!("Running test {} time(s) ... ", execution_count);
    for _ in 1..execution_count + 1 {
        println!("Run {} ...", execution_count);
        cmds_exec = cmds.clone();
        let (mut state, state_cleanup) = action::create_state(config).await?;

        let actions = action::build(cmds_exec, &state).await?;

        if config.reset {
            state.reset_materialized().await?;

            for a in actions.iter().rev() {
                let undo = a.action.undo(&mut state);
                undo.await.map_err(|e| PosError::new(e, a.pos))?
            }
        }

        for a in &actions {
            let redo = a.action.redo(&mut state);
            redo.await.map_err(|e| PosError::new(e, a.pos))?;
            if state.skip_rest {
                break;
            }
        }

        if config.reset {
            let mut errors = Vec::new();

            if let Err(e) = state.reset_s3().await {
                errors.push(e);
            }

            if let Err(e) = state.reset_sqs().await {
                errors.push(e);
            }

            if let Err(e) = state.reset_kinesis().await {
                errors.push(e);
            }

            drop(state);
            if let Err(e) = state_cleanup.await {
                errors.push(e);
            }

            if !errors.is_empty() {
                return Err(anyhow!(
                    "cleanup failed: {} errors: {}",
                    errors.len(),
                    errors.into_iter().map(|e| e.to_string_alt()).join("\n"),
                )
                .into());
            }
        }
    }
    Ok(())
}