dongrong9053 2015-05-12 20:25
浏览 23

Yii单元测试和验证码

Anybody knows how to avoid captcha within Unit testing (Selenium) with Yii 1.x ? I've tried to get cuurent captcha value using in my tests:

$vc_key = "Yii.CCaptchaAction." . Yii::app()->getId() . ".site.captcha";
$captchaCode = Yii::app()->session->get($vc_key);

- got empty value. Also have tried with:

$captcha=Yii::app()->getController()->createAction("captcha");
$captchaCode = $captcha->verifyCode;

And got an error: Fatal error: Call to a member function createAction() on a non-object

  • 写回答

1条回答 默认 最新

  • dongmuyuan3046 2015-05-13 09:39
    关注

    Got it to work with this way: 1. Add to your test config (it uses by Yii unit tests) some variable lets say, it will be "testmode":

    ...
    'params' => array(
        'testmode' => true, // to avoid captcha validation
    ),
    ...
    
    1. In your model validation rules set corresponding condition. For me it is following: In rules:

      array( 'verifyCode', 'captchaValid', 'allowEmpty'=>!Yii::app()->user->isGuest || !CCaptcha::checkRequirements(), 'enableClientValidation' => true, 'message'=>Yii::t('app', 'wrong code'), 'on' => array('create'), ),

    Below:

    public function captchaValid($field, $params) {
        if(!$this->hasErrors($field))
        {
            if (Yii::app()->params['testmode'] == true) // here is our mark
                return;
            $vc_key = "Yii.CCaptchaAction." . Yii::app()->getId() . ".site.captcha";
            if ( Yii::app()->session->get($vc_key) != $this->{$field} )
            {
                $this->addError($field, $params['message']);
            }
    
        }
    }
    

    That's all. For my case it was some additional completions, but in most of cases, approach above should work. If you will have some problems with it, let me know.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?