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

feat: support importing from Postman #179

Merged
merged 3 commits into from
Aug 23, 2023
Merged
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
60 changes: 45 additions & 15 deletions cmd/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ SOFTWARE.
package cmd

import (
"errors"
"fmt"
"os"

Expand All @@ -50,6 +51,7 @@ func createConvertCommand() (c *cobra.Command) {
"The file pattern which try to execute the test cases. Brace expansion is supported, such as: test-suite-{1,2}.yaml")
flags.StringVarP(&opt.converter, "converter", "", "",
fmt.Sprintf("The converter format, supported: %s", util.Keys(converters)))
flags.StringVarP(&opt.source, "source", "", "", "The source format, supported: postman")
flags.StringVarP(&opt.target, "target", "t", "", "The target file path")

_ = c.MarkFlagRequired("pattern")
Expand All @@ -60,11 +62,21 @@ func createConvertCommand() (c *cobra.Command) {
type convertOption struct {
pattern string
converter string
source string
target string
}

func (o *convertOption) preRunE(c *cobra.Command, args []string) (err error) {
o.target = util.EmptyThenDefault(o.target, "sample.jmx")
switch o.source {
case "postman":
o.target = util.EmptyThenDefault(o.target, "sample.yaml")
o.converter = "raw"
case "":
o.target = util.EmptyThenDefault(o.target, "sample.jmx")
default:
err = errors.New("only postman supported")
}

return
}

Expand All @@ -74,23 +86,41 @@ func (o *convertOption) runE(c *cobra.Command, args []string) (err error) {
return
}

var output string
var suites []testing.TestSuite
if suites, err = loader.ListTestSuite(); err == nil {
if len(suites) == 0 {
err = fmt.Errorf("no suites found")
} else {
converter := generator.GetTestSuiteConverter(o.converter)
if converter == nil {
err = fmt.Errorf("no converter found")
} else {
output, err = converter.Convert(&suites[0])
}
var suite *testing.TestSuite
if o.source == "" {
suite, err = getSuiteFromFile(o.pattern)
} else {
suite, err = generator.NewPostmanImporter().ConvertFromFile(o.pattern)
}

if err != nil {
return
}

converter := generator.GetTestSuiteConverter(o.converter)
if converter == nil {
err = fmt.Errorf("no converter found")
} else {
var output string
output, err = converter.Convert(suite)
if output != "" {
err = os.WriteFile(o.target, []byte(output), 0644)
}
}
return
}

if output != "" {
err = os.WriteFile(o.target, []byte(output), 0644)
func getSuiteFromFile(pattern string) (suite *testing.TestSuite, err error) {
loader := testing.NewFileWriter("")
if err = loader.Put(pattern); err == nil {
var suites []testing.TestSuite
if suites, err = loader.ListTestSuite(); err == nil {
if len(suites) > 0 {
suite = &suites[0]
} else {
err = errors.New("no suites found")
}
}
}
return
}
16 changes: 16 additions & 0 deletions cmd/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ SOFTWARE.
package cmd_test

import (
_ "embed"
"io"
"os"
"path"
Expand Down Expand Up @@ -85,4 +86,19 @@ func TestConvert(t *testing.T) {
err := c.Execute()
assert.Error(t, err)
})

t.Run("not supported source format", func(t *testing.T) {
c.SetArgs([]string{"convert", "--source=fake"})
err := c.Execute()
assert.Error(t, err)
})

t.Run("convert from postmant", func(t *testing.T) {
tmpFile := path.Join(os.TempDir(), time.Now().String())
defer os.RemoveAll(tmpFile)

c.SetArgs([]string{"convert", "--source=postman", "--target=", tmpFile, "-p=testdata/postman.json"})
err := c.Execute()
assert.NoError(t, err)
})
}
24 changes: 24 additions & 0 deletions cmd/function_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
/**
MIT License

Copyright (c) 2023 API Testing Authors.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package cmd_test

import (
Expand Down
35 changes: 35 additions & 0 deletions cmd/testdata/postman.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"info": {
"_postman_id": "0da1f6bf-fdbb-46a5-ac46-873564e2259c",
"name": "New Collection",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "6795120",
"_collection_link": "https://www.postman.com/ks-devops/workspace/kubesphere-devops/collection/6795120-0da1f6bf-fdbb-46a5-ac46-873564e2259c?action=share&creator=6795120&source=collection_link"
},
"item": [
{
"name": "New Request",
"protocolProfileBehavior": {
"disableBodyPruning": true
},
"request": {
"method": "GET",
"header": [
{
"key": "key",
"value": "value",
"description": "description",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{}"
},
"url": {
"raw": "http://localhost?key=value"
}
}
}
]
}
87 changes: 85 additions & 2 deletions console/atest-ui/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -137,27 +137,35 @@ function loadStores() {
loadStores()

const dialogVisible = ref(false)
const importDialogVisible = ref(false)
const suiteCreatingLoading = ref(false)
const suiteFormRef = ref<FormInstance>()
const testSuiteForm = reactive({
name: '',
api: '',
store: ''
})
const importSuiteFormRef = ref<FormInstance>()
const importSuiteForm = reactive({
url: '',
store: ''
})

function openTestSuiteCreateDialog() {
dialogVisible.value = true
}

function openTestSuiteImportDialog() {
importDialogVisible.value = true
}

const rules = reactive<FormRules<Suite>>({
name: [{ required: true, message: 'Name is required', trigger: 'blur' }],
store: [{ required: true, message: 'Location is required', trigger: 'blur' }]
})
const submitForm = async (formEl: FormInstance | undefined) => {
if (!formEl) return
console.log(formEl)
await formEl.validate((valid: boolean, fields) => {
console.log(valid, fields)
if (valid) {
suiteCreatingLoading.value = true

Expand All @@ -184,6 +192,40 @@ const submitForm = async (formEl: FormInstance | undefined) => {
})
}

const importSuiteFormRules = reactive<FormRules<Suite>>({
url: [
{ required: true, message: 'URL is required', trigger: 'blur' },
{ type: 'url', message: 'Should be a valid URL value', trigger: 'blur' }
],
store: [{ required: true, message: 'Location is required', trigger: 'blur' }]
})
const importSuiteFormSubmit = async (formEl: FormInstance | undefined) => {
if (!formEl) return
await formEl.validate((valid: boolean, fields) => {
if (valid) {
suiteCreatingLoading.value = true

const requestOptions = {
method: 'POST',
headers: {
'X-Store-Name': importSuiteForm.store
},
body: JSON.stringify({
url: importSuiteForm.url
})
}

fetch('/server.Runner/ImportTestSuite', requestOptions)
.then((response) => response.json())
.then(() => {
loadStores()
importDialogVisible.value = false
formEl.resetFields()
})
}
})
}

const filterText = ref('')
watch(filterText, (val) => {
treeRef.value!.filter(val)
Expand All @@ -209,6 +251,9 @@ const viewName = ref('testcase')
<el-button type="primary" @click="openTestSuiteCreateDialog"
data-intro="Click here to create a new test suite"
test-id="open-new-suite-dialog" :icon="Edit">New</el-button>
<el-button type="primary" @click="openTestSuiteImportDialog"
data-intro="Click here to import from Postman"
test-id="open-import-suite-dialog">Import</el-button>
<el-input v-model="filterText" placeholder="Filter keyword" test-id="search" />

<el-tree
Expand Down Expand Up @@ -292,6 +337,44 @@ const viewName = ref('testcase')
</template>
</el-dialog>

<el-dialog v-model="importDialogVisible" title="Import Test Suite" width="30%" draggable>
<template #footer>
<span class="dialog-footer">
<el-form
:rules="importSuiteFormRules"
:model="importSuiteForm"
ref="importSuiteFormRef"
status-icon label-width="120px">
<el-form-item label="Location" prop="store">
<el-select v-model="importSuiteForm.store" class="m-2"
test-id="suite-import-form-store"
filterable=true
default-first-option=true
placeholder="Storage Location" size="middle">
<el-option
v-for="item in stores"
:key="item.name"
:label="item.name"
:value="item.name"
/>
</el-select>
</el-form-item>
<el-form-item label="URL" prop="url">
<el-input v-model="importSuiteForm.url" test-id="suite-import-form-api" />
</el-form-item>
<el-form-item>
<el-button
type="primary"
@click="importSuiteFormSubmit(importSuiteFormRef)"
test-id="suite-import-submit"
>Import</el-button
>
</el-form-item>
</el-form>
</span>
</template>
</el-dialog>

<TemplateFunctions/>
</template>

Expand Down
Loading