如何在 playframework 中设置数据库/夹具以进行功能测试

2023-12-09

我正在尝试测试我的控制器 - Secure.java。我使用 play 的 Fixtures 类来设置数据库。不幸的是,当发出 POST 调用并调用控件的方法时,数据库结果为空。但是,在测试方法中,我可以按预期检索数据。

The routes

POST    /login                                      user.Secure.authenticate

控制器安全.java:

package controllers.user;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Date;
import java.util.TimeZone;

import models.User;
import play.Logger;
import play.Play;
import play.data.validation.Required;
import play.libs.Crypto;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Util;
import play.utils.Java;
import mashpan.crawl.dropbox.DropboxCrawler;
import mashpan.security.Check;
import mashpan.utilities.*;

import controllers.Application;

/**
 * a more or less exact copy of the secure implementation of play.
 * - enhanced with a transport guarantee.
 * - support for user authentification
 * 
 *  @author ra and Philip De Smedt
 *  @version 0.1
 *  @date 20/11/2011
 *
 */
public class Secure extends TransportUriGuaranteeController {

    public static void authenticate(@Required String username, String password, boolean remember) throws Throwable {
        Logger.debug("[Secure] authenticate: "
                + "[username=" + (username == null ? "null" : username.toString()) + "]"
                + "[password=" + (password == null ? "null" : password.toString()) + "]"
                + "[remember=" + remember + "]"
                );

        // Check tokens
        Boolean allowed = false;
        User user = User.find("byEmail", username).first();
        Logger.debug("[Secure.authenticate] "+"[user=" + (user == null ? "null" : user.toString()) + "]");
//      try {
//          // This is the deprecated method name
//          allowed = (Boolean)Security.invoke("authentify", username, password);
//      } 
//      catch (UnsupportedOperationException e ) 
//      {
//          // This is the official method name
//          allowed = (Boolean)Security.invoke("authenticate", username, password);
//      }

        allowed = Security.authenticate(username, password);


        if(validation.hasErrors() || !allowed) {
            Logger.debug("[Secure] Authentication failed"
                    + ", validationhasErrors()=" + validation.hasErrors()
                    + ", allowed="+allowed
                    );
            if(validation.hasErrors()) {
                Logger.debug("[Secure] validation has errors!");
                for(play.data.validation.Error e : validation.errors()) {
                    Logger.debug("[Secure] Error: "+"[e=" + (e == null ? "null" : e.toString()) + "]");
                }
            }
            flash.keep("url");
            flash.error("secure.error");
            params.flash();
            Application.index();
        }

        // Mark user as connected
        session.put("email", username);

        // Remember if needed
        if (remember) 
        {
            response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
        }

        // Save last login time and redirect to the original URL (or /)
        User u = User.find("byEmail", username).first();
        u.lastLogin = new Date();
        u.save();

        Logger.debug("[Secure] Successfully authenticated user. Redirecting...");
        redirectToOriginalURL();
    }


    public static class Security extends Controller {

        /**
        * Extend Play!s security mechanism to authenticate against
        * the User object.
        */
        public static boolean authenticate(String email, String password) {
            Logger.debug("[Secure.Security.authenticate] "
                    + "[email=" + (email == null ? "null" : email.toString()) + "]"
                    + "[password=" + (password == null ? "null" : password.toString()) + "]");

            User user = User.find("byEmail", email).first();
            List<User> users = User.<User>findAll();
            Logger.debug("[Secure.Security] # of users found="+users.size());
            for(User u : users) {
                Logger.debug("[Secure.Security] "+"[u=" + (u == null ? "null" : u.toString()) + "]");
            }

            if (user == null) {
                Logger.debug("[Secure.Security] Could not find user, authentication failed!");
                return false;
            }

            if (user.confirmationCode.length() != 0) { //user not confirmed yet
                Logger.debug("[Secure.Security] User not confirmed yet, authentication failed!");
                return false;
            }
            return user.isThisCorrectUserPassword(password);
        }

