jjzjj

go - chromedp 收到无效的 CSRF token 错误; Puppeteer 和浏览器都可以

coder 2024-07-08 原文

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

这是获取 CSRF 错误的测试函数及其主要助手。 httpServerURL 是正在运行的实时网络服务器或 httptest.Server.URL 的基本 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 做错了什么(如果有的话)?

最佳答案

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

关于go - chromedp 收到无效的 CSRF token 错误; Puppeteer 和浏览器都可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56909878/

有关go - chromedp 收到无效的 CSRF token 错误; Puppeteer 和浏览器都可以的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  3. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  4. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  5. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  6. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  7. ruby - 是否可以覆盖 gemfile 进行本地开发? - 2

    我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI

  8. ruby - 我可以将我的 README.textile 以正确的格式放入我的 RDoc 中吗? - 2

    我喜欢使用Textile或Markdown为我的项目编写自述文件,但是当我生成RDoc时,自述文件被解释为RDoc并且看起来非常糟糕。有没有办法让RDoc通过RedCloth或BlueCloth而不是它自己的格式化程序运行文件?它可以配置为自动检测文件后缀的格式吗?(例如README.textile通过RedCloth运行,但README.mdown通过BlueCloth运行) 最佳答案 使用YARD直接代替RDoc将允许您包含Textile或Markdown文件,只要它们的文件后缀是合理的。我经常使用类似于以下Rake任务的东西:

  9. ruby - 一个 YAML 对象可以引用另一个吗? - 2

    我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的ruby​​yaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir

  10. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

随机推荐