Repository navigation
Add golden output snapshots and one version source #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "testing" | ||
|
|
||
| "github.com/be-thomas/openiac/internal/buildinfo" | ||
| ) | ||
|
|
||
| func TestVersionCommand(t *testing.T) { | ||
| for _, arg := range []string{"version", "--version", "-v"} { | ||
| var stdout, stderr bytes.Buffer | ||
| if code := run([]string{arg}, &stdout, &stderr); code != 0 { | ||
| t.Fatalf("%s: exit code %d, want 0 (stderr %q)", arg, code, stderr.String()) | ||
| } | ||
| want := "openiac " + buildinfo.Version + "\n" | ||
| if stdout.String() != want { | ||
| t.Errorf("%s: stdout = %q, want %q", arg, stdout.String(), want) | ||
| } | ||
| if stderr.Len() != 0 { | ||
| t.Errorf("%s: stderr = %q, want empty", arg, stderr.String()) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| 0.1.0-dev |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| // Package buildinfo reports the OpenIaC release version. | ||
| package buildinfo | ||
|
|
||
| import ( | ||
| _ "embed" | ||
| "strings" | ||
| ) | ||
|
|
||
| // raw holds the VERSION file that sits next to this package. Keeping the | ||
| // version in a file rather than in a constant means the CLI, the Makefile and | ||
| // a plain `go build` all read the same value. | ||
| // | ||
| //go:embed VERSION | ||
| var raw string | ||
|
|
||
| // Version is the release version, for example "0.1.0". A development build | ||
| // reports a "-dev" suffix. | ||
| var Version = strings.TrimSpace(raw) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package buildinfo_test | ||
|
|
||
| import ( | ||
| "regexp" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/be-thomas/openiac/internal/buildinfo" | ||
| ) | ||
|
|
||
| func TestVersion(t *testing.T) { | ||
| if buildinfo.Version != strings.TrimSpace(buildinfo.Version) { | ||
| t.Fatalf("Version = %q, want no surrounding whitespace", buildinfo.Version) | ||
| } | ||
| // MAJOR.MINOR.PATCH, optionally followed by a pre-release suffix. | ||
| pattern := regexp.MustCompile(`^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$`) | ||
| if !pattern.MatchString(buildinfo.Version) { | ||
| t.Fatalf("Version = %q, want MAJOR.MINOR.PATCH", buildinfo.Version) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| package engine_test | ||
|
|
||
| import ( | ||
| "flag" | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
| "runtime" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/be-thomas/openiac/pkg/emitters" | ||
| "github.com/be-thomas/openiac/pkg/engine" | ||
| ) | ||
|
|
||
| // update rewrites the golden files instead of comparing against them: | ||
| // | ||
| // go test ./pkg/engine -run TestGolden -update | ||
| var update = flag.Bool("update", false, "rewrite golden files") | ||
|
|
||
| // goldenTargets is the pair of emitters every snapshot covers. | ||
| var goldenTargets = []engine.Target{engine.TargetCDK, engine.TargetPulumi} | ||
|
|
||
| // TestGoldenAwsWebApp snapshots the documented example in both targets. It is | ||
| // the regression guard for emitter output: any change to generated TypeScript | ||
| // has to be visible here. | ||
| func TestGoldenAwsWebApp(t *testing.T) { | ||
| snapshot(t, "aws-web-app", filepath.Join("examples", "aws-web-app"), false) | ||
| } | ||
|
|
||
| // TestGoldenWarned snapshots a module the targets cannot fully convert, so the | ||
| // warning section of the snapshots is exercised. Without it a warning-free | ||
| // fixture would leave the section empty in every golden file and changes to | ||
| // warning collection would go unnoticed. | ||
| func TestGoldenWarned(t *testing.T) { | ||
| snapshot(t, "warned", filepath.Join("pkg", "engine", "testdata", "fixtures", "warned"), true) | ||
| } | ||
|
|
||
| // snapshot converts a fixture in both targets and compares each result with | ||
| // its committed golden file. wantWarnings fails the test unless every target | ||
| // reports at least one warning, so a fixture added for that purpose cannot | ||
| // decay into a copy of the warning-free case. | ||
| func snapshot(t *testing.T, name, dir string, wantWarnings bool) { | ||
| t.Helper() | ||
|
|
||
| // The generated "// Source:" comment carries the path the parser was given, | ||
| // so the test runs from the repository root to keep the snapshot portable. | ||
| t.Chdir(repoRoot(t)) | ||
|
|
||
| graph, err := engine.Parse(dir) | ||
| if err != nil { | ||
| t.Fatalf("Parse: %v", err) | ||
| } | ||
|
|
||
| results, err := engine.Convert(graph, goldenTargets, emitters.Options{ | ||
| StackName: "OpenIacStack", | ||
| ProjectName: "openiac", | ||
| }) | ||
| if err != nil { | ||
| t.Fatalf("Convert: %v", err) | ||
| } | ||
| if len(results) != len(goldenTargets) { | ||
| t.Fatalf("results = %d, want %d", len(results), len(goldenTargets)) | ||
| } | ||
|
|
||
| for _, result := range results { | ||
| if wantWarnings && len(result.Warnings) == 0 { | ||
| t.Errorf("%s: warnings = 0, want at least one", result.Target) | ||
| } | ||
| path := filepath.Join("pkg", "engine", "testdata", "golden", name+"."+string(result.Target)+".txt") | ||
| checkGolden(t, path, renderResult(result)) | ||
| } | ||
| } | ||
|
|
||
| // repoRoot finds the module root, so the snapshots do not depend on the | ||
| // directory the test binary was started from: `go test` starts in pkg/engine, | ||
| // but a prebuilt binary or a debugger can start anywhere. | ||
| func repoRoot(t *testing.T) string { | ||
| t.Helper() | ||
| if _, file, _, ok := runtime.Caller(0); ok { | ||
| if root, ok := moduleRoot(filepath.Dir(file)); ok { | ||
| return root | ||
| } | ||
| } | ||
| wd, err := os.Getwd() | ||
| if err != nil { | ||
| t.Fatalf("working directory: %v", err) | ||
| } | ||
| if root, ok := moduleRoot(wd); ok { | ||
| return root | ||
| } | ||
| t.Fatalf("cannot find go.mod above %s", wd) | ||
| return "" | ||
| } | ||
|
|
||
| // moduleRoot walks up from dir until it finds a go.mod. | ||
| func moduleRoot(dir string) (string, bool) { | ||
| for { | ||
| if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { | ||
| return dir, true | ||
| } | ||
| parent := filepath.Dir(dir) | ||
| if parent == dir { | ||
| return "", false | ||
| } | ||
| dir = parent | ||
| } | ||
| } | ||
|
|
||
| // renderResult turns a target result into the text that is snapshotted: each | ||
| // generated file under a header, then every warning in order. | ||
| func renderResult(result engine.TargetResult) string { | ||
| var b strings.Builder | ||
| for i, file := range result.Files { | ||
| if i > 0 { | ||
| b.WriteString("\n") | ||
| } | ||
| fmt.Fprintf(&b, "// ==== %s ====\n", file.Path) | ||
| b.WriteString(file.Content) | ||
| if !strings.HasSuffix(file.Content, "\n") { | ||
| b.WriteString("\n") | ||
| } | ||
| } | ||
| b.WriteString("\n// ==== warnings ====\n") | ||
| for _, warning := range result.Warnings { | ||
| fmt.Fprintf(&b, "// %s\n", warning) | ||
| } | ||
| return b.String() | ||
| } | ||
|
|
||
| func checkGolden(t *testing.T, path, got string) { | ||
| t.Helper() | ||
| if *update { | ||
| if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { | ||
| t.Fatalf("create golden directory: %v", err) | ||
| } | ||
| if err := os.WriteFile(path, []byte(got), 0o644); err != nil { | ||
| t.Fatalf("write %s: %v", path, err) | ||
| } | ||
| return | ||
| } | ||
|
|
||
| want, err := os.ReadFile(path) | ||
| if err != nil { | ||
| t.Fatalf("read %s: %v (run with -update to create it)", path, err) | ||
| } | ||
| if string(want) != got { | ||
| t.Errorf("%s is stale; run `go test ./pkg/engine -run TestGolden -update`\n--- want\n%s\n--- got\n%s", | ||
| path, want, got) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| terraform { | ||
| required_version = ">= 1.0" | ||
|
|
||
| backend "s3" { | ||
| bucket = "openiac-state" | ||
| key = "warned.tfstate" | ||
| region = "us-east-1" | ||
| } | ||
| } | ||
|
|
||
| # A moved block is valid Terraform 1.1+ but has no target equivalent, so the | ||
| # emitters keep it out of the generated code and report it as a warning. This | ||
| # fixture exists so the golden snapshots exercise the warning section. | ||
| moved { | ||
| from = aws_s3_bucket.old | ||
| to = aws_s3_bucket.assets | ||
| } | ||
|
|
||
| resource "aws_s3_bucket" "assets" { | ||
| bucket = "openiac-warned-assets" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| // ==== index.ts ==== | ||
| // Generated by OpenIaC. Review this file before deploying. | ||
| // Source: examples/aws-web-app/main.tf | ||
| import * as cdk from 'aws-cdk-lib'; | ||
| import * as ec2 from 'aws-cdk-lib/aws-ec2'; | ||
| import * as s3 from 'aws-cdk-lib/aws-s3'; | ||
| import * as sqs from 'aws-cdk-lib/aws-sqs'; | ||
| import { Construct } from 'constructs'; | ||
|
|
||
| export interface OpenIacStackProps extends cdk.StackProps {} | ||
|
|
||
| export class OpenIacStack extends cdk.Stack { | ||
| constructor(scope: Construct, id: string, props: OpenIacStackProps = {}) { | ||
| super(scope, id, props); | ||
|
|
||
| // var.region | ||
| const region = this.node.tryGetContext("region") ?? "us-east-1"; | ||
| // var.environment | ||
| const environment = this.node.tryGetContext("environment") ?? "dev"; | ||
|
|
||
| // aws_s3_bucket.assets | ||
| const assetsS3Bucket = new s3.Bucket(this, "aws_s3_bucket.assets", { | ||
| bucketName: `openiac-assets-${environment}`, | ||
| tags: {"Environment": environment}, | ||
| }); | ||
| // aws_sqs_queue.jobs | ||
| const jobsSqsQueue = new sqs.CfnQueue(this, "aws_sqs_queue.jobs", { | ||
| MessageRetentionPeriod: 1209600, | ||
| QueueName: "openiac-jobs", | ||
| VisibilityTimeout: 300, | ||
| }); | ||
| // aws_vpc.main | ||
| const mainVpc = new ec2.CfnVPC(this, "aws_vpc.main", { | ||
| CidrBlock: "10.0.0.0/16", | ||
| EnableDnsHostnames: true, | ||
| EnableDnsSupport: true, | ||
| Tags: [{ Key: "Environment", Value: environment }, { Key: "Name", Value: `openiac-${environment}` }], | ||
| }); | ||
| // aws_security_group.web | ||
| const webSecurityGroup = new ec2.CfnSecurityGroup(this, "aws_security_group.web", { | ||
| GroupDescription: "Allow HTTP from anywhere", | ||
| GroupName: "openiac-web", | ||
| Tags: [{ Key: "Name", Value: "openiac-web" }], | ||
| VpcId: mainVpc.ref, | ||
| SecurityGroupEgress: [{ CidrIp: "0.0.0.0/0", FromPort: 0, IpProtocol: "-1", ToPort: 0 }], | ||
| SecurityGroupIngress: [{ CidrIp: "0.0.0.0/0", FromPort: 80, IpProtocol: "tcp", ToPort: 80 }], | ||
| }); | ||
| // aws_subnet.public | ||
| const publicSubnet = new ec2.CfnSubnet(this, "aws_subnet.public", { | ||
| AvailabilityZone: `${region}a`, | ||
| CidrBlock: "10.0.1.0/24", | ||
| MapPublicIpOnLaunch: true, | ||
| Tags: [{ Key: "Name", Value: "openiac-public" }], | ||
| VpcId: mainVpc.ref, | ||
| }); | ||
| // aws_instance.web | ||
| const webInstance = new ec2.CfnInstance(this, "aws_instance.web", { | ||
| ImageId: "ami-0123456789abcdef0", | ||
| InstanceType: "t3.micro", | ||
| SubnetId: publicSubnet.ref, | ||
| Tags: [{ Key: "Name", Value: "openiac-web" }], | ||
| SecurityGroupIds: [webSecurityGroup.attrGroupId], | ||
| }); | ||
|
|
||
| // output.bucket_arn | ||
| new cdk.CfnOutput(this, "bucket_arn", { value: assetsS3Bucket.bucketArn }); | ||
| // output.instance_ip | ||
| new cdk.CfnOutput(this, "instance_ip", { value: webInstance.attrPublicIp }); | ||
|
|
||
| } | ||
| } | ||
|
|
||
| // ==== warnings ==== |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.