        public static boolean check(String check) {
            if ("isConnected".equals(check)) {
                return Security.isConnected();                  
            }
            return false;
        }

        /**
        * This method returns the current connected username
        * @return
        */
        public static String connected() {
            return session.get("email");
        }

        /**
        * Indicate if a user is currently connected
        * @return  true if the user is connected
        */
        public static boolean isConnected() {
            return session.contains("email");
        }

        /**
        * This method is called after a successful authentication.
        * You need to override this method if you with to perform specific actions (eg. Record the time the user signed in)
        */
        static void onAuthenticated() { }

        /**
        * This method is called before a user tries to sign off.
        * You need to override this method if you wish to perform specific actions (eg. Record the name of the user who signed off)
        */
        static void onDisconnect() { }

        /**
        * This method is called after a successful sign off.
        * You need to override this method if you wish to perform specific actions (eg. Record the time the user signed off)
        */
        static void onDisconnected() { }

        /**
        * This method is called if a check does not succeed. By default it shows the not allowed page (the controller forbidden method).
        * @param profile
        */
        static void onCheckFailed(String profile) {
            forbidden();
        }
    }
}

测试类安全测试.java

package controller.user;

import java.util.*;

import mashpan.utilities.*;
import models.*;

import org.junit.*;

import play.*;
import play.cache.*;
import play.db.jpa.GenericModel.JPAQuery;
import play.mvc.Http.Response;
import play.test.*;

public class FunctionalSecureTests extends FunctionalTest {
    @Before
    public void setUp() {
        Fixtures.deleteDatabase();
        Fixtures.loadModels("testusers.yaml");
        Cache.clear();
    }


    @Test
    public void postLogin_shouldHaveStatus200() {
        User user = User.find("byEmail", UserUtility.EMAIL).first();
        Logger.debug("[FunctionalSecureTests] "+"[user=" + (user == null ? "null" : user.toString()) + "]"); //prints out


        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("username", UserUtility.EMAIL);
        parameters.put("password", UserUtility.PASSWORD);

        Response response = POST("/login", parameters);

        assertIsOk(response);
        assertStatus(200, response);
    }

}

conf/testusers.yaml

User(mashpan):
  first_name: "Mash"
  last_name: "Pan"
  email: "[email protected]"
  signupDate: 2012-03-08
  passwordHash: "NOTFORYOU"
  isAdmin: No
  confirmationCode: ""
  activationSent: Yes
  recoverPasswordCode: !!null
  lastLogin: !!null
  referralCode: !!null

堆栈跟踪

   DEBUG 232 :play#debug - [FunctionalSecureTests] [user=User [first_name=Mash, last_name=Pan, [email protected], signupDate=2012-03-08 01:00:00.0, passwordHash=$2a$10$L6IdeDhMGe1T7IbtSDd.6uLOvhHk7IoAzRzGzNlk8Cm4WWyWCbIp., isAdmin=false, confirmationCode=, activationSent=true, recoverPasswordCode=null, lastLogin=null, referralCode=null, [id=1]]]
   DEBUG 232 :play#debug - [Secure] authenticate: [[email protected]][password=chickenrunfasteriffedup][remember=false]
   DEBUG 232 :play#debug - [Secure.authenticate] [user=null]
   DEBUG 232 :play#debug - [Secure.Security.authenticate] [[email protected]][password=chickenrunfasteriffedup]
   DEBUG 232 :play#debug - [Secure.Security] # of users found=0
   DEBUG 232 :play#debug - [Secure.Security] Could not find user, authentication failed!
   DEBUG 232 :play#debug - [Secure] Authentication failed, validationhasErrors()=false, allowed=false

您的功能测试在一个事务中运行,该事务将在测试结束时结束。因此,在测试完成之前,您在此事务中所做的所有操作都不会提交到数据库。因此,在这种情况下,您可以使用作业来创建仅用于设置的新事务

