Skip to content

Commit 30c4e6a

Browse files
authored
feat: add integration tests for basic and gate definition formatting (#5)
1 parent 6e92abb commit 30c4e6a

File tree

6 files changed

+71
-8
lines changed

6 files changed

+71
-8
lines changed

src/format.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,11 @@ pub fn format_source(source: &str, config: &FormatConfig) -> Result<String, Form
4040
}
4141

4242
fn format_file(ctx: &FormatContext, file: &ast::SourceFile) -> Doc {
43-
let mut docs = Vec::new();
44-
45-
for stmt in file.statements() {
46-
docs.push(format_stmt(ctx, stmt));
47-
docs.push(Doc::hardline());
48-
}
49-
50-
Doc::concat(docs)
43+
let stmts: Vec<Doc> = file
44+
.statements()
45+
.map(|stmt| format_stmt(ctx, stmt))
46+
.collect();
47+
join(stmts, Doc::hardline())
5148
}
5249

5350
fn format_stmt(ctx: &FormatContext, stmt: ast::Stmt) -> Doc {

tests/fixtures/basic/input.qasm

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
OPENQASM 3.0;
2+
include "stdgates.inc";
3+
4+
qubit[2] q;
5+
bit[2] c;
6+
7+
h q[0];
8+
cx q[0],q[1];
9+
10+
c = measure q;

tests/fixtures/basic/output.qasm

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
OPENQASM 3.0;
2+
include "stdgates.inc";
3+
qubit[2] q;
4+
bit[2] c;
5+
h q[0];
6+
cx q[0], q[1];
7+
c = measure q;

tests/fixtures/gate_def/input.qasm

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
gate mygate(theta) q {
2+
rz(theta) q;
3+
x q;
4+
}
5+
6+
gate cx a,b{
7+
ctrl @ x a,b;
8+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
gate mygate(theta) q {
2+
rz(theta) q;
3+
x q;
4+
}
5+
gate cx a,b {
6+
ctrl @ x a,b;
7+
}

tests/golden.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
use std::fs;
2+
use std::path::Path;
3+
4+
use qasmfmt::format;
5+
6+
fn run_test(name: &str) {
7+
let testdata = Path::new(env!("CARGO_MANIFEST_DIR"))
8+
.join("tests/fixtures")
9+
.join(name);
10+
11+
let input = fs::read_to_string(testdata.join("input.qasm"))
12+
.unwrap_or_else(|e| panic!("{}/input.qasm: {}", name, e));
13+
let expected = fs::read_to_string(testdata.join("output.qasm"))
14+
.unwrap_or_else(|e| panic!("{}/output.qasm: {}", name, e));
15+
16+
let actual = format(&input).unwrap_or_else(|e| panic!("{}: {}", name, e));
17+
18+
if actual != expected {
19+
panic!(
20+
"\n\n=== {} ===\n\nExpected:\n{}\n\nActual:\n{}\n",
21+
name, expected, actual
22+
);
23+
}
24+
}
25+
26+
#[test]
27+
fn test_basic() {
28+
run_test("basic");
29+
}
30+
31+
#[test]
32+
fn test_gate_def() {
33+
run_test("gate_def");
34+
}

0 commit comments

Comments
 (0)