'use strict';

/**
 * 辅助方法扩展单元测试
 *
 * @author CaiAoLin
 * @date 2017/10/24
 * @version
 */
const { app, assert } = require('egg-mock/bootstrap');

describe('test/app/extend/helper.test.js', () => {

    it('validateConvert test', function* () {
        // 创建 ctx
        const ctx = app.mockContext();
        const rule = {
            username: { type: 'string', required: true, allowEmpty: false, min: 4, max: 10 },
            group_id: { type: 'integer', required: true, allowEmpty: false, min: 4, max: 10 },
            password: { type: 'password', required: true, allowEmpty: false, min: 4 },
            confirm_password: { type: 'password', required: true, allowEmpty: false, min: 4, compare: 'password' },
            ip: 'isIP',
            telephone: 'isMobile',
        };
        // 转换为json验证
        let convertRule = ctx.helper.validateConvert(rule);
        convertRule = JSON.stringify(convertRule);
        let expectRule = {
            username: { required: true, minlength: 4, maxlength: 10 },
            group_id: { required: true, min: 4, max: 10 },
            password: { required: true, minlength: 4 },
            confirm_password: { required: true, minlength: 4, equalTo: '#password' },
            ip: 'isIP',
            telephone: 'isMobile',
        };
        expectRule = JSON.stringify(expectRule);
        assert(convertRule === expectRule);
    });

    it('generateRandomString test', function* () {
        // 创建 ctx
        const ctx = app.mockContext();
        const randomMix = ctx.helper.generateRandomString(4);
        const mixReg = /[A-Za-z0-9]{4}/;
        assert(mixReg.test(randomMix));

        // 测试纯数字
        const randomNumber = ctx.helper.generateRandomString(4, 2);
        const numberReg = /\d{4}/;
        assert(numberReg.test(randomNumber));

        // 测试纯字母
        const randomString = ctx.helper.generateRandomString(4, 3);
        const stringReg = /[A-Za-z]{4}/;
        assert(stringReg.test(randomString));
    });

    it('showSortFlag test', function* () {
        // 创建 ctx
        const ctx = app.mockContext({
            // sort: { test: 1 },
            sort: ['id', 'asc'],
        });
        const flag = ctx.helper.showSortFlag('id');
        assert(flag === '-');
    });

    it('isAjax test', function* () {
        // 创建 ctx
        const ctx = app.mockContext();
        const result = ctx.helper.isAjax(ctx);
        assert(!result);
    });

    it('sendRequest test', function* () {
        // 创建 ctx
        const ctx = app.mockContext();
        const url = 'http://ip.taobao.com/service/getIpInfo.php';
        const responseData = yield ctx.helper.sendRequest(url, { ip: '116.7.222.12' }, 'GET');
        assert(responseData.data.ip === '116.7.222.12');
    });

});
