This commit is contained in:
harttle
2016-10-26 02:50:41 +08:00
parent 34f5cfa34d
commit 377c805230
14 changed files with 418 additions and 337 deletions
+2 -2
View File
@@ -2,7 +2,7 @@ function TokenizationError(message, input, line) {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message || "";
this.message = message;
this.input = input;
this.line = line;
}
@@ -14,7 +14,7 @@ function ParseError(message, input, line, e) {
this.name = this.constructor.name;
this.originalError = e;
this.message = message || "";
this.message = message;
this.input = input;
this.line = line;
}
+31 -57
View File
@@ -4,7 +4,7 @@ const Promise = require('any-promise');
var render = {
renderTemplates: function(templates, scope, opts) {
if(!scope) throw new Error('unable to evalTemplates: scope undefined');
if (!scope) throw new Error('unable to evalTemplates: scope undefined');
opts = opts || {};
opts.strict_filters = opts.strict_filters || false;
@@ -15,80 +15,54 @@ var render = {
// emptyPromise.then(renderTag(template0).then(renderTag(template1).then(renderTag(template2)...
var lastPromise = templates.reduce((promise, template) => {
return promise.then(() => {
if (scope.safeGet('forloop.skip')) {
return Promise.resolve('');
}
if (scope.safeGet('forloop.stop')) {
throw new Error('forloop.stop'); // this will stop/break the sequential promise chain and go to the catch
}
var promiseLink = Promise.resolve('');
switch (template.type) {
case 'tag':
// Add Promises to the chain
promiseLink = this.renderTag(template, scope, this.register)
.then((partial) => {
if (partial === undefined) {
return true; // basically a noop (do nothing)
}
return html += partial;
});
break;
case 'html':
promiseLink = Promise.resolve(template.value)
.then((partial) => {
return html += partial;
});
break;
case 'output':
var val = this.evalOutput(template, scope, opts);
promiseLink = Promise.resolve(val === undefined ? '' : stringify(val))
.then((partial) => {
return html += partial;
});
break;
}
var promiseLink = Promise.resolve('');
switch (template.type) {
case 'tag':
// Add Promises to the chain
promiseLink = this.renderTag(template, scope, this.register)
.then((partial) => {
if (partial === undefined) {
return true; // basically a noop (do nothing)
}
return html += partial;
});
break;
case 'html':
promiseLink = Promise.resolve(template.value)
.then((partial) => {
return html += partial;
});
break;
case 'output':
var val = this.evalOutput(template, scope, opts);
promiseLink = Promise.resolve(val === undefined ? '' : stringify(val))
.then((partial) => {
return html += partial;
});
break;
}
return promiseLink;
})
.catch((error) => {
if (error.message === 'forloop.skip') {
// the error is a controlled, purposeful stop. so just return the html that we have up to this point
return html;
} else {
// rethrow actual error
throw error;
}
});
return promiseLink;
});
}, Promise.resolve('')); // start the reduce chain with a resolved Promise. After first run, the "promise" argument
// in our reduce callback will be the returned promise from our "then" above. In this
// case, that's the promise returned from this.renderTag or a resolved promise with raw html.
return lastPromise
.then((renderedHtml) => {
return renderedHtml;
})
.catch((error) => {
throw error;
});
return lastPromise;
},
renderTag: function(template, scope, register) {
if (template.name === 'continue') {
scope.set('forloop.skip', true);
return Promise.resolve('');
}
if (template.name === 'break') {
scope.set('forloop.stop', true);
scope.set('forloop.skip', true);
return Promise.reject(new Error('forloop.stop')); // this will stop the sequential promise chain
}
return template.render(scope, register);
},
evalOutput: function(template, scope, opts) {
if(!scope) throw new Error('unable to evalOutput: scope undefined');
if (!scope) throw new Error('unable to evalOutput: scope undefined');
var val = Syntax.evalExp(template.initial, scope);
template.filters.some(filter => {
if (filter.error) {
+140 -142
View File
@@ -2,162 +2,160 @@ const _ = require('./util/underscore.js');
const lexical = require('./lexical.js');
var Scope = {
safeGet: function(str) {
var i;
// get all
if (str === undefined) {
var ctx = {};
for (i = this.scopes.length - 1; i >= 0; i--) {
var scp = this.scopes[i];
for (var k in scp) {
if (scp.hasOwnProperty(k)) {
ctx[k] = scp[k];
}
}
}
return ctx;
}
// get one path
for (i = this.scopes.length - 1; i >= 0; i--) {
var v = this.getPropertyByPath(this.scopes[i], str);
if (v !== undefined) return v;
}
},
get: function(str) {
var val = this.safeGet(str);
if (val === undefined && this.opts.strict) {
throw new Error(`[strict_variables] undefined variable: ${str}`);
}
return val;
},
set: function(k, v) {
this.setPropertyByPath(this.scopes[this.scopes.length - 1], k, v);
return this;
},
push: function(ctx) {
if (!ctx) throw new Error(`trying to push ${ctx} into scopes`);
return this.scopes.push(ctx);
},
pop: function() {
return this.scopes.pop();
},
safeGet: function(str) {
var i;
// get all
if (str === undefined) {
var ctx = {};
for (i = this.scopes.length - 1; i >= 0; i--) {
var scp = this.scopes[i];
for (var k in scp) {
if (scp.hasOwnProperty(k)) {
ctx[k] = scp[k];
}
}
}
return ctx;
}
// get one path
for (i = this.scopes.length - 1; i >= 0; i--) {
var v = this.getPropertyByPath(this.scopes[i], str);
if (v !== undefined) return v;
}
},
get: function(str) {
var val = this.safeGet(str);
if (val === undefined && this.opts.strict) {
throw new Error(`[strict_variables] undefined variable: ${str}`);
}
return val;
},
set: function(k, v) {
this.setPropertyByPath(this.scopes[this.scopes.length - 1], k, v);
return this;
},
push: function(ctx) {
if (!ctx) throw new Error(`trying to push ${ctx} into scopes`);
return this.scopes.push(ctx);
},
pop: function() {
return this.scopes.pop();
},
unshift: function(ctx) {
if (!ctx) throw new Error('trying to push $(ctx) into scopes');
if (!ctx) throw new Error(`trying to push ${ctx} into scopes`);
return this.scopes.unshift(ctx);
},
shift: function() {
return this.scopes.shift();
},
setPropertyByPath: function(obj, path, val) {
if (_.isString(path)) {
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
for (var i = 0; i < paths.length; i++) {
var key = paths[i];
if (i === paths.length - 1) {
return obj[key] = val;
}
if (undefined === obj[key]) obj[key] = {};
// case for readonly objects
obj = obj[key] || {};
}
return obj;
}
return obj[path] = val;
},
setPropertyByPath: function(obj, path, val) {
if (_.isString(path)) {
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
for (var i = 0; i < paths.length; i++) {
var key = paths[i];
if (i === paths.length - 1) {
return obj[key] = val;
}
if (undefined === obj[key]) obj[key] = {};
// case for readonly objects
obj = obj[key] || {};
}
}
},
getPropertyByPath: function(obj, path) {
if (_.isString(path) && path.length) {
var paths = this.propertyAccessSeq(path);
paths.forEach(p => obj = obj && obj[p]);
return obj;
}
return obj[path];
},
getPropertyByPath: function(obj, path) {
if (_.isString(path) && path.length) {
var paths = this.propertyAccessSeq(path);
paths.forEach(p => obj = obj && obj[p]);
return obj;
}
return obj[path];
},
/*
* Parse property access sequence from access string
* @example
* accessSeq("foo.bar") // ['foo', 'bar']
* accessSeq("foo['bar']") // ['foo', 'bar']
* accessSeq("foo['b]r']") // ['foo', 'b]r']
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
*/
propertyAccessSeq: function(str) {
var seq = [],
name = '';
for (var i = 0; i < str.length; i++) {
if (str[i] === '[') {
seq.push(name);
name = '';
/*
* Parse property access sequence from access string
* @example
* accessSeq("foo.bar") // ['foo', 'bar']
* accessSeq("foo['bar']") // ['foo', 'bar']
* accessSeq("foo['b]r']") // ['foo', 'b]r']
* accessSeq("foo[bar.coo]") // ['foo', 'bar'], for bar.coo == 'bar'
*/
propertyAccessSeq: function(str) {
var seq = [],
name = '';
for (var i = 0; i < str.length; i++) {
if (str[i] === '[') {
seq.push(name);
name = '';
var delemiter = str[i + 1];
// foo[bar.coo]
if (delemiter !== "'" && delemiter !== '"') {
var j = matchRightBracket(str, i + 1);
if (j === -1) {
throw new Error(`unbalanced []: ${str}`);
}
name = str.slice(i + 1, j);
// foo[1]
if(lexical.isInteger(name)){
seq.push(name);
}
// foo["bar"]
else{
seq.push(this.get(name));
}
name = '';
i = j;
}
// foo["bar"]
else {
var j = str.indexOf(delemiter, i + 2);
if (j === -1) {
throw new Error(`unbalanced ${delemiter}: ${str}`);
}
name = str.slice(i + 2, j);
seq.push(name);
name = '';
i = j + 1;
}
}
// foo.bar
else if (str[i] === ".") {
seq.push(name);
name = '';
}
//foo.bar
else {
name += str[i];
}
}
if (name.length) seq.push(name);
return seq;
}
var delemiter = str[i + 1];
// foo[bar.coo]
if (delemiter !== "'" && delemiter !== '"') {
var j = matchRightBracket(str, i + 1);
if (j === -1) {
throw new Error(`unbalanced []: ${str}`);
}
name = str.slice(i + 1, j);
// foo[1]
if(lexical.isInteger(name)){
seq.push(name);
}
// foo["bar"]
else{
seq.push(this.get(name));
}
name = '';
i = j;
}
// foo["bar"]
else {
var j = str.indexOf(delemiter, i + 2);
if (j === -1) {
throw new Error(`unbalanced ${delemiter}: ${str}`);
}
name = str.slice(i + 2, j);
seq.push(name);
name = '';
i = j + 1;
}
}
// foo.bar
else if (str[i] === ".") {
seq.push(name);
name = '';
}
//foo.bar
else {
name += str[i];
}
}
if (name.length) seq.push(name);
return seq;
}
};
function matchRightBracket(str, begin) {
var stack = 1; // count of '[' - count of ']'
for (var i = begin; i < str.length; i++) {
if (str[i] === '[') {
stack++;
}
if (str[i] === ']') {
stack--;
if (stack === 0) {
return i;
}
}
}
return -1;
var stack = 1; // count of '[' - count of ']'
for (var i = begin; i < str.length; i++) {
if (str[i] === '[') {
stack++;
}
if (str[i] === ']') {
stack--;
if (stack === 0) {
return i;
}
}
}
return -1;
}
exports.factory = function(_ctx, opts) {
opts = opts || {};
opts.strict = opts.strict || false;
opts = opts || {};
opts.strict = opts.strict || false;
var scope = Object.create(Scope);
scope.opts = opts;
scope.scopes = [_ctx || {}];
return scope;
var scope = Object.create(Scope);
scope.opts = opts;
scope.scopes = [_ctx || {}];
return scope;
};
+4 -1
View File
@@ -1,9 +1,12 @@
const lexical = require('./lexical.js');
const TokenizationError = require('./error.js').TokenizationError;
const _ = require('./util/underscore.js');
function parse(html) {
var tokens = [];
if (!html) return tokens;
if (!_.isString(html)) {
throw new TokenizationError('illegal input type');
}
var syntax = /({%(.*?)%})|({{(.*?)}})/g;
var result, htmlFragment, token;
+12 -6
View File
@@ -10,7 +10,7 @@ var Scope = require('../src/scope.js');
describe('filter', function() {
var scope;
beforeEach(function(){
beforeEach(function() {
filter.clear();
scope = Scope.factory();
});
@@ -20,7 +20,13 @@ describe('filter', function() {
expect(result.error).to.be.an('Error');
});
it('should parse argument syntax', function(){
it('should throw when filter name illegal', function() {
expect(function() {
filter.construct('/');
}).to.throw(/illegal filter/);
});
it('should parse argument syntax', function() {
filter.register('foo', x => x);
var f = filter.construct('foo: a, "b"');
@@ -28,22 +34,22 @@ describe('filter', function() {
expect(f.args).to.deep.equal(['a', '"b"']);
});
it('should register a simple filter', function(){
it('should register a simple filter', function() {
filter.register('upcase', x => x.toUpperCase());
expect(filter.construct('upcase').render('foo', scope)).to.equal('FOO');
});
it('should register a argumented filter', function(){
it('should register a argumented filter', function() {
filter.register('add', (a, b) => a + b);
expect(filter.construct('add: 2').render(3, scope)).to.equal(5);
});
it('should register a multi-argumented filter', function(){
it('should register a multi-argumented filter', function() {
filter.register('add', (a, b, c) => a + b + c);
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal("5c");
});
it('should call filter with corrct arguments', function(){
it('should call filter with corrct arguments', function() {
var spy = sinon.spy();
filter.register('foo', spy);
filter.construct('foo: 33').render('foo', scope);
+7 -1
View File
@@ -13,7 +13,7 @@ var Template = require('../src/parser.js');
describe('template', function() {
var scope, template, add = (l, r) => l + r;
beforeEach(function(){
beforeEach(function() {
filter.clear();
filter.register('add', add);
@@ -21,6 +21,12 @@ describe('template', function() {
template = Template(tag, filter);
});
it('should throw when output string illegal', function() {
expect(function() {
template.parseOutput('/');
}).to.throw(/illegal output string/);
});
it('should parse output string', function() {
var tpl = template.parseOutput('foo');
expect(tpl.type).to.equal('output');
+22 -7
View File
@@ -28,8 +28,16 @@ describe('render', function() {
render = Render();
});
it('should render html', function() {
return render.renderTemplates([{type: 'html', value: '<p>'}], scope).should.eventually.equal('<p>');
describe('.renderTemplates()', function(){
it('should throw when scope undefined', function() {
expect(function(){
render.renderTemplates([]);
}).to.throw(/scope undefined/);
});
it('should render html', function() {
return render.renderTemplates([{type: 'html', value: '<p>'}], scope).should.eventually.equal('<p>');
});
});
it('should eval filter with correct arguments', function() {
@@ -43,10 +51,17 @@ describe('render', function() {
expect(time).to.have.been.calledWith('y', 2);
});
it('should eval output', function() {
filter.register('date', (l, r) => l + r);
filter.register('time', (l, r) => l + 3 * r);
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2');
expect(render.evalOutput(tpl, scope)).to.equal('ab6');
describe('.evalOutput()', function(){
it('should throw when scope undefined', function() {
expect(function(){
render.evalOutput();
}).to.throw(/scope undefined/);
});
it('should eval output', function() {
filter.register('date', (l, r) => l + r);
filter.register('time', (l, r) => l + 3 * r);
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2');
expect(render.evalOutput(tpl, scope)).to.equal('ab6');
});
});
});
+138 -99
View File
@@ -4,126 +4,165 @@ const expect = chai.expect;
var Scope = require('../src/scope.js');
describe('scope', function() {
var scope, ctx;
beforeEach(function() {
ctx = {
foo: 'zoo',
bar: {
zoo: 'coo',
"Mr.Smith": 'John',
arr: ['a', 'b']
}
};
scope = Scope.factory(ctx);
});
var scope, ctx;
beforeEach(function() {
ctx = {
foo: 'zoo',
bar: {
zoo: 'coo',
"Mr.Smith": 'John',
arr: ['a', 'b']
}
};
scope = Scope.factory(ctx);
});
describe('#propertyAccessSeq()', function() {
it('should handle dot syntax', function() {
expect(scope.propertyAccessSeq('foo.bar'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<String>] syntax', function() {
expect(scope.propertyAccessSeq('foo["bar"]'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<Identifier>] syntax', function() {
expect(scope.propertyAccessSeq('foo[foo]'))
.to.deep.equal(['foo', 'zoo']);
});
it('should handle nested access', function() {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo']);
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo']);
});
});
describe('#propertyAccessSeq()', function() {
it('should handle dot syntax', function() {
expect(scope.propertyAccessSeq('foo.bar'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<String>] syntax', function() {
expect(scope.propertyAccessSeq('foo["bar"]'))
.to.deep.equal(['foo', 'bar']);
});
it('should handle [<Identifier>] syntax', function() {
expect(scope.propertyAccessSeq('foo[foo]'))
.to.deep.equal(['foo', 'zoo']);
});
it('should handle nested access', function() {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo']);
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo']);
});
});
describe('#get()', function() {
it('should get direct property', function() {
expect(scope.get('foo')).equal('zoo');
});
describe('#get()', function() {
it('should get direct property', function() {
expect(scope.get('foo')).equal('zoo');
});
it('should get undefined property', function() {
function fn() {
scope.get('notdefined');
}
expect(fn).to.not.throw();
expect(scope.get('notdefined')).to.equal(undefined);
expect(scope.get('')).to.equal(undefined);
expect(scope.get(false)).to.equal(undefined);
});
it('should get undefined property', function() {
function fn() {
scope.get('notdefined');
}
expect(fn).to.not.throw();
expect(scope.get('notdefined')).to.equal(undefined);
expect(scope.get('')).to.equal(undefined);
expect(scope.get(false)).to.equal(undefined);
});
it('should throw undefined in strict mode', function() {
scope = Scope.factory(ctx, {
strict: true
});
it('should throw when [] unbalanced', function() {
expect(function() {
scope.get('foo[bar');
}).to.throw(/unbalanced \[\]/);
});
function fn() {
scope.get('notdefined');
}
expect(fn).to.throw(/undefined variable: notdefined/);
});
it('should throw when "" unbalanced', function() {
expect(function() {
scope.get('foo["bar]');
}).to.throw(/unbalanced "/);
});
it('should get all properties when arguments empty', function() {
expect(scope.get()).deep.equal(ctx);
});
it("should throw when '' unbalanced", function() {
expect(function() {
scope.get("foo['bar]");
}).to.throw(/unbalanced '/);
});
it('should access child property via dot syntax', function() {
expect(scope.get('bar.zoo')).to.equal('coo');
expect(scope.get('bar.arr')).to.deep.equal(['a', 'b']);
});
it('should throw undefined in strict mode', function() {
scope = Scope.factory(ctx, {
strict: true
});
it('should access child property via [<String>] syntax', function() {
expect(scope.get('bar["zoo"]')).to.equal('coo');
});
function fn() {
scope.get('notdefined');
}
expect(fn).to.throw(/undefined variable: notdefined/);
});
it('should access child property via [<Number>] syntax', function() {
expect(scope.get('bar.arr[0]')).to.equal('a');
});
it('should get all properties when arguments empty', function() {
expect(scope.get()).deep.equal(ctx);
});
it('should access child property via [<Identifier>] syntax', function() {
expect(scope.get('bar[foo]')).to.equal('coo');
});
it('should access child property via dot syntax', function() {
expect(scope.get('bar.zoo')).to.equal('coo');
expect(scope.get('bar.arr')).to.deep.equal(['a', 'b']);
});
it('should support nested case', function() {
scope.set('posts', {
"first": {"name": "A Nice Day"}
});
scope.set('category', {
"diary": ["first"]
});
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day');
});
});
it('should access child property via [<String>] syntax', function() {
expect(scope.get('bar["zoo"]')).to.equal('coo');
});
describe('.push(), .pop()', function() {
it('should push scope', function() {
scope.set('bar', 'bar');
scope.push({
foo: 'foo'
});
expect(scope.get('foo')).to.equal('foo');
expect(scope.get('bar')).to.equal('bar');
});
it('should access child property via [<Number>] syntax', function() {
expect(scope.get('bar.arr[0]')).to.equal('a');
});
it('should pop scope', function() {
scope.push({
foo: 'foo'
});
scope.pop();
expect(scope.get('foo')).to.equal('zoo');
});
it('should access child property via [<Identifier>] syntax', function() {
expect(scope.get('bar[foo]')).to.equal('coo');
});
it('should support nested case', function() {
scope.set('posts', {
"first": {
"name": "A Nice Day"
}
});
scope.set('category', {
"diary": ["first"]
});
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day');
});
});
describe('.push(), .pop()', function() {
it('should throw when trying to push non-object', function() {
expect(function() {
scope.push(false);
}).to.throw();
});
it('should push scope', function() {
scope.set('bar', 'bar');
scope.push({
foo: 'foo'
});
expect(scope.get('foo')).to.equal('foo');
expect(scope.get('bar')).to.equal('bar');
});
it('should pop scope', function() {
scope.push({
foo: 'foo'
});
scope.pop();
expect(scope.get('foo')).to.equal('zoo');
});
});
describe('.push(), .pop()', function() {
it('should throw when trying to unshift non-object', function() {
expect(function() {
scope.unshift(false);
}).to.throw();
});
it('should unshift scope', function() {
scope.unshift({foo: 'blue', foo1: 'foo1'})
scope.unshift({
foo: 'blue',
foo1: 'foo1'
})
scope.get('foo').should.equal('zoo');
scope.get('foo1').should.equal('foo1');
});
it('should shift scope', function() {
scope.unshift({foo: 'blue', foo1: 'foo1'});
scope.unshift({
foo: 'blue',
foo1: 'foo1'
});
scope.shift();
expect(scope.get('foo')).to.equal('zoo');
expect(scope.get('foo1')).to.equal(undefined);
});
});
});
});
+25 -15
View File
@@ -34,22 +34,32 @@ describe('expression', function() {
expect(evalValue('x', scope)).to.equal('XXX');
});
it('should eval simple expression', function() {
expect(evalExp('1<2', scope)).to.equal(true);
expect(evalExp('2<=2', scope)).to.equal(true);
expect(evalExp('one<=two', scope)).to.equal(true);
expect(evalExp('x contains "x"', scope)).to.equal(false);
expect(evalExp('x contains "X"', scope)).to.equal(true);
expect(evalExp('"<=" == "<="', scope)).to.equal(true);
});
describe('.evalExp()', function() {
it('should eval complex expression', function() {
expect(evalExp('1<2 and x contains "x"', scope)).to.equal(false);
expect(evalExp('1<2 or x contains "x"', scope)).to.equal(true);
});
it('should throw when scope undefined', function() {
expect(function() {
evalExp('');
}).to.throw(/scope undefined/);
});
it("should eval range expression", function() {
expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4]);
expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4]);
it('should eval simple expression', function() {
expect(evalExp('1<2', scope)).to.equal(true);
expect(evalExp('2<=2', scope)).to.equal(true);
expect(evalExp('one<=two', scope)).to.equal(true);
expect(evalExp('x contains "x"', scope)).to.equal(false);
expect(evalExp('x contains "X"', scope)).to.equal(true);
expect(evalExp('"<=" == "<="', scope)).to.equal(true);
});
it('should eval complex expression', function() {
expect(evalExp('1<2 and x contains "x"', scope)).to.equal(false);
expect(evalExp('1<2 or x contains "x"', scope)).to.equal(true);
expect(evalExp('false or true', scope)).to.equal(true);
});
it("should eval range expression", function() {
expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4]);
expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4]);
});
});
});
+6
View File
@@ -5,6 +5,12 @@ chai.use(require("chai-as-promised"));
describe('tags/assign', function() {
var liquid = Liquid();
it('should throw when variable expression illegal', function() {
var src = '{% assign / %}';
var ctx = {};
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/);
});
it('should assign as string', function() {
var src = '{% assign foo="bar" %}{{foo}}';
return expect(liquid.parseAndRender(src))
+6
View File
@@ -6,6 +6,12 @@ chai.use(require("chai-as-promised"));
describe('tags/decrement', function() {
var liquid = Liquid();
it('should throw when variable expression illegal', function() {
var src = '{% decrement / %}{{one}}';
var ctx = {};
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/);
});
it('should support decrement', function() {
var src = '{% decrement one %}{{one}}';
var ctx = {
+9 -4
View File
@@ -13,7 +13,12 @@ describe('tokenizer', function() {
tokens[0].value.should.equal(html);
tokens[0].type.should.equal('html');
});
it('should handle tag syntax', function(){
it('should throw when non-string passed in', function() {
expect(function() {
tokenizer.parse({});
}).to.throw('illegal input type');
});
it('should handle tag syntax', function() {
var html = '<p>{% for p in a[1]%}</p>';
var tokens = tokenizer.parse(html);
@@ -21,7 +26,7 @@ describe('tokenizer', function() {
tokens[1].type.should.equal('tag');
tokens[1].value.should.equal('for p in a[1]');
});
it('should handle output syntax', function(){
it('should handle output syntax', function() {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>';
var tokens = tokenizer.parse(html);
@@ -29,7 +34,7 @@ describe('tokenizer', function() {
tokens[1].type.should.equal('output');
tokens[1].value.should.equal('foo | date: "%Y-%m-%d"');
});
it('should handle successive outputs and tags', function(){
it('should handle successive outputs and tags', function() {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}';
var tokens = tokenizer.parse(html);
@@ -40,7 +45,7 @@ describe('tokenizer', function() {
tokens[1].value.should.equal('bar');
tokens[2].value.should.equal('foo');
});
it('should keep white spaces and newlines', function(){
it('should keep white spaces and newlines', function() {
var html = '{{foo}}\n{%bar %} \n {{alice}}';
var tokens = tokenizer.parse(html);
expect(tokens.length).to.equal(5);
+8 -3
View File
@@ -8,7 +8,7 @@ describe('util/strftime', function() {
before(function() {
mockUTC();
now = new Date('2016-01-04T13:15:23');
then = new Date('2016-01-03T03:05:03');
then = new Date('2016-03-06T03:05:03');
});
after(function() {
restoreUTC();
@@ -36,7 +36,7 @@ describe('util/strftime', function() {
expect(t(now, '%I')).to.equal('01');
});
it('should format %j as day of year', function() {
expect(t(now, '%j')).to.equal('004');
expect(t(then, '%j')).to.equal('066');
});
it('should format %k as space padded hour', function() {
expect(t(then, '%k')).to.equal(' 3');
@@ -56,8 +56,13 @@ describe('util/strftime', function() {
expect(t(then, '%P')).to.equal('am');
});
it('should format %q as date suffix', function(){
var st = new Date('2016-03-01T03:05:03');
var nd = new Date('2016-03-02T03:05:03');
var rd = new Date('2016-03-03T03:05:03');
expect(t(st, '%q')).to.equal('st');
expect(t(nd, '%q')).to.equal('nd');
expect(t(rd, '%q')).to.equal('rd');
expect(t(now, '%q')).to.equal('th');
expect(t(then, '%q')).to.equal('rd');
});
it('should format %s as UNIX seconds', function(){
expect(t(now, '%s')).to.be.match(/\d+/);
+8
View File
@@ -36,5 +36,13 @@ describe('util/underscore', function() {
expect(spy).to.have.been.calledOnce;
expect(spy).to.have.been.calledWith('bar', 'foo', obj);
});
it('should break when returned false', function() {
var spy = sinon.stub().returns(false);
_.forOwn({
'foo': 'foo',
'bar': 'foo'
}, spy);
expect(spy).to.have.been.calledOnce;
});
});
});