Skip to content
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

Refactor new command #4153

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion cmd/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,10 @@ func getCmdCloud(gs *state.GlobalState) *cobra.Command {
$ {{.}} cloud run script.js

# Run a k6 archive in the Grafana Cloud k6
$ {{.}} cloud run archive.tar`[1:])
$ {{.}} cloud run archive.tar

# Create a new cloud-ready k6 script
$ {{.}} cloud new script.js`[1:])

cloudCmd := &cobra.Command{
Use: "cloud",
Expand All @@ -394,6 +397,7 @@ service. Be sure to run the "k6 cloud login" command prior to authenticate with
cloudCmd.AddCommand(getCmdCloudRun(c))
cloudCmd.AddCommand(getCmdCloudLogin(gs))
cloudCmd.AddCommand(getCmdCloudUpload(c))
cloudCmd.AddCommand(getCmdCloudNew(c))

cloudCmd.Flags().SortFlags = false
cloudCmd.Flags().AddFlagSet(c.flagSet())
Expand Down
97 changes: 97 additions & 0 deletions cmd/cloud_new.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package cmd

import (
"fmt"

templates "go.k6.io/k6/cmd/newtemplates"
"go.k6.io/k6/cmd/state"
"go.k6.io/k6/lib/fsext"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
)

const defaultNewCloudScriptName = "script.js"

type cmdCloudNew struct {
gs *state.GlobalState
overwriteFiles bool
templateType string
projectID string
}

func (c *cmdCloudNew) flagSet() *pflag.FlagSet {
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
flags.SortFlags = false
flags.BoolVarP(&c.overwriteFiles, "force", "f", false, "overwrite existing files")
flags.StringVar(&c.templateType, "template", "minimal", "template type (choices: minimal, protocol, browser)")
flags.StringVar(&c.projectID, "project-id", "", "specify the Grafana Cloud ProjectID for the test")
return flags
}

func (c *cmdCloudNew) run(cmd *cobra.Command, args []string) error {

Check warning on line 32 in cmd/cloud_new.go

View workflow job for this annotation

GitHub Actions / lint

unused-parameter: parameter 'cmd' seems to be unused, consider removing or renaming it as _ (revive)
target := defaultNewCloudScriptName
if len(args) > 0 {
target = args[0]
}

fileExists, err := fsext.Exists(c.gs.FS, target)
if err != nil {
return err
}
if fileExists && !c.overwriteFiles {
return fmt.Errorf("%s already exists. Use the `--force` flag to overwrite", target)
}

fd, err := c.gs.FS.Create(target)
if err != nil {
return err
}
defer fd.Close()

Check failure on line 50 in cmd/cloud_new.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `fd.Close` is not checked (errcheck)

tmpl, err := templates.GetTemplate(c.templateType)
if err != nil {
return err
}

argsStruct := templates.TemplateArgs{
ScriptName: target,
EnableCloud: true,
ProjectID: c.projectID,
}

if err := templates.ExecuteTemplate(fd, tmpl, argsStruct); err != nil {
return err
}

fmt.Fprintf(c.gs.Stdout, "New cloud script created: %s (%s template).\n", target, c.templateType)

Check failure on line 67 in cmd/cloud_new.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `fmt.Fprintf` is not checked (errcheck)
return nil
}

func getCmdCloudNew(cloudCmd *cmdCloud) *cobra.Command {
c := &cmdCloudNew{gs: cloudCmd.gs}

exampleText := getExampleText(cloudCmd.gs, `
# Create a minimal cloud-ready script
$ {{.}} cloud new --template minimal

# Create a protocol-based cloud script with a specific ProjectID
$ {{.}} cloud new --template protocol --project-id my-project-id

# Overwrite an existing file with a browser-based cloud script
$ {{.}} cloud new -f --template browser test.js --project-id my-project-id`[1:])

initCmd := &cobra.Command{
Use: "new [file]",
Short: "Create a new k6 script",
Long: `Create a new cloud-ready k6 script using one of the predefined templates.

By default, the script will be named script.js unless a different name is specified.`,
Example: exampleText,
Args: cobra.MaximumNArgs(1),
RunE: c.run,
}

initCmd.Flags().AddFlagSet(c.flagSet())
return initCmd
}
134 changes: 28 additions & 106 deletions cmd/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,99 +2,31 @@

import (
"fmt"
"path"
"text/template"

"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
templates "go.k6.io/k6/cmd/newtemplates"
"go.k6.io/k6/cmd/state"
"go.k6.io/k6/lib/fsext"
)

const defaultNewScriptName = "script.js"

//nolint:gochecknoglobals
var defaultNewScriptTemplate = template.Must(template.New("new").Parse(`import http from 'k6/http';
import { sleep } from 'k6';

export const options = {
// A number specifying the number of VUs to run concurrently.
vus: 10,
// A string specifying the total duration of the test run.
duration: '30s',

// The following section contains configuration options for execution of this
// test script in Grafana Cloud.
//
// See https://grafana.com/docs/grafana-cloud/k6/get-started/run-cloud-tests-from-the-cli/
// to learn about authoring and running k6 test scripts in Grafana k6 Cloud.
//
// cloud: {
// // The ID of the project to which the test is assigned in the k6 Cloud UI.
// // By default tests are executed in default project.
// projectID: "",
// // The name of the test in the k6 Cloud UI.
// // Test runs with the same name will be grouped.
// name: "{{ .ScriptName }}"
// },

// Uncomment this section to enable the use of Browser API in your tests.
//
// See https://grafana.com/docs/k6/latest/using-k6-browser/running-browser-tests/ to learn more
// about using Browser API in your test scripts.
//
// scenarios: {
// // The scenario name appears in the result summary, tags, and so on.
// // You can give the scenario any name, as long as each name in the script is unique.
// ui: {
// // Executor is a mandatory parameter for browser-based tests.
// // Shared iterations in this case tells k6 to reuse VUs to execute iterations.
// //
// // See https://grafana.com/docs/k6/latest/using-k6/scenarios/executors/ for other executor types.
// executor: 'shared-iterations',
// options: {
// browser: {
// // This is a mandatory parameter that instructs k6 to launch and
// // connect to a chromium-based browser, and use it to run UI-based
// // tests.
// type: 'chromium',
// },
// },
// },
// }
};

// The function that defines VU logic.
//
// See https://grafana.com/docs/k6/latest/examples/get-started-with-k6/ to learn more
// about authoring k6 scripts.
//
export default function() {
http.get('https://test.k6.io');
sleep(1);
}
`))

type initScriptTemplateArgs struct {
ScriptName string
}

// newScriptCmd represents the `k6 new` command
type newScriptCmd struct {
gs *state.GlobalState
overwriteFiles bool
templateType string
}

func (c *newScriptCmd) flagSet() *pflag.FlagSet {
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
flags.SortFlags = false
flags.BoolVarP(&c.overwriteFiles, "force", "f", false, "Overwrite existing files")

flags.BoolVarP(&c.overwriteFiles, "force", "f", false, "overwrite existing files")
flags.StringVar(&c.templateType, "template", "minimal", "template type (choices: minimal, protocol, browser)")
return flags
}

func (c *newScriptCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive
func (c *newScriptCmd) run(cmd *cobra.Command, args []string) error {

Check warning on line 29 in cmd/new.go

View workflow job for this annotation

GitHub Actions / lint

unused-parameter: parameter 'cmd' seems to be unused, consider removing or renaming it as _ (revive)
target := defaultNewScriptName
if len(args) > 0 {
target = args[0]
Expand All @@ -104,64 +36,54 @@
if err != nil {
return err
}

if fileExists && !c.overwriteFiles {
return fmt.Errorf("%s already exists, please use the `--force` flag if you want overwrite it", target)
return fmt.Errorf("%s already exists. Use the `--force` flag to overwrite", target)
}

fd, err := c.gs.FS.Create(target)
if err != nil {
return err
}
defer func() {
_ = fd.Close() // we may think to check the error and log
}()
defer fd.Close()

Check failure on line 47 in cmd/new.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `fd.Close` is not checked (errcheck)

if err := defaultNewScriptTemplate.Execute(fd, initScriptTemplateArgs{
ScriptName: path.Base(target),
}); err != nil {
tmpl, err := templates.GetTemplate(c.templateType)
if err != nil {
return err
}

valueColor := getColor(c.gs.Flags.NoColor || !c.gs.Stdout.IsTTY, color.Bold)
printToStdout(c.gs, fmt.Sprintf(
"Initialized a new k6 test script in %s. You can now execute it by running `%s run %s`.\n",
valueColor.Sprint(target),
c.gs.BinaryName,
target,
))
argsStruct := templates.TemplateArgs{
ScriptName: target,
}

if err := templates.ExecuteTemplate(fd, tmpl, argsStruct); err != nil {
return err
}

fmt.Fprintf(c.gs.Stdout, "New script created: %s (%s template).\n", target, c.templateType)

Check failure on line 62 in cmd/new.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `fmt.Fprintf` is not checked (errcheck)
return nil
}

func getCmdNewScript(gs *state.GlobalState) *cobra.Command {
c := &newScriptCmd{gs: gs}

exampleText := getExampleText(gs, `
# Create a minimal k6 script in the current directory. By default, k6 creates script.js.
{{.}} new

# Create a minimal k6 script in the current directory and store it in test.js
{{.}} new test.js

# Overwrite existing test.js with a minimal k6 script
{{.}} new -f test.js`[1:])
exampleText := getExampleText(c.gs, `
# Create a minimal k6 script
$ {{.}} new --template minimal

# Overwrite an existing file with a protocol-based script
$ {{.}} new -f --template protocol test.js`[1:])

initCmd := &cobra.Command{
Use: "new",
Short: "Create and initialize a new k6 script",
Long: `Create and initialize a new k6 script.

This command will create a minimal k6 script in the current directory and
store it in the file specified by the first argument. If no argument is
provided, the script will be stored in script.js.
Use: "new [file]",
Short: "Create a new k6 script",
Long: `Create a new k6 script using one of the predefined templates.

This command will not overwrite existing files.`,
By default, the script will be named script.js unless a different name is specified.`,
Example: exampleText,
Args: cobra.MaximumNArgs(1),
RunE: c.run,
}
initCmd.Flags().AddFlagSet(c.flagSet())

initCmd.Flags().AddFlagSet(c.flagSet())
return initCmd
}
2 changes: 0 additions & 2 deletions cmd/new_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -56,7 +55,6 @@ func TestNewScriptCmd(t *testing.T) {

jsData := string(data)
assert.Contains(t, jsData, "export const options = {")
assert.Contains(t, jsData, fmt.Sprintf(`name: "%s"`, testCase.expectedCloudName))
assert.Contains(t, jsData, "export default function() {")
})
}
Expand Down
54 changes: 54 additions & 0 deletions cmd/newtemplates/browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { browser } from "k6/browser";
import http from "k6/http";
import { sleep, check } from 'k6';

const BASE_URL = __ENV.BASE_URL || "https://quickpizza.grafana.com";

export const options = {
scenarios: {
ui: {
executor: "shared-iterations",
options: {
browser: {
type: "chromium",
},
},
},
}, {{ if .EnableCloud }}
cloud: { {{ if .ProjectID }}
projectID: {{ .ProjectID }}, {{ else }}
// projectID: 12345, // Replace this with your own projectID {{ end }}
name: "{{ .ScriptName }}",
}, {{ end }}
};

export function setup() {
let res = http.get(BASE_URL);
if (res.status !== 200) {
throw new Error(
`Got unexpected status code ${res.status} when trying to setup. Exiting.`
);
}
}

export default async function() {
let checkData;
const page = await browser.newPage();
try {
await page.goto(BASE_URL);
checkData = await page.locator("h1").textContent();
check(page, {
header: checkData === "Looking to break out of your pizza routine?",
});
await page.locator('//button[. = "Pizza, Please!"]').click();
await page.waitForTimeout(500);
await page.screenshot({ path: "screenshot.png" });
checkData = await page.locator("div#recommendations").textContent();
check(page, {
recommendation: checkData !== "",
});
} finally {
await page.close();
}
sleep(1);
}
Loading
Loading