Select Git revision
step.go 2.00 KiB
package http
import (
"context"
"encoding/base64"
"fmt"
"log"
"git.autistici.org/ai3/tools/service-prober/common/jsontypes"
)
type BasicAuth struct {
Username string `json:"username"`
Password string `json:"password"`
}
// A Step in a script, a series of HTTP transactions whose results we can
// verify somehow (right now just by needle-in-haystack string matching).
type Step struct {
Name string `json:"name"`
Type string `json:"type"`
URL string `json:"url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
FormValues map[string]string `json:"form_values"`
BasicAuth *BasicAuth `json:"basic_auth"`
Selector string `json:"selector"`
ExpectedURL jsontypes.Regexp `json:"expected_url"`
ExpectedData jsontypes.Regexp `json:"expected_data"`
}
func CheckStep(ctx context.Context, b *Browser, step *Step, debug *log.Logger) error {
var resp *Response
var err error
switch step.Type {
case "open":
method := step.Method
if method == "" {
method = "GET"
}
hdrs := step.Headers
if step.BasicAuth != nil && step.BasicAuth.Username != "" {
if hdrs == nil {
hdrs = make(map[string]string)
}
auth := base64.StdEncoding.EncodeToString([]byte(
step.BasicAuth.Username + ":" + step.BasicAuth.Password))
hdrs["Authorization"] = "Basic " + auth
}
resp, err = b.Open(ctx, method, step.URL, &RequestOptions{Headers: hdrs})
case "click":
resp, err = b.Click(ctx, step.Selector)
case "submit":
resp, err = b.SubmitForm(ctx, step.Selector, step.FormValues)
}
if err != nil {
return err
}
if step.ExpectedURL.IsSet() && !step.ExpectedURL.MatchString(resp.URL.String()) {
return fmt.Errorf("expected URL %s, got %s instead", step.ExpectedURL.String(), resp.URL.String())
}
if step.ExpectedData.IsSet() && !step.ExpectedData.MatchString(resp.Body) {
return fmt.Errorf("page body at %s does not match expected regexp %s", resp.URL.String(), step.ExpectedData.String())
}
return nil
}