@Before
public void setUp() throws Exception {
    new Job() {
        @Override
        public void doJob() throws Exception {
            Fixtures.deleteDatabase();
            Fixtures.loadModels("testusers.yaml");
            Cache.clear();
        }
    }.now().get();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 playframework 中设置数据库/夹具以进行功能测试 的相关文章

  • 自动在资源顶部插入 ETag(资产指纹)作为注释

    如何要求 Play 在不使用第三方插件的情况下自动将文件的 ETag 作为注释插入到文件顶部附近 例如 对于 HTML 资源 插入在顶部 tag 关于如何使用 Play 框架的内置公共资产路由 指纹支持来做到这一点的答案也很棒 相关问题 用
  • 为什么 Scala 程序的编译速度非常慢?

    过去两个月我一直在使用 Scala 我还在一个小应用程序中使用 Play 框架 我观察到 即使对于打印 Hello World 的程序来说 编译也非常慢 为什么这么慢 有什么减少时间的技巧吗 您的情况下编译速度有多快 scalac 的速度受
  • 如何从所有应用程序加载 Django 装置?

    我在 Django 应用程序中使用固定装置 但只有两个应用程序加载了固定装置 当我使用 verbosity 2 手动运行 loaddata 时 我可以看到它只在两个应用程序中查找 尽管我在内部创建了更多的固定装置目录 所有应用程序均已正确安
  • 玩法:如何实现动作组合

    鉴于以下情况ActionBuilder实施 class SignedRequest A request Request A extends WrappedRequest A request object SignedAction exten
  • 创建通用 Json 序列化函数

    是否可以使用 Play Framework 2 2 在 Scala 中创建一个通用函数 将任意对象序列化为 JSON 而无需提供编写器或格式化程序 例如 此非通用代码将创建给定客户的 JSON 响应 import play api libs
  • 使用 JsonView 将 POJO 转换为 JsonNode

    我正在编写一个典型的 Play Framework 应用程序 我想使用 Jackson 从控制器的方法返回 JsonNode 这就是我现在正在做的 public static Result foo MyPojoType myPojo new
  • Play2 的异常无法在 postgresql 上运行

    我发现play2的anorm的行解析器依赖于jdbc驱动程序返回的元数据 所以在play提供的内置示例 zentasks 中 我可以找到这样的代码 object Project val simple get Pk Long project
  • 当日志在不同进程中发出时,caplog 中的消息为空

    我正在使用 log cli true 运行测试 剧本 import logging import sys from multiprocessing import Process logging basicConfig stream sys
  • PlayFramework:如何转换 JSON 数组的每个元素

    鉴于以下 JSON values one two three 我如何在 Scala Play 中像这样转换它 values elem one elem two elem three 这很容易Play 的 JSON 转换器 https www
  • 如何访问 Play Guice 模块中的请求?

    我正在编写一个处理多个系统的应用程序 用户可以选择他想要使用的系统 我将该系统 ID 存储在会话 客户端会话 中 现在我有服务课程 比如说客户服务 class CustomerService val systemID String Impl
  • 清理 IntelliJ 中构建的 Play 框架

    我有一个拼写错误conf routes文件导致 Play Framework 生成错误命名的类 重建项目并运行Invalidate Caches并没有解决 IntelliJ 中的问题 当我手动运行时重新生成了不正确的类文件play clea
  • Slick和bonecp:org.postgresql.util.PSQLException:FATAL:抱歉,太多客户端已经错误

    当我在本地开发应用程序时 我使用以下命令启动我的 play2 应用程序sbt run 我喜欢如何更改代码 然后重新加载浏览器以查看我的更改 在大约 10 次代码更改之后 我收到 postgresql 太多连接错误 见下文 我的数据库连接使用
  • Play 框架:从 Build.sbt 读取版本

    我看到了很多关于如何从 build sbt 读取版本的问题 并且已经提供了很多解决方法来解决如何将 build sbt 指向 conf application conf 并在中指定版本改为conf application conf 我有一个
  • 如何使用play框架上传多个文件?

    我在用play framework 2 1 2 使用java我正在创建视图来上传多个文件 我的代码在这里 form action routes upload up enctype gt multipart form data
  • 在网络文件系统上使用 Play 框架自动重新加载

    我正在 VirtualBox VM 上运行 Play 框架应用程序 项目源代码位于与主机系统共享的目录中 框架的自动重新加载功能不起作用 这 可能 是由于 JNotify 无法检测到源文件的更改造成的 因为文件系统不是本地的 NFS 和 v
  • factory_girl + rspec 似乎并没有在每个示例后回滚更改

    类似于这里描述的问题 http rpheath com posts 411 how to use factory girl with rspec http rpheath com posts 411 how to use factory g
  • Play.application() 的替代方案是什么

    我是 Play 框架的新手 我想读取conf文件夹中的一个文件 所以我用了Play application classloader getResources Data json nextElement getFile 但我知道 play P
  • 为什么 Pytest 对夹具参数执行嵌套循环

    使用 Pytest 我想编写一个测试函数 该函数接受多个装置作为参数 每个灯具都有几个参数 例如 test demo py 中是一个函数test squared is less than 10需要固定装置 negative integer
  • ebean 映射到 BYTEA 的数据类型是什么?

    我有一个游戏 2 0 2 需要在数据库中存储一些文件的应用程序 我们使用 Ebean 作为 ORM 我相信我的数据库中需要一个 BYTEA 列来存储该文件 但我不确定在我的模型中使用什么数据类型 我应该使用某种Blob 或者只是一个byte
  • 如何定义一个 pytest 夹具供给定测试子目录中的所有测试使用?

    给定一个目录tests有几个子目录 每个子目录都包含测试模块 如何创建一个pytest仅在特定子目录中找到的每个测试之前运行的固定装置 tests init py subdirXX test module1 py test module2

随机推荐

  • 如何在 Angular JS Web 应用程序中使用 ckeditor?

    我很难使用ckeditor在我内置的 html 页面中angularjs 我已经尝试了很多例子 ng ckeditor directive ckeditor directive 但这些例子都没有帮助我 我想要一个文本区域 我可以在其中输入图
  • 在 Typescript 类中声明常量

    在 TypeScript 中声明常量的最佳方式是什么class 你不能声明一个常量 你可以声明一个readonly场 它比您期望的常数弱 但可能足够好 class MyClass static readonly staticReadOnly
  • Mac OS X >= 10.6 上的 Finder 文件图标徽章(图标覆盖)

    我正在寻找一种解决方案 可以在 Mac 上使用 cocoa 进行文件图标叠加 图标徽章 就像 Dropbox 在 mac 上所做的那样 有谁知道如何做到这一点 我搜索了 Xcode 文档并研究了scp插件源代码是一种旧的碳代码 有点晚了 但
  • Docker 容器无法到达本地主机端口 4444。为什么呢?

    我容器化了一个应用程序 它是自动化 Selenium 测试的测试驱动程序 Selenium 服务器 也称为 Selenium Hub 在另一个容器以及 Firefox 节点中运行 位于 localhost 4444 下 但我的应用程序无法到
  • 响应.on 是什么意思? Node.js

    我在处理 Node js http 请求时遇到问题 如果我无法弄清楚 我稍后会问一个更大的问题 我有修改过的代码和示例 但我不明白 response on 的含义 阅读有关 Node js 中 http 的更多信息 HTTP 事务剖析 我没
  • 浮点数表示,Java 示例[重复]

    这个问题在这里已经有答案了 您能否解释一下为什么我得到下一个结果 当我运行这个时 System out println 0 2 0 1 我得到 0 1 当我运行这个时 System out println 0 3 0 2 我得到 0 099
  • 在 Blazor 中,“await Task.Run(StateHasChanged)”和“await InvokeAsync(StateHasChanged)”之间有什么区别?

    我最近继承了 Blazor Webassemble 应用程序 但对 dotnet 或 Blazor 的经验很少 一些组件使用await Task Run StateHasChanged 而不是await InvokeAsync StateH
  • 根据字符将 Python 字符串列表拆分为单独的列表

    我试图弄清楚如何根据列表中的字符将以下列表拆分为单独的列表 list 2014 00 03 01 Matt login 0 01 2014 02 06 12 Mary login 0 01 我想在引入每个 符号后创建一个列表 例如 我希望输
  • PayPal 订阅 PDT / IPN - 请

    我在理解贝宝支付方面遇到了很多麻烦 我如何确认用户已成功注册我的订阅 我对 IPN 的了解为 0 但例如 如果用户使用以下命令注册到我的网站 电子邮件受保护 但使用贝宝帐户 电子邮件受保护 付款然后我如何匹配用户 我读到 PDT 不会发送用
  • 使用 jsonpath 获取匹配元素的父级

    假设我有一个如下所示的 JSON 对象 name A sub prop 1 prop 2 prop 3 name B sub prop 7 prop 8 prop 9 我怎样才能得到元素的父元素prop值为2 jsonpath query
  • 将最大值添加到 R 中的新列[重复]

    这个问题在这里已经有答案了 这是数据 a lt c 1 1 2 2 3 b lt c 1 3 5 9 4 df1 lt data frame a b df1 a b 1 1 1 3 2 5 2 9 3 4 我想要这样的东西 a b max
  • 如何使用 Pygame 播放正弦波/方波?

    我正在尝试使用 Pygame 播放正弦波sndarray make sound功能 但是 当我使用这个数组来播放它时 np sin 2 np pi np arange 44100 440 44100 astype np float32 wh
  • 如何更改 ICS 风格的 EditText 中线条的颜色

    我在我的应用程序中将 ABS 与主题全息一起使用 并且我得到的 EditText 样式就像在 ICS 中一样 但 EditText 的线条颜色默认为蓝色 对于我的设计 我需要 EditText 的白色线条 我尝试更改背景 但不起作用 有什么
  • 当 URL 存在时 urllib2 捕获 404 错误

    我遇到了奇怪的错误 urllib2 在打开有效的 url 时捕获 404 错误 我在浏览器中试了一下 可以打开url 我还传递了用户代理 import urllib request as urllib2 uri https i ytimg
  • 如何更改 UIImageView 中 UIImage 的位置

    我有一个UIImage called image我想改变它在里面的位置imageView所以可以稍微向下拖动 大约30px 有人可以告诉我该怎么做吗 这就是我要做的 但结果不正确 var image UIImage var imageVie
  • 更改 Intellij IDEA 中的 ${USER} 环境变量

    Intellij IDEA 有这样的类 文件模板 Created by USER on DATE where USER 默认情况下是登录用户名 或终极版本的许可用户名 我需要在文件模板中使用与登录操作系统用户名不同的名称 我怎样才能在IDE
  • 如何在 JavaScript 中创建字典并动态添加键值对

    来自帖子 发送一个 JSON 数组作为字典接收 我正在尝试做与那篇文章相同的事情 唯一的问题是我不知道预先的键和值是什么 所以我需要能够动态添加键和值对 但我不知道该怎么做 如何创建该对象并动态添加键值对 我试过了 var vars key
  • 升级到 WAS 7 后出现 javax.servlet.UnavailableException

    我已将应用程序从 WAS 6 迁移到 WAS 7 代码没有显示任何编译错误或缺少任何内容 但当我尝试运行该应用程序时 出现以下异常 9 19 12 9 45 37 609 EDT 00000009 extension W com ibm w
  • 有没有办法获得c函数的大小?

    我想知道是否有办法在运行时获取内存中c函数的大小 我已经使用了这段代码 但它不起作用 include
  • 如何在 playframework 中设置数据库/夹具以进行功能测试

    我正在尝试测试我的控制器 Secure java 我使用 play 的 Fixtures 类来设置数据库 不幸的是 当发出 POST 调用并调用控件的方法时 数据库结果为空 但是 在测试方法中 我可以按预期检索数据 The routes P