Skip to content

Commit

Permalink
Refactor trigger commands to use fixtures (#244)
Browse files Browse the repository at this point in the history
* Refactor trigger commands to use fixtures

* Clean up webhooks list endpoint from request examples

* Clean up after rebase

* Move webhooks endpoints to a place without circular imports

* Re-enable wsl linter

* Create gen files

* Move fixtures logic to own command/package

* Start refactoring gen code

* Refactor the existing generate logic

* Read from the system file or the prebuilt file

* Fix trigger references
  • Loading branch information
tomer-stripe committed Nov 1, 2019
1 parent df816ab commit a74cad7
Show file tree
Hide file tree
Showing 42 changed files with 1,309 additions and 1,237 deletions.
9 changes: 4 additions & 5 deletions pkg/cmd/samples/fixtures.go → pkg/cmd/fixtures.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package samples
package cmd

import (
"github.com/spf13/afero"
"github.com/spf13/cobra"

"github.com/stripe/stripe-cli/pkg/config"
s "github.com/stripe/stripe-cli/pkg/samples"
"github.com/stripe/stripe-cli/pkg/fixtures"
"github.com/stripe/stripe-cli/pkg/stripe"
"github.com/stripe/stripe-cli/pkg/validators"
"github.com/stripe/stripe-cli/pkg/version"
Expand All @@ -18,8 +18,7 @@ type FixturesCmd struct {
Cfg *config.Config
}

// NewFixturesCmd creates and returns a list command for samples
func NewFixturesCmd(cfg *config.Config) *FixturesCmd {
func newFixturesCmd(cfg *config.Config) *FixturesCmd {
fixturesCmd := &FixturesCmd{
Cfg: cfg,
}
Expand All @@ -43,7 +42,7 @@ func (fc *FixturesCmd) runFixturesCmd(cmd *cobra.Command, args []string) error {
return err
}

fixture, err := s.NewFixture(
fixture, err := fixtures.NewFixture(
afero.NewOsFs(),
apiKey,
stripe.DefaultAPIBaseURL,
Expand Down
9 changes: 1 addition & 8 deletions pkg/cmd/listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,7 @@ func (lc *listenCmd) getEndpointsFromAPI(secretKey string) requests.WebhookEndpo
apiBaseURL = stripe.DefaultAPIBaseURL
}

examples := requests.Examples{
Profile: Config.Profile,
APIVersion: "2019-03-14",
APIKey: secretKey,
APIBaseURL: apiBaseURL,
}

return examples.WebhookEndpointsList()
return requests.WebhookEndpointsList(apiBaseURL, "2019-03-14", secretKey, &Config.Profile)
}

func buildEndpointRoutes(endpoints requests.WebhookEndpointList, forwardURL, forwardConnectURL string, forwardHeaders []string, forwardConnectHeaders []string) []proxy.EndpointRoute {
Expand Down
5 changes: 3 additions & 2 deletions pkg/cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//go:generate go run gen_resources_cmds.go
//go:generate go run gen_events_list.go
//go:generate go run ../gen/gen_resources_cmds.go
//go:generate go run ../gen/gen_events_list.go

package cmd

Expand Down Expand Up @@ -95,6 +95,7 @@ func init() {
rootCmd.AddCommand(newConfigCmd().cmd)
rootCmd.AddCommand(newDeleteCmd().reqs.Cmd)
rootCmd.AddCommand(newFeedbackdCmd().cmd)
rootCmd.AddCommand(newFixturesCmd(&Config).Cmd)
rootCmd.AddCommand(newGetCmd().reqs.Cmd)
rootCmd.AddCommand(newListenCmd().cmd)
rootCmd.AddCommand(newLoginCmd().cmd)
Expand Down
1 change: 0 additions & 1 deletion pkg/cmd/samples.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ func newSamplesCmd() *samplesCmd {
}

samplesCmd.cmd.AddCommand(samples.NewCreateCmd(&Config).Cmd)
samplesCmd.cmd.AddCommand(samples.NewFixturesCmd(&Config).Cmd)
samplesCmd.cmd.AddCommand(samples.NewListCmd().Cmd)

return samplesCmd
Expand Down
108 changes: 19 additions & 89 deletions pkg/cmd/trigger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,87 +3,43 @@ package cmd
import (
"fmt"

"github.com/spf13/afero"
"github.com/spf13/cobra"

"github.com/stripe/stripe-cli/pkg/ansi"
"github.com/stripe/stripe-cli/pkg/requests"
"github.com/stripe/stripe-cli/pkg/fixtures"
"github.com/stripe/stripe-cli/pkg/stripe"
"github.com/stripe/stripe-cli/pkg/validators"
"github.com/stripe/stripe-cli/pkg/version"
)

const apiVersion = "2019-03-14"

type triggerCmd struct {
cmd *cobra.Command

fs afero.Fs
apiBaseURL string
}

func newTriggerCmd() *triggerCmd {
tc := &triggerCmd{}
tc.fs = afero.NewOsFs()
tc.cmd = &cobra.Command{
Use: "trigger <event>",
Args: validators.MaximumNArgs(1),
ValidArgs: []string{
"charge.captured",
"charge.dispute.created",
"charge.failed",
"charge.refunded",
"charge.succeeded",
"checkout.session.completed",
"customer.created",
"customer.deleted",
"customer.updated",
"customer.source.created",
"customer.source.updated",
"customer.subscription.deleted",
"customer.subscription.updated",
"invoice.created",
"invoice.finalized",
"invoice.payment_failed",
"invoice.payment_succeeded",
"invoice.updated",
"payment_intent.created",
"payment_intent.payment_failed",
"payment_intent.succeeded",
"payment_intent.canceled",
"payment_method.attached",
},
Short: "Trigger test webhook events to fire",
Use: "trigger <event>",
Args: validators.MaximumNArgs(1),
ValidArgs: fixtures.EventNames(),
Short: "Trigger test webhook events to fire",
Long: fmt.Sprintf(`%s
Cause a specific webhook event to be created and sent. Webhooks tested through
the trigger command will also create all necessary side-effect events that are
needed to create the triggered event.
%s
charge.captured
charge.dispute.created
charge.failed
charge.refunded
charge.succeeded
checkout.session.completed
customer.created
customer.deleted
customer.updated
customer.source.created
customer.source.updated
customer.subscription.deleted
customer.subscription.updated
invoice.created
invoice.finalized
invoice.payment_failed
invoice.payment_succeeded
invoice.updated
payment_intent.created
payment_intent.payment_failed
payment_intent.succeeded
payment_intent.canceled
payment_method.attached
%s
`,
getBanner(),
ansi.Bold("Supported events:"),
fixtures.EventList(),
),
Example: `stripe trigger payment_intent.created`,
RunE: tc.runTriggerCmd,
Expand All @@ -104,52 +60,26 @@ func (tc *triggerCmd) runTriggerCmd(cmd *cobra.Command, args []string) error {
return err
}

examples := requests.Examples{
Profile: Config.Profile,
APIBaseURL: tc.apiBaseURL,
APIVersion: apiVersion,
APIKey: apiKey,
}

if len(args) == 0 {
cmd.Usage()

return nil
}

event := args[0]
supportedEvents := map[string]interface{}{
"charge.captured": examples.ChargeCaptured,
"charge.dispute.created": examples.ChargeDisputed,
"charge.failed": examples.ChargeFailed,
"charge.refunded": examples.ChargeRefunded,
"charge.succeeded": examples.ChargeSucceeded,
"checkout.session.completed": examples.CheckoutSessionCompleted,
"customer.created": examples.CustomerCreated,
"customer.deleted": examples.CustomerDeleted,
"customer.updated": examples.CustomerUpdated,
"customer.source.created": examples.CustomerSourceCreated,
"customer.source.updated": examples.CustomerSourceUpdated,
"customer.subscription.deleted": examples.CustomerSubscriptionDeleted,
"customer.subscription.updated": examples.CustomerSubscriptionUpdated,
"invoice.created": examples.InvoiceCreated,
"invoice.finalized": examples.InvoiceFinalized,
"invoice.payment_failed": examples.InvoicePaymentFailed,
"invoice.payment_succeeded": examples.InvoicePaymentSucceeded,
"invoice.updated": examples.InvoiceUpdated,
"payment_intent.created": examples.PaymentIntentCreated,
"payment_intent.payment_failed": examples.PaymentIntentFailed,
"payment_intent.succeeded": examples.PaymentIntentSucceeded,
"payment_intent.canceled": examples.PaymentIntentCanceled,
"payment_method.attached": examples.PaymentMethodAttached,
}
supportedEvents := fixtures.SupportedEvents(tc.fs, apiKey)

function, ok := supportedEvents[event]
fixture, ok := supportedEvents[event]
if !ok {
return fmt.Errorf(fmt.Sprintf("event %s is not supported.", event))
exists, _ := afero.Exists(tc.fs, event)
if !exists {
return fmt.Errorf(fmt.Sprintf("event %s is not supported.", event))
}

fixture = fixtures.BuildFromFixture(tc.fs, apiKey, args[0])
}

err = function.(func() error)()
err = fixture.Execute()
if err == nil {
fmt.Println("Trigger succeeded! Check dashboard for event details.")
} else {
Expand Down
29 changes: 25 additions & 4 deletions pkg/samples/fixtures.go → pkg/fixtures/fixtures.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package samples
//go:generate go run vfsgen.go

package fixtures

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
Expand Down Expand Up @@ -57,9 +60,25 @@ func NewFixture(fs afero.Fs, apiKey, baseURL, file string) (*Fixture, error) {
responses: make(map[string]*gojsonq.JSONQ),
}

filedata, err := afero.ReadFile(fxt.Fs, file)
if err != nil {
return nil, err
var filedata []byte

var err error

if _, ok := reverseMap()[file]; ok {
f, err := FS.Open(file)
if err != nil {
return nil, err
}

filedata, err = ioutil.ReadAll(f)
if err != nil {
return nil, err
}
} else {
filedata, err = afero.ReadFile(fxt.Fs, file)
if err != nil {
return nil, err
}
}

err = json.Unmarshal(filedata, &fxt.fixture)
Expand Down Expand Up @@ -195,6 +214,8 @@ func (fxt *Fixture) parseMap(params map[string]interface{}, parent string) []str
data = append(data, fmt.Sprintf("%s=%s", keyname, fxt.parseQuery(v.String())))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
data = append(data, fmt.Sprintf("%s=%v", keyname, v.Int()))
case reflect.Float32, reflect.Float64:
data = append(data, fmt.Sprintf("%s=%v", keyname, v.Float()))
case reflect.Map:
m := value.(map[string]interface{})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package samples
package fixtures

import (
"net/http"
Expand Down
8 changes: 8 additions & 0 deletions pkg/fixtures/fs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
//+build dev

package fixtures

import "net/http"

// FS exports the filesystem
var FS http.FileSystem = http.Dir("../../triggers")
Loading

0 comments on commit a74cad7

Please sign in to comment.