0

我正在使用 chromedp 来测试我的基于 Go 的网站。虽然我已经设法使用它进行了基本的登录测试,但当我尝试退出我刚刚登录的帐户时,我遇到了 CSRF 错误。

这是获取 CSRF 错误的测试函数及其主要助手。httpServerURL是正在运行的实时网络服务器的基本 URL,或者是httptest.Server.URL(无论哪种方式,我都会得到相同的 CSRF 错误):

func TestSignupDuplicate(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    ctx, cancel = chromedp.NewContext(ctx) //   chromedp.WithDebugf(log.Printf),

    defer cancel()

    email := "doubly.headless@example.com"
    password := "asdfasdf"

    signUpWithContext(ctx, t, email, password)

    defer func() {
        if err := userManager.DeleteByEmail(email); err != nil {
            t.Fatal(err)
        }
    }()

    var postSignoutClickLocationGot string
    postSignoutClickLocationExpected := httpServerURL + "/"
    if err := chromedp.Run(ctx,
        chromedp.Click("//button[@class='sign-out-form__button']"),
        chromedp.Sleep(800*time.Millisecond),
        chromedp.Location(&postSignoutClickLocationGot),
    ); err != nil {
        t.Fatal(err)
    }

    if postSignoutClickLocationGot != postSignoutClickLocationExpected {
        t.Logf("Expected to be redirected to <%s> after signing out, but was here instead: <%s>",
            postSignoutClickLocationExpected,
            postSignoutClickLocationGot,
        )
    }

    var location string
    var html string
    if err := chromedp.Run(ctx,
        //chromedp.WaitReady("//footer"),
        chromedp.Location(&location),
        chromedp.InnerHTML("/html", &html),
    ); err != nil {
        t.Fatalf("Had trouble getting debug information: %s", err)
    }

    log.Println(location)
    log.Println(html)

    signUpWithContext(ctx, t, email, password)

    expectedAlertHeading := "E-mail address already in use"
    var gotAlertHeading string

    if err := chromedp.Run(ctx,
        chromedp.Text("//*[@class='alert__heading']", &gotAlertHeading),
    ); err != nil {
        t.Fatalf("couldn’t get alert heading: %s", err)
    }

    if expectedAlertHeading != gotAlertHeading {
        t.Fatalf("Unexpected alert heading. Want: «%s». Got: «%s»", expectedAlertHeading, gotAlertHeading)
    }
}

func signUpWithContext(ctx context.Context, t *testing.T, email, password string) {
    t.Helper()

    if err := chromedp.Run(ctx,
        chromedp.Navigate(httpServerURL+"/signup/"),
        chromedp.WaitVisible("#email", chromedp.ByID),
        chromedp.SendKeys("#email", email, chromedp.ByID),
        chromedp.SendKeys("#password", password, chromedp.ByID),
        chromedp.Submit("//button[@type='submit']"),
    ); err != nil {
        t.Fatal(err)
    }
}

这是它的输出:

Running tool: /usr/local/go/bin/go test -timeout 30s example.com/webdictions -run ^(TestSignupDuplicate)$

2019/07/05 15:26:02 http://127.0.0.1:53464/signout/
2019/07/05 15:26:02 <head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">Forbidden - CSRF token invalid
</pre></body>
--- FAIL: TestSignupDuplicate (3.01s)
    /Users/comatoast/Projects/predictionsweb/main_test.go:150: Expected to be redirected to <http://127.0.0.1:53464/> after signing out, but was here instead: <http://127.0.0.1:53464/signout/>
    /Users/comatoast/Projects/predictionsweb/main_test.go:177: couldn’t get alert heading: context deadline exceeded
FAIL
FAIL    example.com/webdictions 3.073s

奇怪的是,Puppeteer 程序不会像这样出错。最后,无论用户在我开始测试之前是否已经拥有一个帐户,我都没有得到任何 CSRF 错误的屏幕截图:

const puppeteer = require('puppeteer');

(async () => {
    const opts = {
        width: 800,
        height: 600,
        deviceScaleFactor: 2,
    }
    const browser = await puppeteer.launch({defaultViewport: opts});
    const page = await browser.newPage();
    await page.goto('http://www.localhost:3000/');
    await page.click("a[href='/signup/']");
    await page.type('#email', "headless.javascript@example.com");
    await page.type('#password', 'asdfasdf');
    await page.click('[type="submit"]');
    await page.screenshot({path: '1. should be the dashboard after signup.png'});

    await page.click('.sign-out-form__button');
    await page.screenshot({path: '2. should be slash.png'});

    await page.click('a[href="/signup/"]')
    await page.screenshot({path: '3. signup again.png'});

    await page.type('#email', "headless.javascript@example.com");
    await page.type('#password', 'asdfasdf');
    await page.click('[type="submit"]');

    await page.screenshot({path: '4. after second identical signup attempt.png'});

//    await page.screenshot({path: 'screenshot.png'});
    await browser.close();
})();

同样,当我尝试在 Safari 或 Chrome 中注册同一个帐户两次时,我收到一个正常的“此电子邮件地址已在使用”错误,而不是 CSRF 错误。如果有的话,我通过 chromedp 做错了什么?

4

1 回答 1

0

事实证明,在“注册”页面的第二次访问中,我点击了一个一键式“退出”表单chromedp.Submit("//button[@type='submit']")。将路径更改为明确chromedp.Submit("//form[@action='/signup/']//button[@type='submit']")signUpWithContext解决了我单击错误表单的提交按钮的问题。

于 2019-07-10T00:41:25.353 回答