This commit is contained in:
harttle
2017-04-24 21:31:30 +08:00
parent 82f84d96c1
commit 2632e3e97e
50 changed files with 3941 additions and 3903 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "standard",
"env": {
"browser": true,
"node": true
},
"plugins": [
"standard",
"promise"
]
}
+141 -141
View File
@@ -1,152 +1,152 @@
const Scope = require('./src/scope');
const _ = require('./src/util/underscore.js');
const assert = require('./src/util/assert.js');
const tokenizer = require('./src/tokenizer.js');
const statFileAsync = require('./src/util/fs.js').statFileAsync;
const readFileAsync = require('./src/util/fs.js').readFileAsync;
const path = require('path');
const Render = require('./src/render.js');
const lexical = require('./src/lexical.js');
const Tag = require('./src/tag.js');
const Filter = require('./src/filter.js');
const Parser = require('./src/parser');
const Syntax = require('./src/syntax.js');
const tags = require('./tags');
const filters = require('./filters');
const Promise = require('any-promise');
const anySeries = require('./src/util/promise.js').anySeries;
const Errors = require('./src/util/error.js');
const Scope = require('./src/scope')
const _ = require('./src/util/underscore.js')
const assert = require('./src/util/assert.js')
const tokenizer = require('./src/tokenizer.js')
const statFileAsync = require('./src/util/fs.js').statFileAsync
const readFileAsync = require('./src/util/fs.js').readFileAsync
const path = require('path')
const Render = require('./src/render.js')
const lexical = require('./src/lexical.js')
const Tag = require('./src/tag.js')
const Filter = require('./src/filter.js')
const Parser = require('./src/parser')
const Syntax = require('./src/syntax.js')
const tags = require('./tags')
const filters = require('./filters')
const Promise = require('any-promise')
const anySeries = require('./src/util/promise.js').anySeries
const Errors = require('./src/util/error.js')
var _engine = {
init: function(tag, filter, options) {
if (options.cache) {
this.cache = {};
}
this.options = options;
this.tag = tag;
this.filter = filter;
this.parser = Parser(tag, filter);
this.renderer = Render();
tags(this);
filters(this);
return this;
},
parse: function(html, filepath) {
var tokens = tokenizer.parse(html, filepath, this.options);
return this.parser.parse(tokens);
},
render: function(tpl, ctx, opts) {
opts = _.assign({}, this.options, opts);
var scope = Scope.factory(ctx, opts);
return this.renderer.renderTemplates(tpl, scope);
},
parseAndRender: function(html, ctx, opts) {
return Promise.resolve()
.then(() => this.parse(html))
.then(tpl => this.render(tpl, ctx, opts))
.catch(e => {
if (e instanceof Errors.RenderBreakError) {
return e.html;
}
throw e;
});
},
renderFile: function(filepath, ctx, opts) {
opts = _.assign({}, opts);
return this.getTemplate(filepath, opts.root)
.then(templates => this.render(templates, ctx, opts));
},
evalOutput: function(str, scope) {
var tpl = this.parser.parseOutput(str.trim());
return this.renderer.evalOutput(tpl, scope);
},
registerFilter: function(name, filter) {
return this.filter.register(name, filter);
},
registerTag: function(name, tag) {
return this.tag.register(name, tag);
},
lookup: function(filepath, root) {
root = this.options.root.concat(root || []);
root = _.uniq(root);
var paths = root.map(root => path.resolve(root, filepath));
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
if (e.code === 'ENOENT') {
e.message = `Failed to lookup ${filepath} in: ${root}`;
}
throw e;
});
},
getTemplate: function(filepath, root) {
if(!path.extname(filepath)){
filepath += this.options.extname;
}
return this
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath];
if (tpl) {
return Promise.resolve(tpl);
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => this.cache[filepath] = tpl);
} else {
return readFileAsync(filepath).then(str => this.parse(str, filepath));
}
});
},
express: function(opts) {
opts = opts || {};
var self = this;
return function(filePath, ctx, callback) {
assert(_.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?');
opts.root = this.root;
self.renderFile(filePath, ctx, opts)
.then(html => callback(null, html))
.catch(e => callback(e));
};
init: function (tag, filter, options) {
if (options.cache) {
this.cache = {}
}
};
this.options = options
this.tag = tag
this.filter = filter
this.parser = Parser(tag, filter)
this.renderer = Render()
function factory(options) {
options = _.assign({
root: ['.'],
cache: false,
extname: '.liquid',
trim_right: false,
trim_left: false,
strict_filters: false,
strict_variables: false
}, options);
options.root = normalizeStringArray(options.root);
tags(this)
filters(this)
var engine = Object.create(_engine);
engine.init(Tag(), Filter(options), options);
return engine;
return this
},
parse: function (html, filepath) {
var tokens = tokenizer.parse(html, filepath, this.options)
return this.parser.parse(tokens)
},
render: function (tpl, ctx, opts) {
opts = _.assign({}, this.options, opts)
var scope = Scope.factory(ctx, opts)
return this.renderer.renderTemplates(tpl, scope)
},
parseAndRender: function (html, ctx, opts) {
return Promise.resolve()
.then(() => this.parse(html))
.then(tpl => this.render(tpl, ctx, opts))
.catch(e => {
if (e instanceof Errors.RenderBreakError) {
return e.html
}
throw e
})
},
renderFile: function (filepath, ctx, opts) {
opts = _.assign({}, opts)
return this.getTemplate(filepath, opts.root)
.then(templates => this.render(templates, ctx, opts))
},
evalOutput: function (str, scope) {
var tpl = this.parser.parseOutput(str.trim())
return this.renderer.evalOutput(tpl, scope)
},
registerFilter: function (name, filter) {
return this.filter.register(name, filter)
},
registerTag: function (name, tag) {
return this.tag.register(name, tag)
},
lookup: function (filepath, root) {
root = this.options.root.concat(root || [])
root = _.uniq(root)
var paths = root.map(root => path.resolve(root, filepath))
return anySeries(paths, path => statFileAsync(path).then(() => path))
.catch((e) => {
if (e.code === 'ENOENT') {
e.message = `Failed to lookup ${filepath} in: ${root}`
}
throw e
})
},
getTemplate: function (filepath, root) {
if (!path.extname(filepath)) {
filepath += this.options.extname
}
return this
.lookup(filepath, root)
.then(filepath => {
if (this.options.cache) {
var tpl = this.cache[filepath]
if (tpl) {
return Promise.resolve(tpl)
}
return readFileAsync(filepath)
.then(str => this.parse(str))
.then(tpl => (this.cache[filepath] = tpl))
} else {
return readFileAsync(filepath).then(str => this.parse(str, filepath))
}
})
},
express: function (opts) {
opts = opts || {}
var self = this
return function (filePath, ctx, callback) {
assert(_.isArray(this.root) || _.isString(this.root),
'illegal views root, are you using express.js?')
opts.root = this.root
self.renderFile(filePath, ctx, opts)
.then(html => callback(null, html))
.catch(e => callback(e))
}
}
}
function normalizeStringArray(value) {
if (_.isArray(value)) return value;
if (_.isString(value)) return [value];
return [];
function factory (options) {
options = _.assign({
root: ['.'],
cache: false,
extname: '.liquid',
trim_right: false,
trim_left: false,
strict_filters: false,
strict_variables: false
}, options)
options.root = normalizeStringArray(options.root)
var engine = Object.create(_engine)
engine.init(Tag(), Filter(options), options)
return engine
}
factory.lexical = lexical;
factory.isTruthy = Syntax.isTruthy;
factory.isFalsy = Syntax.isFalsy;
factory.evalExp = Syntax.evalExp;
factory.evalValue = Syntax.evalValue;
function normalizeStringArray (value) {
if (_.isArray(value)) return value
if (_.isString(value)) return [value]
return []
}
factory.lexical = lexical
factory.isTruthy = Syntax.isTruthy
factory.isFalsy = Syntax.isFalsy
factory.evalExp = Syntax.evalExp
factory.evalValue = Syntax.evalValue
factory.Types = {
ParseError: Errors.ParseError,
TokenizationEroor: Errors.TokenizationError,
RenderBreakError: Errors.RenderBreakError,
AssertionError: Errors.AssertionError
};
ParseError: Errors.ParseError,
TokenizationEroor: Errors.TokenizationError,
RenderBreakError: Errors.RenderBreakError,
AssertionError: Errors.AssertionError
}
module.exports = factory;
module.exports = factory
+9 -1
View File
@@ -4,7 +4,8 @@
"description": "A feature-rich Liquid template engine for Node.js and browsers, with compliance with the Ruby version.",
"main": "index.js",
"scripts": {
"test": "mocha --recursive",
"lint": "eslint src/ test/",
"test": "npm run lint && mocha --recursive",
"dist": "make dist",
"preversion": "npm test",
"version": "npm run dist && git add -A dist",
@@ -37,6 +38,13 @@
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"coveralls": "^2.11.9",
"eslint": "^3.19.0",
"eslint-config-standard": "^10.2.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-mocha": "^4.9.0",
"eslint-plugin-node": "^4.2.2",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1",
"express": "^4.14.0",
"istanbul": "^0.4.3",
"mocha": "^3.0.2",
+56 -58
View File
@@ -1,68 +1,66 @@
const lexical = require('./lexical.js');
const Syntax = require('./syntax.js');
const assert = require('./util/assert.js');
const _ = require('./util/underscore.js');
const lexical = require('./lexical.js')
const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
const _ = require('./util/underscore.js')
var valueRE = new RegExp(`${lexical.value.source}`, 'g');
var valueRE = new RegExp(`${lexical.value.source}`, 'g')
module.exports = function(options) {
options = _.assign({}, options);
var filters = {};
module.exports = function (options) {
options = _.assign({}, options)
var filters = {}
var _filterInstance = {
render: function(output, scope) {
var args = this.args.map(arg => Syntax.evalValue(arg, scope));
args.unshift(output);
return this.filter.apply(null, args);
},
parse: function(str) {
var match = lexical.filterLine.exec(str);
assert(match, 'illegal filter: ' + str);
var _filterInstance = {
render: function (output, scope) {
var args = this.args.map(arg => Syntax.evalValue(arg, scope))
args.unshift(output)
return this.filter.apply(null, args)
},
parse: function (str) {
var match = lexical.filterLine.exec(str)
assert(match, 'illegal filter: ' + str)
var name = match[1], argList = match[2] || '', filter = filters[name];
if (typeof filter !== 'function'){
if(options.strict_filters){
throw new TypeError(`undefined filter: ${name}`);
}
this.name= name;
this.filter= x => x;
this.args= [];
return this;
//return {
//name: name,
//error: new TypeError(`undefined filter: ${name}`)
//};
}
var args = [];
while(match = valueRE.exec(argList.trim())){
var v = match[0];
var re = new RegExp(`${v}\\s*:`, 'g');
re.test(match.input) ? args.push(`'${v}'`) : args.push(v);
}
this.name = name;
this.filter = filter;
this.args = args;
return this;
var name = match[1]
var argList = match[2] || ''
var filter = filters[name]
if (typeof filter !== 'function') {
if (options.strict_filters) {
throw new TypeError(`undefined filter: ${name}`)
}
};
this.name = name
this.filter = x => x
this.args = []
return this
}
function construct(str) {
var instance = Object.create(_filterInstance);
return instance.parse(str);
var args = []
while ((match = valueRE.exec(argList.trim()))) {
var v = match[0]
var re = new RegExp(`${v}\\s*:`, 'g')
re.test(match.input) ? args.push(`'${v}'`) : args.push(v)
}
this.name = name
this.filter = filter
this.args = args
return this
}
}
function register(name, filter) {
filters[name] = filter;
}
function construct (str) {
var instance = Object.create(_filterInstance)
return instance.parse(str)
}
function clear() {
filters = {};
}
function register (name, filter) {
filters[name] = filter
}
return {
construct, register, clear
};
};
function clear () {
filters = {}
}
return {
construct, register, clear
}
}
+84 -61
View File
@@ -1,92 +1,115 @@
// quote related
var singleQuoted = /'[^']*'/;
var doubleQuoted = /"[^"]*"/;
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`);
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`);
var singleQuoted = /'[^']*'/
var doubleQuoted = /"[^"]*"/
var quoted = new RegExp(`${singleQuoted.source}|${doubleQuoted.source}`)
var quoteBalanced = new RegExp(`(?:${quoted.source}|[^'"])*`)
// basic types
var integer = /-?\d+/;
var number = /-?\d+\.?\d*|\.?\d+/;
var bool = /true|false/;
var integer = /-?\d+/
var number = /-?\d+\.?\d*|\.?\d+/
var bool = /true|false/
// peoperty access
var identifier = /[\w-]+/;
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`);
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`);
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`);
var identifier = /[\w-]+/
var subscript = new RegExp(`\\[(?:${quoted.source}|[\\w-\\.]+)\\]`)
var literal = new RegExp(`(?:${quoted.source}|${bool.source}|${number.source})`)
var variable = new RegExp(`${identifier.source}(?:\\.${identifier.source}|${subscript.source})*`)
// range related
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`);
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`);
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`);
var rangeLimit = new RegExp(`(?:${variable.source}|${number.source})`)
var range = new RegExp(`\\(${rangeLimit.source}\\.\\.${rangeLimit.source}\\)`)
var rangeCapture = new RegExp(`\\((${rangeLimit.source})\\.\\.(${rangeLimit.source})\\)`)
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`);
var value = new RegExp(`(?:${variable.source}|${literal.source}|${range.source})`)
// hash related
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`);
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g');
var hash = new RegExp(`(?:${identifier.source})\\s*:\\s*(?:${value.source})`)
var hashCapture = new RegExp(`(${identifier.source})\\s*:\\s*(${value.source})`, 'g')
// full match
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`);
var literalLine = new RegExp(`^${literal.source}$`, 'i');
var variableLine = new RegExp(`^${variable.source}$`);
var numberLine = new RegExp(`^${number.source}$`);
var boolLine = new RegExp(`^${bool.source}$`, 'i');
var quotedLine = new RegExp(`^${quoted.source}$`);
var rangeLine = new RegExp(`^${rangeCapture.source}$`);
var integerLine = new RegExp(`^${integer.source}$`);
var tagLine = new RegExp(`^\\s*(${identifier.source})\\s*([\\s\\S]*)\\s*$`)
var literalLine = new RegExp(`^${literal.source}$`, 'i')
var variableLine = new RegExp(`^${variable.source}$`)
var numberLine = new RegExp(`^${number.source}$`)
var boolLine = new RegExp(`^${bool.source}$`, 'i')
var quotedLine = new RegExp(`^${quoted.source}$`)
var rangeLine = new RegExp(`^${rangeCapture.source}$`)
var integerLine = new RegExp(`^${integer.source}$`)
// filter related
var valueDeclaration = new RegExp(`(?:${identifier.source}\\s*:\\s*)?${value.source}`)
var valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`);
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g');
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`);
var filterLine = new RegExp(`^${filterCapture.source}$`);
var valueList = new RegExp(`${valueDeclaration.source}(\\s*,\\s*${valueDeclaration.source})*`)
var filter = new RegExp(`${identifier.source}(?:\\s*:\\s*${valueList.source})?`, 'g')
var filterCapture = new RegExp(`(${identifier.source})(?:\\s*:\\s*(${valueList.source}))?`)
var filterLine = new RegExp(`^${filterCapture.source}$`)
var operators = [
/\s+or\s+/,
/\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/
];
/\s+or\s+/,
/\s+and\s+/,
/==|!=|<=|>=|<|>|\s+contains\s+/
]
function isInteger(str){
return integerLine.test(str);
function isInteger (str) {
return integerLine.test(str)
}
function isLiteral(str) {
return literalLine.test(str);
function isLiteral (str) {
return literalLine.test(str)
}
function isRange(str) {
return rangeLine.test(str);
function isRange (str) {
return rangeLine.test(str)
}
function isVariable(str) {
return variableLine.test(str);
function isVariable (str) {
return variableLine.test(str)
}
function matchValue(str) {
return value.exec(str);
function matchValue (str) {
return value.exec(str)
}
function parseLiteral(str) {
var res;
if (res = str.match(numberLine)) {
return Number(str);
}
if (res = str.match(boolLine)) {
return str.toLowerCase() === 'true';
}
if (res = str.match(quotedLine)) {
return str.slice(1, -1);
}
function parseLiteral (str) {
var res = str.match(numberLine)
if (res) {
return Number(str)
}
res = str.match(boolLine)
if (res) {
return str.toLowerCase() === 'true'
}
res = str.match(quotedLine)
if (res) {
return str.slice(1, -1)
}
}
module.exports = {
quoted, number, bool, literal, filter, integer,
hash, hashCapture,
range, rangeCapture,
identifier, value, quoteBalanced, operators,
quotedLine, numberLine, boolLine, rangeLine, literalLine, filterLine, tagLine,
isLiteral, isVariable, parseLiteral, isRange, matchValue, isInteger
};
quoted,
number,
bool,
literal,
filter,
integer,
hash,
hashCapture,
range,
rangeCapture,
identifier,
value,
quoteBalanced,
operators,
quotedLine,
numberLine,
boolLine,
rangeLine,
literalLine,
filterLine,
tagLine,
isLiteral,
isVariable,
parseLiteral,
isRange,
matchValue,
isInteger
}
+15 -15
View File
@@ -1,17 +1,17 @@
var operators = {
'==': (l, r) => l == r,
'!=': (l, r) => l != r,
'>': (l, r) => l !== null && r !== null && l > r,
'<': (l, r) => l !== null && r !== null && l < r,
'>=': (l, r) => l !== null && r !== null && l >= r,
'<=': (l, r) => l !== null && r !== null && l <= r,
'contains': (l, r) => {
if (!l) return false;
if (typeof l.indexOf !== 'function') return false;
return l.indexOf(r) > -1;
},
'and': (l, r) => l && r,
'or': (l, r) => l || r
};
'==': (l, r) => l === r,
'!=': (l, r) => l !== r,
'>': (l, r) => l !== null && r !== null && l > r,
'<': (l, r) => l !== null && r !== null && l < r,
'>=': (l, r) => l !== null && r !== null && l >= r,
'<=': (l, r) => l !== null && r !== null && l <= r,
'contains': (l, r) => {
if (!l) return false
if (typeof l.indexOf !== 'function') return false
return l.indexOf(r) > -1
},
'and': (l, r) => l && r,
'or': (l, r) => l || r
}
module.exports = operators;
module.exports = operators
+91 -91
View File
@@ -1,105 +1,105 @@
const lexical = require('./lexical.js');
const ParseError = require('./util/error.js').ParseError;
const assert = require('./util/assert.js');
const lexical = require('./lexical.js')
const ParseError = require('./util/error.js').ParseError
const assert = require('./util/assert.js')
module.exports = function(Tag, Filter) {
var stream = {
init: function(tokens) {
this.tokens = tokens;
this.handlers = {};
return this;
},
on: function(name, cb) {
this.handlers[name] = cb;
return this;
},
trigger: function(event, arg) {
var h = this.handlers[event];
if (typeof h === 'function') {
h(arg);
return true;
}
},
start: function() {
this.trigger('start');
var token;
while (!this.stopRequested && (token = this.tokens.shift())) {
if (this.trigger('token', token)) continue;
if (token.type == 'tag' &&
this.trigger(`tag:${token.name}`, token)) {
continue;
}
var template = parseToken(token, this.tokens);
this.trigger('template', template);
}
if (!this.stopRequested) this.trigger('end');
return this;
},
stop: function() {
this.stopRequested = true;
return this;
module.exports = function (Tag, Filter) {
var stream = {
init: function (tokens) {
this.tokens = tokens
this.handlers = {}
return this
},
on: function (name, cb) {
this.handlers[name] = cb
return this
},
trigger: function (event, arg) {
var h = this.handlers[event]
if (typeof h === 'function') {
h(arg)
return true
}
},
start: function () {
this.trigger('start')
var token
while (!this.stopRequested && (token = this.tokens.shift())) {
if (this.trigger('token', token)) continue
if (token.type === 'tag' &&
this.trigger(`tag:${token.name}`, token)) {
continue
}
};
function parse(tokens) {
var token, templates = [];
while (token = tokens.shift()) {
templates.push(parseToken(token, tokens));
}
return templates;
var template = parseToken(token, this.tokens)
this.trigger('template', template)
}
if (!this.stopRequested) this.trigger('end')
return this
},
stop: function () {
this.stopRequested = true
return this
}
}
function parseToken(token, tokens) {
try {
var tpl = null;
if (token.type === 'tag') {
tpl = parseTag(token, tokens);
} else if (token.type === 'output') {
tpl = parseOutput(token.value);
} else { // token.type === 'html'
tpl = token;
}
tpl.token = token;
return tpl;
} catch (e) {
throw new ParseError(e, token);
}
function parse (tokens) {
var token
var templates = []
while ((token = tokens.shift())) {
templates.push(parseToken(token, tokens))
}
return templates
}
function parseTag(token, tokens) {
if (token.name === 'continue' || token.name === 'break') return token;
return Tag.construct(token, tokens);
function parseToken (token, tokens) {
try {
var tpl = null
if (token.type === 'tag') {
tpl = parseTag(token, tokens)
} else if (token.type === 'output') {
tpl = parseOutput(token.value)
} else { // token.type === 'html'
tpl = token
}
tpl.token = token
return tpl
} catch (e) {
throw new ParseError(e, token)
}
}
function parseOutput(str) {
var match = lexical.matchValue(str);
assert(match, `illegal output string: ${str}`);
function parseTag (token, tokens) {
if (token.name === 'continue' || token.name === 'break') return token
return Tag.construct(token, tokens)
}
var initial = match[0];
str = str.substr(match.index + match[0].length);
function parseOutput (str) {
var match = lexical.matchValue(str)
assert(match, `illegal output string: ${str}`)
var filters = [];
while (match = lexical.filter.exec(str)) {
filters.push([match[0].trim()]);
}
var initial = match[0]
str = str.substr(match.index + match[0].length)
return {
type: 'output',
initial: initial,
filters: filters.map(str => Filter.construct(str))
};
}
function parseStream(tokens) {
var s = Object.create(stream);
return s.init(tokens);
var filters = []
while ((match = lexical.filter.exec(str))) {
filters.push([match[0].trim()])
}
return {
parse,
parseTag,
parseStream,
parseOutput
};
};
type: 'output',
initial: initial,
filters: filters.map(str => Filter.construct(str))
}
}
function parseStream (tokens) {
var s = Object.create(stream)
return s.init(tokens)
}
return {
parse,
parseTag,
parseStream,
parseOutput
}
}
+56 -56
View File
@@ -1,68 +1,68 @@
const Syntax = require('./syntax.js');
const Promise = require('any-promise');
const mapSeries = require('./util/promise.js').mapSeries;
const RenderBreakError = require('./util/error.js').RenderBreakError;
const RenderError = require('./util/error.js').RenderError;
const assert = require('./util/assert.js');
const Syntax = require('./syntax.js')
const Promise = require('any-promise')
const mapSeries = require('./util/promise.js').mapSeries
const RenderBreakError = require('./util/error.js').RenderBreakError
const RenderError = require('./util/error.js').RenderError
const assert = require('./util/assert.js')
var render = {
renderTemplates: function(templates, scope) {
assert(scope, 'unable to evalTemplates: scope undefined');
renderTemplates: function (templates, scope) {
assert(scope, 'unable to evalTemplates: scope undefined')
var html = '';
return mapSeries(templates, (tpl) => {
return renderTemplate.call(this, tpl)
.then(partial => html += partial)
.catch(e => {
if (e instanceof RenderBreakError) {
e.resolvedHTML = html;
throw e;
}
throw new RenderError(e, tpl);
});
}).then(() => html);
var html = ''
return mapSeries(templates, (tpl) => {
return renderTemplate.call(this, tpl)
.then(partial => (html += partial))
.catch(e => {
if (e instanceof RenderBreakError) {
e.resolvedHTML = html
throw e
}
throw new RenderError(e, tpl)
})
}).then(() => html)
function renderTemplate(template) {
if (template.type === 'tag') {
return this.renderTag(template, scope)
.then(partial => partial === undefined ? '' : partial);
} else if (template.type === 'output') {
return Promise.resolve()
function renderTemplate (template) {
if (template.type === 'tag') {
return this.renderTag(template, scope)
.then(partial => partial === undefined ? '' : partial)
} else if (template.type === 'output') {
return Promise.resolve()
.then(() => this.evalOutput(template, scope))
.then(partial => partial === undefined ? '' : stringify(partial));
} else { // template.type === 'html'
return Promise.resolve(template.value);
}
}
},
renderTag: function(template, scope) {
if (template.name === 'continue') {
return Promise.reject(new RenderBreakError('continue'));
}
if (template.name === 'break') {
return Promise.reject(new RenderBreakError('break'));
}
return template.render(scope);
},
evalOutput: function(template, scope) {
assert(scope, 'unable to evalOutput: scope undefined');
return template.filters.reduce(
(prev, filter) => filter.render(prev, scope),
Syntax.evalExp(template.initial, scope));
.then(partial => partial === undefined ? '' : stringify(partial))
} else { // template.type === 'html'
return Promise.resolve(template.value)
}
}
};
},
function factory() {
var instance = Object.create(render);
return instance;
renderTag: function (template, scope) {
if (template.name === 'continue') {
return Promise.reject(new RenderBreakError('continue'))
}
if (template.name === 'break') {
return Promise.reject(new RenderBreakError('break'))
}
return template.render(scope)
},
evalOutput: function (template, scope) {
assert(scope, 'unable to evalOutput: scope undefined')
return template.filters.reduce(
(prev, filter) => filter.render(prev, scope),
Syntax.evalExp(template.initial, scope))
}
}
function stringify(val) {
if (typeof val === 'string') return val;
return JSON.stringify(val);
function factory () {
var instance = Object.create(render)
return instance
}
module.exports = factory;
function stringify (val) {
if (typeof val === 'string') return val
return JSON.stringify(val)
}
module.exports = factory
+165 -169
View File
@@ -1,182 +1,178 @@
const _ = require('./util/underscore.js');
const lexical = require('./lexical.js');
const assert = require('./util/assert.js');
const toStr = Object.prototype.toString;
const _ = require('./util/underscore.js')
const lexical = require('./lexical.js')
const assert = require('./util/assert.js')
const toStr = Object.prototype.toString
var Scope = {
getAll: function() {
var ctx = {};
for (var i = this.scopes.length - 1; i >= 0; i--) {
_.assign(ctx, this.scopes[i]);
getAll: function () {
var ctx = {}
for (var i = this.scopes.length - 1; i >= 0; i--) {
_.assign(ctx, this.scopes[i])
}
return ctx
},
get: function (str) {
for (var i = this.scopes.length - 1; i >= 0; i--) {
try {
return this.getPropertyByPath(this.scopes[i], str)
} catch (e) {
if (/undefined variable/.test(e.message)) {
continue
}
return ctx;
},
get: function(str) {
for (var i = this.scopes.length - 1; i >= 0; i--) {
try {
return this.getPropertyByPath(this.scopes[i], str);
} catch (e) {
if (/undefined variable/.test(e.message)) {
continue;
}
if (/Cannot read property/.test(e.message)) {
if (this.opts.strict_variables) {
e.message += ': ' + str;
throw e;
} else {
continue;
}
} else {
e.message += ': ' + str;
throw e;
}
}
if (/Cannot read property/.test(e.message)) {
if (this.opts.strict_variables) {
e.message += ': ' + str
throw e
} else {
continue
}
} else {
e.message += ': ' + str
throw e
}
if (this.opts.strict_variables) {
throw new TypeError('undefined variable: ' + str);
}
}
if (this.opts.strict_variables) {
throw new TypeError('undefined variable: ' + str)
}
},
set: function (k, v) {
this.setPropertyByPath(this.scopes[this.scopes.length - 1], k, v)
return this
},
push: function (ctx) {
assert(ctx, `trying to push ${ctx} into scopes`)
return this.scopes.push(ctx)
},
pop: function () {
return this.scopes.pop()
},
unshift: function (ctx) {
assert(ctx, `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)
}
},
set: function(k, v) {
this.setPropertyByPath(this.scopes[this.scopes.length - 1], k, v);
return this;
},
push: function(ctx) {
assert(ctx, `trying to push ${ctx} into scopes`);
return this.scopes.push(ctx);
},
pop: function() {
return this.scopes.pop();
},
unshift: function(ctx) {
assert(ctx, `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] = {};
if (undefined === obj[key]) obj[key] = {}
// case for readonly objects
obj = obj[key] || {};
}
}
},
getPropertyByPath: function(obj, path) {
var paths = this.propertyAccessSeq(path + '');
var varName = paths.shift();
if (!obj.hasOwnProperty(varName)) {
throw new TypeError('undefined variable');
}
var variable = obj[varName];
var lastName = paths.pop();
paths.forEach(p => variable = variable[p]);
if (undefined !== lastName) {
if (lastName === 'size' &&
(toStr.call(variable) === '[object Array]'
|| toStr.call(variable) === '[object String]')) {
return variable.length;
}
variable = variable[lastName]
}
return variable;
},
/*
* 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);
assert(j !== -1, `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 {
j = str.indexOf(delemiter, i + 2);
assert(j !== -1, `unbalanced ${delemiter}: ${str}`);
name = str.slice(i + 2, j);
seq.push(name);
name = '';
i = j + 2;
}
}
// foo.bar
else if (str[i] === ".") {
seq.push(name);
name = '';
}
//foo.bar
else {
name += str[i];
}
}
if (name.length) seq.push(name);
return seq;
obj = obj[key] || {}
}
}
};
},
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;
}
}
getPropertyByPath: function (obj, path) {
var paths = this.propertyAccessSeq(path + '')
var varName = paths.shift()
if (!obj.hasOwnProperty(varName)) {
throw new TypeError('undefined variable')
}
return -1;
var variable = obj[varName]
var lastName = paths.pop()
paths.forEach(p => (variable = variable[p]))
if (undefined !== lastName) {
if (lastName === 'size' &&
(toStr.call(variable) === '[object Array]' ||
toStr.call(variable) === '[object String]')) {
return variable.length
}
variable = variable[lastName]
}
return variable
},
/*
* 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 = []
var name = ''
for (var i = 0; i < str.length; i++) {
if (str[i] === '[') {
seq.push(name)
name = ''
var delemiter = str[i + 1]
if (delemiter !== "'" && delemiter !== '"') {
// foo[bar.coo]
var j = matchRightBracket(str, i + 1)
assert(j !== -1, `unbalanced []: ${str}`)
name = str.slice(i + 1, j)
if (lexical.isInteger(name)) {
// foo[1]
seq.push(name)
} else {
// foo["bar"]
seq.push(this.get(name))
}
name = ''
i = j
} else {
// foo["bar"]
j = str.indexOf(delemiter, i + 2)
assert(j !== -1, `unbalanced ${delemiter}: ${str}`)
name = str.slice(i + 2, j)
seq.push(name)
name = ''
i = j + 2
}
} else if (str[i] === '.') {
// foo.bar
seq.push(name)
name = ''
} else {
// foo.bar
name += str[i]
}
}
if (name.length) seq.push(name)
return seq
}
}
exports.factory = function(ctx, opts) {
opts = _.assign({
strict_variables: false,
strict_filters: false,
blocks: {},
root: []
}, opts);
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
}
ctx = _.assign(ctx, {
liquid: opts
});
exports.factory = function (ctx, opts) {
opts = _.assign({
strict_variables: false,
strict_filters: false,
blocks: {},
root: []
}, opts)
var scope = Object.create(Scope);
scope.opts = opts;
scope.scopes = [ctx];
return scope;
};
ctx = _.assign(ctx, {
liquid: opts
})
var scope = Object.create(Scope)
scope.opts = opts
scope.scopes = [ctx]
return scope
}
+40 -40
View File
@@ -1,55 +1,55 @@
const operators = require('./operators.js');
const lexical = require('./lexical.js');
const assert = require('../src/util/assert.js');
const operators = require('./operators.js')
const lexical = require('./lexical.js')
const assert = require('../src/util/assert.js')
function evalExp(exp, scope) {
assert(scope, 'unable to evalExp: scope undefined');
var operatorREs = lexical.operators,
match;
for (var i = 0; i < operatorREs.length; i++) {
var operatorRE = operatorREs[i];
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`);
if (match = exp.match(expRE)) {
var l = evalExp(match[1], scope);
var op = operators[match[2].trim()];
var r = evalExp(match[3], scope);
return op(l, r);
}
function evalExp (exp, scope) {
assert(scope, 'unable to evalExp: scope undefined')
var operatorREs = lexical.operators
var match
for (var i = 0; i < operatorREs.length; i++) {
var operatorRE = operatorREs[i]
var expRE = new RegExp(`^(${lexical.quoteBalanced.source})(${operatorRE.source})(${lexical.quoteBalanced.source})$`)
if ((match = exp.match(expRE))) {
var l = evalExp(match[1], scope)
var op = operators[match[2].trim()]
var r = evalExp(match[3], scope)
return op(l, r)
}
}
if (match = exp.match(lexical.rangeLine)) {
var low = evalValue(match[1], scope),
high = evalValue(match[2], scope);
var range = [];
for (var j = low; j <= high; j++) {
range.push(j);
}
return range;
if ((match = exp.match(lexical.rangeLine))) {
var low = evalValue(match[1], scope)
var high = evalValue(match[2], scope)
var range = []
for (var j = low; j <= high; j++) {
range.push(j)
}
return range
}
return evalValue(exp, scope);
return evalValue(exp, scope)
}
function evalValue(str, scope) {
str = str && str.trim();
if (!str) return undefined;
function evalValue (str, scope) {
str = str && str.trim()
if (!str) return undefined
if (lexical.isLiteral(str)) {
return lexical.parseLiteral(str);
}
if (lexical.isVariable(str)) {
return scope.get(str);
}
if (lexical.isLiteral(str)) {
return lexical.parseLiteral(str)
}
if (lexical.isVariable(str)) {
return scope.get(str)
}
}
function isTruthy(val) {
return !isFalsy(val);
function isTruthy (val) {
return !isFalsy(val)
}
function isFalsy(val) {
return false === val || undefined === val || null === val;;
function isFalsy (val) {
return val === false || undefined === val || val === null
}
module.exports = {
evalExp, evalValue, isTruthy, isFalsy
};
evalExp, evalValue, isTruthy, isFalsy
}
+64 -64
View File
@@ -1,73 +1,73 @@
const lexical = require('./lexical.js');
const _ = require('./util/underscore.js');
const Promise = require('any-promise');
const Syntax = require('./syntax.js');
const assert = require('./util/assert.js');
const lexical = require('./lexical.js')
const _ = require('./util/underscore.js')
const Promise = require('any-promise')
const Syntax = require('./syntax.js')
const assert = require('./util/assert.js')
function hash(markup, scope) {
var obj = {},
match;
lexical.hashCapture.lastIndex = 0;
while (match = lexical.hashCapture.exec(markup)) {
var k = match[1],
v = match[2];
obj[k] = Syntax.evalValue(v, scope);
}
return obj;
function hash (markup, scope) {
var obj = {}
var match
lexical.hashCapture.lastIndex = 0
while ((match = lexical.hashCapture.exec(markup))) {
var k = match[1]
var v = match[2]
obj[k] = Syntax.evalValue(v, scope)
}
return obj
}
module.exports = function() {
var tagImpls = {};
module.exports = function () {
var tagImpls = {}
var _tagInstance = {
render: function(scope) {
var obj = hash(this.token.args, scope);
var impl = this.tagImpl;
if (typeof impl.render !== 'function') {
return Promise.resolve('');
}
return Promise.resolve()
.then(() => typeof impl.render === 'function' ?
impl.render(scope, obj) : '')
.catch(function(e) {
if (_.isError(e)) {
throw e;
}
var msg = `Please reject with an Error in ${impl.render}, got ${e}`;
throw new Error(msg);
});
},
parse: function(token, tokens) {
this.type = 'tag';
this.token = token;
this.name = token.name;
var _tagInstance = {
render: function (scope) {
var obj = hash(this.token.args, scope)
var impl = this.tagImpl
if (typeof impl.render !== 'function') {
return Promise.resolve('')
}
return Promise.resolve()
.then(() => typeof impl.render === 'function'
? impl.render(scope, obj) : '')
.catch(function (e) {
if (_.isError(e)) {
throw e
}
var msg = `Please reject with an Error in ${impl.render}, got ${e}`
throw new Error(msg)
})
},
parse: function (token, tokens) {
this.type = 'tag'
this.token = token
this.name = token.name
var tagImpl = tagImpls[this.name];
assert(tagImpl, `tag ${this.name} not found`);
this.tagImpl = Object.create(tagImpl);
if (this.tagImpl.parse) {
this.tagImpl.parse(token, tokens);
}
}
};
function register(name, tag) {
tagImpls[name] = tag;
var tagImpl = tagImpls[this.name]
assert(tagImpl, `tag ${this.name} not found`)
this.tagImpl = Object.create(tagImpl)
if (this.tagImpl.parse) {
this.tagImpl.parse(token, tokens)
}
}
}
function construct(token, tokens) {
var instance = Object.create(_tagInstance);
instance.parse(token, tokens);
return instance;
}
function register (name, tag) {
tagImpls[name] = tag
}
function clear() {
tagImpls = {};
}
function construct (token, tokens) {
var instance = Object.create(_tagInstance)
instance.parse(token, tokens)
return instance
}
return {
construct,
register,
clear
};
};
function clear () {
tagImpls = {}
}
return {
construct,
register,
clear
}
}
+77 -77
View File
@@ -1,92 +1,92 @@
const lexical = require('./lexical.js');
const TokenizationError = require('./util/error.js').TokenizationError;
const _ = require('./util/underscore.js');
const assert = require('../src/util/assert.js');
const lexical = require('./lexical.js')
const TokenizationError = require('./util/error.js').TokenizationError
const _ = require('./util/underscore.js')
const assert = require('../src/util/assert.js')
function parse(html, filepath, options) {
assert(_.isString(html), 'illegal input type');
function parse (html, filepath, options) {
assert(_.isString(html), 'illegal input type')
html = whiteSpaceCtrl(html, options);
html = whiteSpaceCtrl(html, options)
var tokens = [];
var syntax = /({%-?([\s\S]*?)-?%})|({{([\s\S]*?)}})/g;
var result, htmlFragment, token;
var lastMatchEnd = 0, lastMatchBegin = -1, parsedLinesCount = 0;
var tokens = []
var syntax = /({%-?([\s\S]*?)-?%})|({{([\s\S]*?)}})/g
var result, htmlFragment, token
var lastMatchEnd = 0
var lastMatchBegin = -1
var parsedLinesCount = 0
while ((result = syntax.exec(html)) !== null) {
while ((result = syntax.exec(html)) !== null) {
// passed html fragments
if (result.index > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, result.index);
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
});
}
// tag appeared
if (result[1]) {
token = factory('tag', 1, result);
var match = token.value.match(lexical.tagLine);
if (!match) {
throw new TokenizationError(`illegal tag syntax`, token);
}
token.name = match[1];
token.args = match[2];
tokens.push(token);
}
// output
else { token = factory('output', 3, result);
tokens.push(token);
}
lastMatchEnd = syntax.lastIndex;
if (result.index > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, result.index)
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
})
}
if (result[1]) {
// tag appeared
token = factory('tag', 1, result)
var match = token.value.match(lexical.tagLine)
if (!match) {
throw new TokenizationError(`illegal tag syntax`, token)
}
token.name = match[1]
token.args = match[2]
tokens.push(token)
} else {
// output
token = factory('output', 3, result)
tokens.push(token)
}
lastMatchEnd = syntax.lastIndex
}
// remaining html
if (html.length > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, html.length);
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
});
}
return tokens;
if (html.length > lastMatchEnd) {
htmlFragment = html.slice(lastMatchEnd, html.length)
tokens.push({
type: 'html',
raw: htmlFragment,
value: htmlFragment
})
}
return tokens
function factory(type, offset, match) {
return {
type: type,
raw: match[offset],
value: match[offset + 1].trim(),
line: getLineNum(match),
input: html,
file: filepath
};
function factory (type, offset, match) {
return {
type: type,
raw: match[offset],
value: match[offset + 1].trim(),
line: getLineNum(match),
input: html,
file: filepath
}
}
function getLineNum(match) {
var lines = match.input.slice(lastMatchBegin + 1, match.index).split('\n');
parsedLinesCount += lines.length - 1;
lastMatchBegin = match.index;
return parsedLinesCount + 1;
}
function getLineNum (match) {
var lines = match.input.slice(lastMatchBegin + 1, match.index).split('\n')
parsedLinesCount += lines.length - 1
lastMatchBegin = match.index
return parsedLinesCount + 1
}
}
function whiteSpaceCtrl(html, options){
options = options || {};
if(options.trim_left) {
html = html.replace(/{%-?/g, '{%-');
}
if(options.trim_right) {
html = html.replace(/-?%}/g, '-%}');
}
var rLeft = options.greedy ? /\s+({%-)/g : /[\t\r ]*({%-)/g;
var rRight = options.greedy ? /(-%})\s+/g : /(-%})[\t\r ]*\n?/g;
return html.replace(rLeft, '$1').replace(rRight, '$1');
function whiteSpaceCtrl (html, options) {
options = options || {}
if (options.trim_left) {
html = html.replace(/{%-?/g, '{%-')
}
if (options.trim_right) {
html = html.replace(/-?%}/g, '-%}')
}
var rLeft = options.greedy ? /\s+({%-)/g : /[\t\r ]*({%-)/g
var rRight = options.greedy ? /(-%})\s+/g : /(-%})[\t\r ]*\n?/g
return html.replace(rLeft, '$1').replace(rRight, '$1')
}
exports.parse = parse;
exports.whiteSpaceCtrl = whiteSpaceCtrl;
exports.parse = parse
exports.whiteSpaceCtrl = whiteSpaceCtrl
+9 -9
View File
@@ -1,13 +1,13 @@
const AssertionError = require('./error.js').AssertionError;
const AssertionError = require('./error.js').AssertionError
function assert(predicate, message) {
if (!predicate) {
if (message instanceof Error) {
throw message;
}
var message = message || `expect ${predicate} to be true`;
throw new AssertionError(message);
function assert (predicate, message) {
if (!predicate) {
if (message instanceof Error) {
throw message
}
message = message || `expect ${predicate} to be true`
throw new AssertionError(message)
}
}
module.exports = assert;
module.exports = assert
+88 -88
View File
@@ -1,118 +1,118 @@
const _ = require('./underscore.js');
const _ = require('./underscore.js')
function TokenizationError(message, token) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
function TokenizationError (message, token) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
}
this.name = this.constructor.name
this.input = token.input;
this.line = token.line;
this.file = token.file;
this.input = token.input
this.line = token.line
this.file = token.file
var context = mkContext(token.input, token.line);
this.message = mkMessage(message, token);
this.stack = context + '\n' + (this.stack || '');
var context = mkContext(token.input, token.line)
this.message = mkMessage(message, token)
this.stack = context + '\n' + (this.stack || '')
}
TokenizationError.prototype = Object.create(Error.prototype);
TokenizationError.prototype.constructor = TokenizationError;
TokenizationError.prototype = Object.create(Error.prototype)
TokenizationError.prototype.constructor = TokenizationError
function ParseError(e, token) {
_.assign(this, e);
this.originalError = e;
this.name = this.constructor.name;
function ParseError (e, token) {
_.assign(this, e)
this.originalError = e
this.name = this.constructor.name
this.input = token.input;
this.line = token.line;
this.file = token.file;
this.input = token.input
this.line = token.line
this.file = token.file
var context = mkContext(token.input, token.line);
this.message = mkMessage(e.message || 'Unkown Error', token);
this.stack = context + '\n' + (e.stack || '');
var context = mkContext(token.input, token.line)
this.message = mkMessage(e.message || 'Unkown Error', token)
this.stack = context + '\n' + (e.stack || '')
}
ParseError.prototype = Object.create(Error.prototype);
ParseError.prototype.constructor = ParseError;
ParseError.prototype = Object.create(Error.prototype)
ParseError.prototype.constructor = ParseError
function RenderError(e, tpl) {
function RenderError (e, tpl) {
// return the original render error
if(e instanceof RenderError){
return e;
}
_.assign(this, e);
this.originalError = e;
this.name = this.constructor.name;
if (e instanceof RenderError) {
return e
}
_.assign(this, e)
this.originalError = e
this.name = this.constructor.name
this.input = tpl.token.input;
this.line = tpl.token.line;
this.file = tpl.token.file;
this.input = tpl.token.input
this.line = tpl.token.line
this.file = tpl.token.file
var context = mkContext(tpl.token.input, tpl.token.line);
this.message = mkMessage(e.message || 'Unkown Error', tpl.token);
this.stack = context + '\n' + (e.stack || '');
var context = mkContext(tpl.token.input, tpl.token.line)
this.message = mkMessage(e.message || 'Unkown Error', tpl.token)
this.stack = context + '\n' + (e.stack || '')
}
RenderError.prototype = Object.create(Error.prototype);
RenderError.prototype.constructor = RenderError;
RenderError.prototype = Object.create(Error.prototype)
RenderError.prototype.constructor = RenderError
function RenderBreakError(message) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
this.message = message || '';
function RenderBreakError (message) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
}
this.name = this.constructor.name
this.message = message || ''
}
RenderBreakError.prototype = Object.create(Error.prototype);
RenderBreakError.prototype.constructor = RenderBreakError;
RenderBreakError.prototype = Object.create(Error.prototype)
RenderBreakError.prototype.constructor = RenderBreakError
function AssertionError(message) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
this.message = message;
function AssertionError (message) {
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
}
this.name = this.constructor.name
this.message = message
}
AssertionError.prototype = Object.create(Error.prototype);
AssertionError.prototype.constructor = AssertionError;
AssertionError.prototype = Object.create(Error.prototype)
AssertionError.prototype.constructor = AssertionError
function mkContext(input, line) {
var lines = input.split('\n');
var begin = Math.max(line - 2, 1);
var end = Math.min(line + 3, lines.length);
function mkContext (input, line) {
var lines = input.split('\n')
var begin = Math.max(line - 2, 1)
var end = Math.min(line + 3, lines.length)
var context = _
var context = _
.range(begin, end + 1)
.map(l => [
(l === line) ? '>> ' : ' ',
align(l, end),
'| ',
lines[l - 1]
(l === line) ? '>> ' : ' ',
align(l, end),
'| ',
lines[l - 1]
].join(''))
.join('\n');
.join('\n')
return context;
return context
}
function align(n, max) {
var length = (max + '').length;
var str = n + '';
var blank = Array(length - str.length).join(' ');
return blank + str;
function align (n, max) {
var length = (max + '').length
var str = n + ''
var blank = Array(length - str.length).join(' ')
return blank + str
}
function mkMessage(msg, token){
msg = msg || '';
if(token.file){
msg += ', file:' + token.file;
}
if(token.line){
msg += ', line:' + token.line;
}
return msg;
function mkMessage (msg, token) {
msg = msg || ''
if (token.file) {
msg += ', file:' + token.file
}
if (token.line) {
msg += ', line:' + token.line
}
return msg
}
module.exports = {
TokenizationError,
ParseError,
RenderBreakError,
AssertionError,
RenderError
};
TokenizationError,
ParseError,
RenderBreakError,
AssertionError,
RenderError
}
+14 -14
View File
@@ -1,20 +1,20 @@
const fs = require('fs');
const fs = require('fs')
function readFileAsync(filepath) {
return new Promise(function(resolve, reject) {
fs.readFile(filepath, 'utf8', function(err, content) {
err ? reject(err) : resolve(content);
});
});
function readFileAsync (filepath) {
return new Promise(function (resolve, reject) {
fs.readFile(filepath, 'utf8', function (err, content) {
err ? reject(err) : resolve(content)
})
})
};
function statFileAsync(path) {
return new Promise(function(resolve, reject) {
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
});
function statFileAsync (path) {
return new Promise(function (resolve, reject) {
fs.stat(path, (err, stat) => err ? reject(err) : resolve(stat))
})
};
module.exports = {
readFileAsync,
statFileAsync
};
readFileAsync,
statFileAsync
}
+17 -17
View File
@@ -1,4 +1,4 @@
const Promise = require('any-promise');
const Promise = require('any-promise')
/*
* Call functions in serial until someone resolved.
@@ -6,12 +6,12 @@ const Promise = require('any-promise');
* @param {Array} iteratee returns a new promise.
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function anySeries(iterable, iteratee) {
var ret = Promise.reject(new Error('init'));
iterable.forEach(function(item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable));
});
return ret;
function anySeries (iterable, iteratee) {
var ret = Promise.reject(new Error('init'))
iterable.forEach(function (item, idx) {
ret = ret.catch(e => iteratee(item, idx, iterable))
})
return ret
}
/*
@@ -20,16 +20,16 @@ function anySeries(iterable, iteratee) {
* @param {Array} iteratee returns a new promise.
* The iteratee is invoked with three arguments: (value, index, iterable).
*/
function mapSeries(iterable, iteratee) {
var ret = Promise.resolve('init');
var result = [];
iterable.forEach(function(item, idx) {
ret = ret
function mapSeries (iterable, iteratee) {
var ret = Promise.resolve('init')
var result = []
iterable.forEach(function (item, idx) {
ret = ret
.then(() => iteratee(item, idx, iterable))
.then(x => result.push(x));
});
return ret.then(() => result);
.then(x => result.push(x))
})
return ret.then(() => result)
}
exports.anySeries = anySeries;
exports.mapSeries = mapSeries;
exports.anySeries = anySeries
exports.mapSeries = mapSeries
+180 -181
View File
@@ -1,200 +1,199 @@
var monthNames = [
"January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"
];
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'
]
var monthNamesShort = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec"
];
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'
]
var dayNames = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
];
var dayNamesShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
]
var dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
var suffixes = {
1: 'st',
2: 'nd',
3: 'rd',
'default': 'th'
};
1: 'st',
2: 'nd',
3: 'rd',
'default': 'th'
}
// prototype extensions
var _date = {
daysInMonth: function(d) {
var feb = _date.isLeapYear(d) ? 29 : 28;
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
},
daysInMonth: function (d) {
var feb = _date.isLeapYear(d) ? 29 : 28
return [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
},
getDayOfYear: function(d) {
var num = 0;
for (var i = 0; i < d.getMonth(); ++i) {
num += _date.daysInMonth(d)[i];
}
return num + d.getDate();
},
// Startday is an integer of which day to start the week measuring from
// TODO: that comment was retarted. fix it.
getWeekOfYear: function(d, startDay) {
// Skip to startDay of this week
var now = this.getDayOfYear(d) + (startDay - d.getDay());
// Find the first startDay of the year
var jan1 = new Date(d.getFullYear(), 0, 1);
var then = (7 - jan1.getDay() + startDay);
return _number.pad(Math.floor((now - then) / 7) + 1, 2);
},
isLeapYear: function(d) {
var year = d.getFullYear();
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
},
getSuffix: function(d) {
var str = d.getDate().toString();
var index = parseInt(str.slice(-1));
return suffixes[index] || suffixes['default'];
},
century: function(d) {
return parseInt(d.getFullYear().toString().substring(0, 2), 10);
getDayOfYear: function (d) {
var num = 0
for (var i = 0; i < d.getMonth(); ++i) {
num += _date.daysInMonth(d)[i]
}
};
return num + d.getDate()
},
// Startday is an integer of which day to start the week measuring from
// TODO: that comment was retarted. fix it.
getWeekOfYear: function (d, startDay) {
// Skip to startDay of this week
var now = this.getDayOfYear(d) + (startDay - d.getDay())
// Find the first startDay of the year
var jan1 = new Date(d.getFullYear(), 0, 1)
var then = (7 - jan1.getDay() + startDay)
return _number.pad(Math.floor((now - then) / 7) + 1, 2)
},
isLeapYear: function (d) {
var year = d.getFullYear()
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)))
},
getSuffix: function (d) {
var str = d.getDate().toString()
var index = parseInt(str.slice(-1))
return suffixes[index] || suffixes['default']
},
century: function (d) {
return parseInt(d.getFullYear().toString().substring(0, 2), 10)
}
}
var _number = {
pad: function(value, size, ch) {
if (!ch) ch = '0';
var result = value.toString();
var pad = size - result.length;
pad: function (value, size, ch) {
if (!ch) ch = '0'
var result = value.toString()
var pad = size - result.length
while (pad-- > 0) {
result = ch + result;
}
return result;
while (pad-- > 0) {
result = ch + result
}
};
return result
}
}
var format_codes = {
a: function(d) {
return dayNamesShort[d.getDay()];
},
A: function(d) {
return dayNames[d.getDay()];
},
b: function(d) {
return monthNamesShort[d.getMonth()];
},
B: function(d) {
return monthNames[d.getMonth()];
},
c: function(d) {
return d.toLocaleString();
},
C: function(d) {
return _date.century(d);
},
d: function(d) {
return _number.pad(d.getDate(), 2);
},
e: function(d) {
return _number.pad(d.getDate(), 2, ' ');
},
H: function(d) {
return _number.pad(d.getHours(), 2);
},
I: function(d) {
return _number.pad(d.getHours() % 12 || 12, 2);
},
j: function(d) {
return _number.pad(_date.getDayOfYear(d), 3);
},
k: function(d) {
return _number.pad(d.getHours(), 2, ' ');
},
l: function(d) {
return _number.pad(d.getHours() % 12 || 12, 2, ' ');
},
L: function(d) {
return _number.pad(d.getMilliseconds(), 3);
},
m: function(d) {
return _number.pad(d.getMonth() + 1, 2);
},
M: function(d) {
return _number.pad(d.getMinutes(), 2);
},
p: function(d) {
return (d.getHours() < 12 ? 'AM' : 'PM');
},
P: function(d) {
return (d.getHours() < 12 ? 'am' : 'pm');
},
q: function(d) {
return _date.getSuffix(d);
},
s: function(d) {
return Math.round(d.valueOf() / 1000);
},
S: function(d) {
return _number.pad(d.getSeconds(), 2);
},
u: function(d) {
return d.getDay() || 7;
},
U: function(d) {
return _date.getWeekOfYear(d, 0);
},
w: function(d) {
return d.getDay();
},
W: function(d) {
return _date.getWeekOfYear(d, 1);
},
x: function(d) {
return d.toLocaleDateString();
},
X: function(d) {
return d.toLocaleTimeString();
},
y: function(d) {
return d.getFullYear().toString().substring(2, 4);
},
Y: function(d) {
return d.getFullYear();
},
z: function(d) {
var tz = d.getTimezoneOffset() / 60 * 100;
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4);
},
"%": function() {
return '%';
var formatCodes = {
a: function (d) {
return dayNamesShort[d.getDay()]
},
A: function (d) {
return dayNames[d.getDay()]
},
b: function (d) {
return monthNamesShort[d.getMonth()]
},
B: function (d) {
return monthNames[d.getMonth()]
},
c: function (d) {
return d.toLocaleString()
},
C: function (d) {
return _date.century(d)
},
d: function (d) {
return _number.pad(d.getDate(), 2)
},
e: function (d) {
return _number.pad(d.getDate(), 2, ' ')
},
H: function (d) {
return _number.pad(d.getHours(), 2)
},
I: function (d) {
return _number.pad(d.getHours() % 12 || 12, 2)
},
j: function (d) {
return _number.pad(_date.getDayOfYear(d), 3)
},
k: function (d) {
return _number.pad(d.getHours(), 2, ' ')
},
l: function (d) {
return _number.pad(d.getHours() % 12 || 12, 2, ' ')
},
L: function (d) {
return _number.pad(d.getMilliseconds(), 3)
},
m: function (d) {
return _number.pad(d.getMonth() + 1, 2)
},
M: function (d) {
return _number.pad(d.getMinutes(), 2)
},
p: function (d) {
return (d.getHours() < 12 ? 'AM' : 'PM')
},
P: function (d) {
return (d.getHours() < 12 ? 'am' : 'pm')
},
q: function (d) {
return _date.getSuffix(d)
},
s: function (d) {
return Math.round(d.valueOf() / 1000)
},
S: function (d) {
return _number.pad(d.getSeconds(), 2)
},
u: function (d) {
return d.getDay() || 7
},
U: function (d) {
return _date.getWeekOfYear(d, 0)
},
w: function (d) {
return d.getDay()
},
W: function (d) {
return _date.getWeekOfYear(d, 1)
},
x: function (d) {
return d.toLocaleDateString()
},
X: function (d) {
return d.toLocaleTimeString()
},
y: function (d) {
return d.getFullYear().toString().substring(2, 4)
},
Y: function (d) {
return d.getFullYear()
},
z: function (d) {
var tz = d.getTimezoneOffset() / 60 * 100
return (tz > 0 ? '-' : '+') + _number.pad(Math.abs(tz), 4)
},
'%': function () {
return '%'
}
}
formatCodes.h = formatCodes.b
formatCodes.N = formatCodes.L
var strftime = function (d, format) {
var output = ''
var remaining = format
while (true) {
var r = /%./g
var results = r.exec(remaining)
// No more format codes. Add the remaining text and return
if (!results) {
return output + remaining
}
};
format_codes.h = format_codes.b;
format_codes.N = format_codes.L;
var strftime = function(d, format) {
var output = '';
var remaining = format;
// Add the preceding text
output += remaining.slice(0, r.lastIndex - 2)
remaining = remaining.slice(r.lastIndex)
while (true) {
var r = /%./g;
var results = r.exec(remaining);
// Add the format code
var ch = results[0].charAt(1)
var func = formatCodes[ch]
output += func ? func.call(this, d) : '%' + ch
}
}
// No more format codes. Add the remaining text and return
if (!results) {
return output + remaining;
}
// Add the preceding text
output += remaining.slice(0, r.lastIndex - 2);
remaining = remaining.slice(r.lastIndex);
// Add the format code
var ch = results[0].charAt(1);
var func = format_codes[ch];
output += func ? func.call(this, d) : '%' + ch;
}
};
module.exports = strftime;
module.exports = strftime
+65 -66
View File
@@ -3,15 +3,15 @@
* @param {any} value The value to check.
* @return {Boolean} Returns true if value is a string, else false.
*/
function isString(value) {
return value instanceof String || typeof value === 'string';
function isString (value) {
return value instanceof String || typeof value === 'string'
}
function isError(value) {
var signature = Object.prototype.toString.call(value);
function isError (value) {
var signature = Object.prototype.toString.call(value)
// [object XXXError]
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message == 'string' && typeof value.name == 'string');
return signature.substr(-6, 5) === 'Error' ||
(typeof value.message === 'string' && typeof value.name === 'string')
}
/*
@@ -22,14 +22,14 @@ function isError(value) {
* @param {Function} iteratee The function invoked per iteration.
* @return {Object} Returns object.
*/
function forOwn(object, iteratee) {
object = object || {};
for (var k in object) {
if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break;
}
function forOwn (object, iteratee) {
object = object || {}
for (var k in object) {
if (object.hasOwnProperty(k)) {
if (iteratee(object[k], k, object) === false) break
}
return object;
}
return object
}
/*
@@ -43,46 +43,45 @@ function forOwn(object, iteratee) {
* @param {...Object} sources The source objects.
* @return {Object} Returns object.
*/
function assign(object) {
object = isObject(object) ? object : {};
var srcs = Array.prototype.slice.call(arguments, 1);
srcs.forEach(function(src) {
_assignBinary(object, src);
});
return object;
function assign (object) {
object = isObject(object) ? object : {}
var srcs = Array.prototype.slice.call(arguments, 1)
srcs.forEach(function (src) {
_assignBinary(object, src)
})
return object
}
function _assignBinary(dst, src) {
if (!dst) return dst;
forOwn(src, function(v, k) {
dst[k] = v;
});
return dst;
function _assignBinary (dst, src) {
if (!dst) return dst
forOwn(src, function (v, k) {
dst[k] = v
})
return dst
}
function isArray(value) {
return value instanceof Array;
function isArray (value) {
return value instanceof Array
}
function echo(prefix) {
return v => {
console.log('[' + prefix + ']', v);
return v;
};
function echo (prefix) {
return v => {
console.log('[' + prefix + ']', v)
return v
}
}
function uniq(arr) {
var u = {},
a = [];
for (var i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) {
continue;
}
a.push(arr[i]);
u[arr[i]] = 1;
function uniq (arr) {
var u = {}
var a = []
for (var i = 0, l = arr.length; i < l; ++i) {
if (u.hasOwnProperty(arr[i])) {
continue
}
return a;
a.push(arr[i])
u[arr[i]] = 1
}
return a
}
/*
@@ -91,8 +90,8 @@ function uniq(arr) {
* @param {any} value The value to check.
* @return {Boolean} Returns true if value is an object, else false.
*/
function isObject(value) {
return value !== null && typeof value === 'object';
function isObject (value) {
return value !== null && typeof value === 'object'
}
/*
@@ -103,29 +102,29 @@ function isObject(value) {
* Note that ranges that stop before they start are considered to be zero-length instead of
* negative — if you'd like a negative range, use a negative step.
*/
function range(start, stop, step) {
if (arguments.length === 1) {
stop = start;
start = 0;
}
step = step || 1;
function range (start, stop, step) {
if (arguments.length === 1) {
stop = start
start = 0
}
step = step || 1
var arr = [];
for (var i = start; i < stop; i += step) {
arr.push(i);
}
return arr;
var arr = []
for (var i = start; i < stop; i += step) {
arr.push(i)
}
return arr
}
exports.isString = isString;
exports.isArray = isArray;
exports.isObject = isObject;
exports.isError = isError;
exports.isString = isString
exports.isArray = isArray
exports.isObject = isObject
exports.isError = isError
exports.range = range;
exports.range = range
exports.forOwn = forOwn;
exports.assign = assign;
exports.uniq = uniq;
exports.forOwn = forOwn
exports.assign = assign
exports.uniq = uniq
exports.echo = echo;
exports.echo = echo
+76 -75
View File
@@ -1,91 +1,92 @@
const Liquid = require('..');
const lexical = Liquid.lexical;
const mapSeries = require('../src/util/promise.js').mapSeries;
const RenderBreakError = Liquid.Types.RenderBreakError;
const assert = require('../src/util/assert.js');
const Liquid = require('..')
const lexical = Liquid.lexical
const mapSeries = require('../src/util/promise.js').mapSeries
const RenderBreakError = Liquid.Types.RenderBreakError
const assert = require('../src/util/assert.js')
const re = new RegExp(`^(${lexical.identifier.source})\\s+in\\s+` +
`(${lexical.value.source})` +
`(?:\\s+${lexical.hash.source})*` +
`(?:\\s+(reversed))?` +
`(?:\\s+${lexical.hash.source})*$`);
`(?:\\s+${lexical.hash.source})*$`)
module.exports = function(liquid) {
liquid.registerTag('for', {
module.exports = function (liquid) {
liquid.registerTag('for', {
parse: function(tagToken, remainTokens) {
var match = re.exec(tagToken.args);
assert(match, `illegal tag: ${tagToken.raw}`);
this.variable = match[1];
this.collection = match[2];
this.reversed = !!match[3];
parse: function (tagToken, remainTokens) {
var match = re.exec(tagToken.args)
assert(match, `illegal tag: ${tagToken.raw}`)
this.variable = match[1]
this.collection = match[2]
this.reversed = !!match[3]
this.templates = [];
this.elseTemplates = [];
this.templates = []
this.elseTemplates = []
var p, stream = liquid.parser.parseStream(remainTokens)
.on('start', () => p = this.templates)
.on('tag:else', () => p = this.elseTemplates)
.on('tag:endfor', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
var p
var stream = liquid.parser.parseStream(remainTokens)
.on('start', () => (p = this.templates))
.on('tag:else', () => (p = this.elseTemplates))
.on('tag:endfor', () => stream.stop())
.on('template', tpl => p.push(tpl))
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start();
},
stream.start()
},
render: function(scope, hash) {
var collection = Liquid.evalExp(this.collection, scope);
render: function (scope, hash) {
var collection = Liquid.evalExp(this.collection, scope)
if (!Array.isArray(collection) ||
if (!Array.isArray(collection) ||
(Array.isArray(collection) && collection.length === 0)) {
return liquid.renderer.renderTemplates(this.elseTemplates, scope);
}
return liquid.renderer.renderTemplates(this.elseTemplates, scope)
}
var length = collection.length;
var offset = hash.offset || 0;
var limit = (hash.limit === undefined) ? collection.length : hash.limit;
var length = collection.length
var offset = hash.offset || 0
var limit = (hash.limit === undefined) ? collection.length : hash.limit
collection = collection.slice(offset, offset + limit);
if (this.reversed) collection.reverse();
collection = collection.slice(offset, offset + limit)
if (this.reversed) collection.reverse()
var contexts = collection.map((item, i) => {
var ctx = {};
ctx[this.variable] = item;
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === length - 1,
length: length,
rindex: length - i,
rindex0: length - i - 1,
stop: false,
skip: false
};
return ctx;
});
var html = '';
return mapSeries(contexts, (context) => {
scope.push(context);
return liquid.renderer
.renderTemplates(this.templates, scope)
.then(partial => html += partial)
.catch(e => {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML;
if (e.message === 'continue') return;
}
throw e;
})
.then(() => scope.pop());
}).catch((e) => {
if (e instanceof RenderBreakError && e.message === 'break') {
return;
}
throw e;
}).then(() => html);
var contexts = collection.map((item, i) => {
var ctx = {}
ctx[this.variable] = item
ctx.forloop = {
first: i === 0,
index: i + 1,
index0: i,
last: i === length - 1,
length: length,
rindex: length - i,
rindex0: length - i - 1,
stop: false,
skip: false
}
});
};
return ctx
})
var html = ''
return mapSeries(contexts, (context) => {
scope.push(context)
return liquid.renderer
.renderTemplates(this.templates, scope)
.then(partial => (html += partial))
.catch(e => {
if (e instanceof RenderBreakError) {
html += e.resolvedHTML
if (e.message === 'continue') return
}
throw e
})
.then(() => scope.pop())
}).catch((e) => {
if (e instanceof RenderBreakError && e.message === 'break') {
return
}
throw e
}).then(() => html)
}
})
}
+19 -21
View File
@@ -1,26 +1,24 @@
const Promise = require('any-promise');
const Promise = require('any-promise')
module.exports = function(liquid) {
module.exports = function (liquid) {
liquid.registerTag('raw', {
parse: function (tagToken, remainTokens) {
this.tokens = []
liquid.registerTag('raw', {
parse: function(tagToken, remainTokens) {
this.tokens = [];
var stream = liquid.parser.parseStream(remainTokens);
stream
var stream = liquid.parser.parseStream(remainTokens)
stream
.on('token', token => {
if(token.name === 'endraw') stream.stop();
else this.tokens.push(token);
if (token.name === 'endraw') stream.stop()
else this.tokens.push(token)
})
.on('end', x => {
throw new Error(`tag ${tagToken.raw} not closed`);
});
stream.start();
},
render: function(scope, hash) {
var tokens = this.tokens.map(token => token.raw).join('');
return Promise.resolve(tokens);
}
});
};
throw new Error(`tag ${tagToken.raw} not closed`)
})
stream.start()
},
render: function (scope, hash) {
var tokens = this.tokens.map(token => token.raw).join('')
return Promise.resolve(tokens)
}
})
}
+11
View File
@@ -0,0 +1,11 @@
{
"rules": {
"no-unused-expressions": "off"
},
"env": {
"mocha": true
},
"plugins": [
"mocha"
]
}
+84 -84
View File
@@ -1,94 +1,94 @@
const chai = require("chai");
const expect = chai.expect;
const mock = require('mock-fs');
const request = require('supertest');
const express = require('express');
const Liquid = require('..');
const chai = require('chai')
const expect = chai.expect
const mock = require('mock-fs')
const request = require('supertest')
const express = require('express')
const Liquid = require('..')
describe('engine#express()', function() {
var app, engine;
describe('engine#express()', function () {
var app, engine
beforeEach(function() {
app = express();
engine = Liquid({
root: '/root',
extname: '.html'
});
beforeEach(function () {
app = express()
engine = Liquid({
root: '/root',
extname: '.html'
})
app.set('view engine', 'html');
app.engine('html', engine.express());
app.set('view engine', 'html')
app.engine('html', engine.express())
app.get('/name', (req, res) => res.render('name', {
name: 'harttle'
}));
app.get('/include/:file', (req, res) => res.render('include', {
file: req.params.file
}));
});
after(function() {
mock.restore();
});
it('should render express views', function(done) {
mock({ '/views/name.html': 'My name is {{name}}.' });
app.set('views', ['/views']);
request(app).get('/name')
app.get('/name', (req, res) => res.render('name', {
name: 'harttle'
}))
app.get('/include/:file', (req, res) => res.render('include', {
file: req.params.file
}))
})
after(function () {
mock.restore()
})
it('should render express views', function (done) {
mock({ '/views/name.html': 'My name is {{name}}.' })
app.set('views', ['/views'])
request(app).get('/name')
.expect('My name is harttle.')
.expect(200, done);
});
it('should pass error when file not found', function(done) {
var view = {
root: []
};
var file = '/not-exist.html';
var ctx = {};
engine.express().call(view, file, ctx, function(err) {
try {
expect(err.code).to.equal('ENOENT');
expect(err.message).to.match(/Failed to lookup/);
done();
} catch (e) {
done(e);
}
});
});
it('should respect root option when lookup', function(done) {
mock({
'/root/foo.html': 'foo',
'/views/include.html': '{% include file %}'
});
app.set('views', ['/views']);
request(app).get('/include/foo')
.expect(200, done)
})
it('should pass error when file not found', function (done) {
var view = {
root: []
}
var file = '/not-exist.html'
var ctx = {}
engine.express().call(view, file, ctx, function (err) {
try {
expect(err.code).to.equal('ENOENT')
expect(err.message).to.match(/Failed to lookup/)
done()
} catch (e) {
done(e)
}
})
})
it('should respect root option when lookup', function (done) {
mock({
'/root/foo.html': 'foo',
'/views/include.html': '{% include file %}'
})
app.set('views', ['/views'])
request(app).get('/include/foo')
.expect('foo')
.expect(200, done);
});
it('should respect express views (Array) when lookup', function(done) {
mock({
'/views/include.html': '{% include file %}',
'/partials/bar.html': 'bar'
});
app.set('views', ['/views', '/partials']);
request(app).get('/include/bar')
.expect(200, done)
})
it('should respect express views (Array) when lookup', function (done) {
mock({
'/views/include.html': '{% include file %}',
'/partials/bar.html': 'bar'
})
app.set('views', ['/views', '/partials'])
request(app).get('/include/bar')
.expect('bar')
.expect(200, done);
});
it('should respect express views (String) when lookup', function(done) {
mock({
'/views/include.html': '{% include file %}',
'/views/bar.html': 'bar'
});
app.set('views', '/views');
request(app).get('/include/bar')
.expect(200, done)
})
it('should respect express views (String) when lookup', function (done) {
mock({
'/views/include.html': '{% include file %}',
'/views/bar.html': 'bar'
})
app.set('views', '/views')
request(app).get('/include/bar')
.expect('bar')
.expect(200, done);
});
it('should respect express views (Undefined) when lookup', function(done) {
var files = {};
files[process.cwd() + '/views/include.html'] = '{% include file %}';
files[process.cwd() + '/views/bar.html'] = 'bar';
mock(files);
.expect(200, done)
})
it('should respect express views (Undefined) when lookup', function (done) {
var files = {}
files[process.cwd() + '/views/include.html'] = '{% include file %}'
files[process.cwd() + '/views/bar.html'] = 'bar'
mock(files)
request(app).get('/include/bar')
request(app).get('/include/bar')
.expect('bar')
.expect(200, done);
});
});
.expect(200, done)
})
})
+47 -47
View File
@@ -1,57 +1,57 @@
const chai = require("chai");
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const expect = chai.expect;
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
const expect = chai.expect
chai.use(sinonChai);
chai.use(sinonChai)
var filter = require('../src/filter.js')();
var Scope = require('../src/scope.js');
var filter = require('../src/filter.js')()
var Scope = require('../src/scope.js')
describe('filter', function() {
var scope;
beforeEach(function() {
filter.clear();
scope = Scope.factory();
});
it('should return default filter when not registered', function() {
var result = filter.construct('foo');
expect(result.name).to.equal('foo');
});
describe('filter', function () {
var scope
beforeEach(function () {
filter.clear()
scope = Scope.factory()
})
it('should return default filter when not registered', function () {
var result = filter.construct('foo')
expect(result.name).to.equal('foo')
})
it('should throw when filter name illegal', function() {
expect(function() {
filter.construct('/');
}).to.throw(/illegal filter/);
});
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"');
it('should parse argument syntax', function () {
filter.register('foo', x => x)
var f = filter.construct('foo: a, "b"')
expect(f.name).to.equal('foo');
expect(f.args).to.deep.equal(['a', '"b"']);
});
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['a', '"b"'])
})
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 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() {
filter.register('add', (a, b) => a + b);
expect(filter.construct('add: 2').render(3, scope)).to.equal(5);
});
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() {
filter.register('add', (a, b, c) => a + b + c);
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal("5c");
});
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() {
var spy = sinon.spy();
filter.register('foo', spy);
filter.construct('foo: 33').render('foo', scope);
expect(spy).to.have.been.calledWith('foo', 33);
});
});
it('should call filter with corrct arguments', function () {
var spy = sinon.spy()
filter.register('foo', spy)
filter.construct('foo: 33').render('foo', scope)
expect(spy).to.have.been.calledWith('foo', 33)
})
})
+283 -282
View File
@@ -1,341 +1,342 @@
const chai = require("chai");
const chaiAsPromised = require("chai-as-promised");
var liquid = require('..')(),
ctx;
chai.use(chaiAsPromised);
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const expect = chai.expect
var liquid = require('..')()
var ctx
chai.use(chaiAsPromised)
function test(src, dst) {
ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
obj: {
foo: 'bar'
},
func: function() {},
posts: [{
category: 'foo'
}, {
category: 'bar'
}]
};
return liquid.parseAndRender(src, ctx).should.eventually.equal(dst);
function test (src, dst) {
ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
obj: {
foo: 'bar'
},
func: function () {},
posts: [{
category: 'foo'
}, {
category: 'bar'
}]
}
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
}
describe('filters', function() {
describe('abs', function() {
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'));
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'));
it('should return convert string', () => test('{{ "-3" | abs }}', '3'));
});
describe('filters', function () {
describe('abs', function () {
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'))
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'))
it('should return convert string', () => test('{{ "-3" | abs }}', '3'))
})
describe('append', function() {
it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | append: "abc" }}', '-3abc'));
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'));
});
describe('append', function () {
it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | append: "abc" }}', '-3abc'))
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'))
})
it('should support capitalize', () => test('{{ "i am good" | capitalize }}', 'I am good'));
it('should support capitalize', () => test('{{ "i am good" | capitalize }}', 'I am good'))
describe('ceil', function() {
it('should return "2" for 1.2', () => test('{{ 1.2 | ceil }}', '2'));
it('should return "2" for 2.0', () => test('{{ 2.0 | ceil }}', '2'));
it('should return "4" for 3.5', () => test('{{ "3.5" | ceil }}', '4'));
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'));
});
describe('ceil', function () {
it('should return "2" for 1.2', () => test('{{ 1.2 | ceil }}', '2'))
it('should return "2" for 2.0', () => test('{{ 2.0 | ceil }}', '2'))
it('should return "4" for 3.5', () => test('{{ "3.5" | ceil }}', '4'))
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'))
})
describe('date', function() {
it('should support date: %a %b %d %Y', function() {
var str = ctx.date.toDateString();
return test('{{ date | date:"%a %b %d %Y"}}', str);
});
it('should create a new Date when given "now"', function() {
return test('{{ "now" | date: "%Y"}}', (new Date).getFullYear().toString());
});
it('should render as empty string when invalid', function() {
return test('{{ "" | date: "%Y"}}', "");
});
});
describe('date', function () {
it('should support date: %a %b %d %Y', function () {
var str = ctx.date.toDateString()
return test('{{ date | date:"%a %b %d %Y"}}', str)
})
it('should create a new Date when given "now"', function () {
return test('{{ "now" | date: "%Y"}}', (new Date()).getFullYear().toString())
})
it('should render as empty string when invalid', function () {
return test('{{ "" | date: "%Y"}}', '')
})
})
describe('default', function() {
it('should use default when falsy', () => test('{{false |default: "a"}}', 'a'));
it('should not use default when truthy', () => test('{{true |default: "a"}}', 'true'));
});
describe('default', function () {
it('should use default when falsy', () => test('{{false |default: "a"}}', 'a'))
it('should not use default when truthy', () => test('{{true |default: "a"}}', 'true'))
})
describe('divided_by', function() {
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'));
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'));
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', '1'));
it('should convert string to number', () => test('{{"5" | divided_by: "3"}}', '1'));
});
describe('divided_by', function () {
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'))
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'))
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', '1'))
it('should convert string to number', () => test('{{"5" | divided_by: "3"}}', '1'))
})
describe('downcase', function() {
it('should return "parker moore" for "Parker Moore"',
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'));
it('should return "apple" for "apple"',
() => test('{{ "apple" | downcase }}', 'apple'));
});
describe('downcase', function () {
it('should return "parker moore" for "Parker Moore"',
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'))
it('should return "apple" for "apple"',
() => test('{{ "apple" | downcase }}', 'apple'))
})
describe('escape', function() {
it('should escape \' and &', function() {
return test('{{ "Have you read \'James & the Giant Peach\'?" | escape }}',
'Have you read &#39;James &amp; the Giant Peach&#39;?');
});
it('should escape normal string', function() {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara');
});
it('should escape function', function() {
return test('{{ func | escape }}', 'function () {}');
});
});
describe('escape', function () {
it('should escape \' and &', function () {
return test('{{ "Have you read \'James & the Giant Peach\'?" | escape }}',
'Have you read &#39;James &amp; the Giant Peach&#39;?')
})
it('should escape normal string', function () {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
})
it('should escape function', function () {
return test('{{ func | escape }}', 'function () {}')
})
})
describe('escape_once', function() {
it('should do escape', () =>
test('{{ "1 < 2 & 3" | escape_once }}', '1 &lt; 2 &amp; 3'));
it('should not escape twice',
() => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3'));
});
describe('escape_once', function () {
it('should do escape', () =>
test('{{ "1 < 2 & 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
it('should not escape twice',
() => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
})
it('should support split/first', function() {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}';
return test(src, 'apples');
});
it('should support split/first', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return test(src, 'apples')
})
describe('floor', function() {
it('should return "1" for 1.2', () => test('{{ 1.2 | floor }}', '1'));
it('should return "2" for 2.0', () => test('{{ 2.0 | floor }}', '2'));
it('should return "183" for 183.357', () => test('{{ 183.357 | floor }}', '183'));
it('should return "3" for 3.5', () => test('{{ "3.5" | floor }}', '3'));
});
describe('floor', function () {
it('should return "1" for 1.2', () => test('{{ 1.2 | floor }}', '1'))
it('should return "2" for 2.0', () => test('{{ 2.0 | floor }}', '2'))
it('should return "183" for 183.357', () => test('{{ 183.357 | floor }}', '183'))
it('should return "3" for 3.5', () => test('{{ "3.5" | floor }}', '3'))
})
it('should support join', function() {
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}';
return test(src, 'John and Paul and George and Ringo');
});
it('should support join', function () {
var src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}'
return test(src, 'John and Paul and George and Ringo')
})
it('should support split/last', function() {
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}';
return test(src, 'tiger');
});
it('should support split/last', function () {
var src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}'
return test(src, 'tiger')
})
it('should support lstrip', function() {
var src = '{{ " So much room for activities! " | lstrip }}';
return test(src, 'So much room for activities! ');
});
it('should support lstrip', function () {
var src = '{{ " So much room for activities! " | lstrip }}'
return test(src, 'So much room for activities! ')
})
it('should support map', function() {
return test('{{posts | map: "category"}}', '["foo","bar"]');
});
it('should support map', function () {
return test('{{posts | map: "category"}}', '["foo","bar"]')
})
describe('minus', function() {
it('should return "2" for 4,2', () => test('{{ 4 | minus: 2 }}', '2'));
it('should return "12" for 16,4', () => test('{{ 16 | minus: 4 }}', '12'));
it('should return "171.357" for 183.357,12',
() => test('{{ 183.357 | minus: 12 }}', '171.357'));
it('should convert first arg as number', () => test('{{ "4" | minus: 1 }}', '3'));
it('should convert both args as number', () => test('{{ "4" | minus: "1" }}', '3'));
});
describe('minus', function () {
it('should return "2" for 4,2', () => test('{{ 4 | minus: 2 }}', '2'))
it('should return "12" for 16,4', () => test('{{ 16 | minus: 4 }}', '12'))
it('should return "171.357" for 183.357,12',
() => test('{{ 183.357 | minus: 12 }}', '171.357'))
it('should convert first arg as number', () => test('{{ "4" | minus: 1 }}', '3'))
it('should convert both args as number', () => test('{{ "4" | minus: "1" }}', '3'))
})
describe('modulo', function() {
it('should return "1" for 3,2', () => test('{{ 3 | modulo: 2 }}', '1'));
it('should return "3" for 24,7', () => test('{{ 24 | modulo: 7 }}', '3'));
it('should return "3.357" for 183.357,12',
() => test('{{ 183.357 | modulo: 12 }}', '3.357'));
it('should convert string', () => test('{{ "24" | modulo: "7" }}', '3'));
});
describe('modulo', function () {
it('should return "1" for 3,2', () => test('{{ 3 | modulo: 2 }}', '1'))
it('should return "3" for 24,7', () => test('{{ 24 | modulo: 7 }}', '3'))
it('should return "3.357" for 183.357,12',
() => test('{{ 183.357 | modulo: 12 }}', '3.357'))
it('should convert string', () => test('{{ "24" | modulo: "7" }}', '3'))
})
it('should support string_with_newlines', function() {
var src = '{% capture string_with_newlines %}\n' +
it('should support string_with_newlines', function () {
var src = '{% capture string_with_newlines %}\n' +
'Hello\n' +
'there\n' +
'{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}';
var dst = '<br />' +
'{{ string_with_newlines | newline_to_br }}'
var dst = '<br />' +
'Hello<br />' +
'there<br />';
return test(src, dst);
});
'there<br />'
return test(src, dst)
})
describe('plus', function() {
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'));
it('should return "20" for 16,4', () => test('{{ 16 | plus: 4 }}', '20'));
it('should return "195.357" for 183.357,12',
() => test('{{ 183.357 | plus: 12 }}', '195.357'));
it('should convert first arg as number', () => test('{{ "4" | plus: 2 }}', '6'));
it('should convert both args as number', () => test('{{ "4" | plus: "2" }}', '6'));
});
describe('plus', function () {
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'))
it('should return "20" for 16,4', () => test('{{ 16 | plus: 4 }}', '20'))
it('should return "195.357" for 183.357,12',
() => test('{{ 183.357 | plus: 12 }}', '195.357'))
it('should convert first arg as number', () => test('{{ "4" | plus: 2 }}', '6'))
it('should convert both args as number', () => test('{{ "4" | plus: "2" }}', '6'))
})
it('should support prepend', function() {
return test('{% assign url = "liquidmarkup.com" %}' +
it('should support prepend', function () {
return test('{% assign url = "liquidmarkup.com" %}' +
'{{ "/index.html" | prepend: url }}',
'liquidmarkup.com/index.html');
});
'liquidmarkup.com/index.html')
})
it('should support remove', function() {
return test('{{ "I strained to see the train through the rain" | remove: "rain" }}',
'I sted to see the t through the ');
});
it('should support remove', function () {
return test('{{ "I strained to see the train through the rain" | remove: "rain" }}',
'I sted to see the t through the ')
})
it('should support remove_first', function() {
return test('{{ "I strained to see the train through the rain" | remove_first: "rain" }}',
'I sted to see the train through the rain');
});
it('should support remove_first', function () {
return test('{{ "I strained to see the train through the rain" | remove_first: "rain" }}',
'I sted to see the train through the rain')
})
it('should support replace', function() {
return test('{{ "Take my protein pills and put my helmet on" | replace: "my", "your" }}',
'Take your protein pills and put your helmet on');
});
it('should support replace', function () {
return test('{{ "Take my protein pills and put my helmet on" | replace: "my", "your" }}',
'Take your protein pills and put your helmet on')
})
it('should support replace_first', function() {
return test('{% assign my_string = "Take my protein pills and put my helmet on" %}\n' +
it('should support replace_first', function () {
return test('{% assign my_string = "Take my protein pills and put my helmet on" %}\n' +
'{{ my_string | replace_first: "my", "your" }}',
'\nTake your protein pills and put my helmet on');
});
'\nTake your protein pills and put my helmet on')
})
it('should support reverse', function() {
return test('{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
'.moT rojaM ot lortnoc dnuorG');
});
it('should support reverse', function () {
return test('{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
'.moT rojaM ot lortnoc dnuorG')
})
describe('round', function() {
it('should return "1" for 1.2', () => test('{{1.2|round}}', '1'));
it('should return "3" for 2.7', () => test('{{2.7|round}}', '3'));
it('should return "183.36" for 183.357,2',
() => test('{{183.357|round: 2}}', '183.36'));
it('should convert string to number', () => test('{{"2.7"|round}}', '3'));
});
describe('round', function () {
it('should return "1" for 1.2', () => test('{{1.2|round}}', '1'))
it('should return "3" for 2.7', () => test('{{2.7|round}}', '3'))
it('should return "183.36" for 183.357,2',
() => test('{{183.357|round: 2}}', '183.36'))
it('should convert string to number', () => test('{{"2.7"|round}}', '3'))
})
it('should support rstrip', function() {
return test('{{ " So much room for activities! " | rstrip }}',
' So much room for activities!');
});
it('should support rstrip', function () {
return test('{{ " So much room for activities! " | rstrip }}',
' So much room for activities!')
})
describe('size', function() {
it('should return string length',
() => test('{{ "Ground control to Major Tom." | size }}', '28'));
it('should return array size', function() {
return test('{% assign my_array = "apples, oranges, peaches, plums"' +
describe('size', function () {
it('should return string length',
() => test('{{ "Ground control to Major Tom." | size }}', '28'))
it('should return array size', function () {
return test('{% assign my_array = "apples, oranges, peaches, plums"' +
' | split: ", " %}{{ my_array | size }}',
'4');
});
it('should also be used with dot notation - string',
() => test('{% assign my_string = "Ground control to Major Tom." %}{{ my_string.size }}', '28'));
it('should also be used with dot notation - array',
() => test('{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}{{ my_array.size }}', '4'));
});
'4')
})
it('should also be used with dot notation - string',
() => test('{% assign my_string = "Ground control to Major Tom." %}{{ my_string.size }}', '28'))
it('should also be used with dot notation - array',
() => test('{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}{{ my_array.size }}', '4'))
})
describe('slice', function() {
it('should slice first char by 0', () => test('{{ "Liquid" | slice: 0 }}', 'L'));
it('should slice third char by 2', () => test('{{ "Liquid" | slice: 2 }}', 'q'));
it('should slice substr by 2,5', () => test('{{ "Liquid" | slice: 2, 5 }}', 'quid'));
it('should slice substr by -3,2', () => test('{{ "Liquid" | slice: -3, 2 }}', 'ui'));
});
describe('slice', function () {
it('should slice first char by 0', () => test('{{ "Liquid" | slice: 0 }}', 'L'))
it('should slice third char by 2', () => test('{{ "Liquid" | slice: 2 }}', 'q'))
it('should slice substr by 2,5', () => test('{{ "Liquid" | slice: 2, 5 }}', 'quid'))
it('should slice substr by -3,2', () => test('{{ "Liquid" | slice: -3, 2 }}', 'ui'))
})
it('should support sort', function() {
return test('{% assign my_array = "zebra, octopus, giraffe, Sally Snake"' +
it('should support sort', function () {
return test('{% assign my_array = "zebra, octopus, giraffe, Sally Snake"' +
' | split: ", " %}' +
'{{ my_array | sort | join: ", " }}',
'Sally Snake, giraffe, octopus, zebra');
});
'Sally Snake, giraffe, octopus, zebra')
})
it('should support split', function() {
return test('{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
it('should support split', function () {
return test('{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{% for member in beatles %}' +
'{{ member }} ' +
'{% endfor %}',
'John Paul George Ringo ');
});
'John Paul George Ringo ')
})
it('should support strip', function() {
return test('{{ " So much room for activities! " | strip }}',
'So much room for activities!');
});
it('should support strip', function () {
return test('{{ " So much room for activities! " | strip }}',
'So much room for activities!')
})
describe('strip_html', function() {
it('should strip all tags', function() {
return test('{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}',
'Have you read Ulysses?');
});
it('should strip until empty', function() {
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '');
});
});
describe('strip_html', function () {
it('should strip all tags', function () {
return test('{{ "Have <em>you</em> read <strong>Ulysses</strong>?" | strip_html }}',
'Have you read Ulysses?')
})
it('should strip until empty', function () {
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '')
})
})
it('should support strip_newlines', function() {
return test('{% capture string_with_newlines %}\n' +
it('should support strip_newlines', function () {
return test('{% capture string_with_newlines %}\n' +
'Hello\nthere\n{% endcapture %}' +
'{{ string_with_newlines | strip_newlines }}',
'Hellothere');
});
'Hellothere')
})
describe('times', function() {
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'));
it('should return "168" for 24,7', () => test('{{ 24 | times: 7 }}', '168'));
it('should return "2200.284" for 183.357,12',
() => test('{{ 183.357 | times: 12 }}', '2200.284'));
it('should convert string to number', () => test('{{ "24" | times: "7" }}', '168'));
});
describe('times', function () {
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'))
it('should return "168" for 24,7', () => test('{{ 24 | times: 7 }}', '168'))
it('should return "2200.284" for 183.357,12',
() => test('{{ 183.357 | times: 12 }}', '2200.284'))
it('should convert string to number', () => test('{{ "24" | times: "7" }}', '168'))
})
describe('truncate', function() {
it('should truncate when string too long', function() {
return test('{{ "Ground control to Major Tom." | truncate: 20 }}',
'Ground control to...');
});
it('should not truncate when string not long enough', function() {
return test('{{ "Ground control to Major Tom." | truncate: 80 }}',
'Ground control to Major Tom.');
});
it('should truncate with custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncate: 25,", and so on" }}',
'Ground control, and so on');
});
it('should truncate with empty custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncate: 20, "" }}',
'Ground control to Ma');
});
});
describe('truncate', function () {
it('should truncate when string too long', function () {
return test('{{ "Ground control to Major Tom." | truncate: 20 }}',
'Ground control to...')
})
it('should not truncate when string not long enough', function () {
return test('{{ "Ground control to Major Tom." | truncate: 80 }}',
'Ground control to Major Tom.')
})
it('should truncate with custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncate: 25,", and so on" }}',
'Ground control, and so on')
})
it('should truncate with empty custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncate: 20, "" }}',
'Ground control to Ma')
})
})
describe('truncatewords', function() {
it('should truncate when too many words', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
'Ground control to...');
});
it('should not truncate when not enough words', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 8 }}',
'Ground control to Major Tom.');
});
it('should truncate with custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
'Ground control to--');
});
it('should truncate with empty custom ellipsis', function() {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
'Ground control to');
});
});
describe('truncatewords', function () {
it('should truncate when too many words', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
'Ground control to...')
})
it('should not truncate when not enough words', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 8 }}',
'Ground control to Major Tom.')
})
it('should truncate with custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
'Ground control to--')
})
it('should truncate with empty custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
'Ground control to')
})
})
it('should support uniq', function() {
return test('{% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %}' +
it('should support uniq', function () {
return test('{% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %}' +
'{{ my_array | uniq | join: ", " }}',
'ants, bugs, bees');
});
'ants, bugs, bees')
})
it('should support upcase', () => test('{{ "Parker Moore" | upcase }}', 'PARKER MOORE'));
it('should support upcase', () => test('{{ "Parker Moore" | upcase }}', 'PARKER MOORE'))
describe('url_encode', function() {
it('should encode @',
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'));
it('should encode <space>',
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'));
});
describe('url_encode', function () {
it('should encode @',
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'))
it('should encode <space>',
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'))
})
describe('obj_test', function() {
liquid.registerFilter('obj_test', function() {
return Array.prototype.slice.call(arguments).join(',');
});
it('should support object', () => test('{{ "a" | obj_test: k1: "v1", k2: "v2" }}', 'a,k1,v1,k2,v2'));
});
});
describe('obj_test', function () {
liquid.registerFilter('obj_test', function () {
return Array.prototype.slice.call(arguments).join(',')
})
it('should support object', () => test('{{ "a" | obj_test: k1: "v1", k2: "v2" }}', 'a,k1,v1,k2,v2'))
})
})
+111 -111
View File
@@ -1,124 +1,124 @@
const chai = require("chai");
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
var lexical = require('../src/lexical.js');
var lexical = require('../src/lexical.js')
describe('lexical', function() {
it('should test filter syntax', function() {
lexical.filterLine.test('abs').should.equal(true);
lexical.filterLine.test('plus:1').should.equal(true);
lexical.filterLine.test('replace: "a", b').should.equal(true);
lexical.filterLine.test('foo: a, "b"').should.equal(true);
lexical.filterLine.test('abs | another').should.equal(false);
lexical.filterLine.test('join: "," | another').should.equal(false);
lexical.filterLine.test('obj_test: k1: "v1", k2: "v2"').should.equal(true);
});
describe('lexical', function () {
it('should test filter syntax', function () {
expect(lexical.filterLine.test('abs')).to.equal(true)
expect(lexical.filterLine.test('plus:1')).to.equal(true)
expect(lexical.filterLine.test('replace: "a", b')).to.equal(true)
expect(lexical.filterLine.test('foo: a, "b"')).to.equal(true)
expect(lexical.filterLine.test('abs | another')).to.equal(false)
expect(lexical.filterLine.test('join: "," | another')).to.equal(false)
expect(lexical.filterLine.test('obj_test: k1: "v1", k2: "v2"')).to.equal(true)
})
it('should test boolean literal', function() {
lexical.isLiteral('true').should.equal(true);
lexical.isLiteral('TrUE').should.equal(true);
lexical.isLiteral('false').should.equal(true);
});
it('should test boolean literal', function () {
expect(lexical.isLiteral('true')).to.equal(true)
expect(lexical.isLiteral('TrUE')).to.equal(true)
expect(lexical.isLiteral('false')).to.equal(true)
})
it('should test number literal', function() {
lexical.isLiteral('2.3').should.equal(true);
lexical.isLiteral('.3').should.equal(true);
lexical.isLiteral('-3.').should.equal(true);
lexical.isLiteral('23').should.equal(true);
});
it('should test number literal', function () {
expect(lexical.isLiteral('2.3')).to.equal(true)
expect(lexical.isLiteral('.3')).to.equal(true)
expect(lexical.isLiteral('-3.')).to.equal(true)
expect(lexical.isLiteral('23')).to.equal(true)
})
it("should test range literal", function() {
lexical.isRange("(12..32)").should.equal(true);
lexical.isRange("(12..foo)").should.equal(true);
lexical.isRange("(foo.bar..foo)").should.equal(true);
});
it('should test range literal', function () {
expect(lexical.isRange('(12..32)')).to.equal(true)
expect(lexical.isRange('(12..foo)')).to.equal(true)
expect(lexical.isRange('(foo.bar..foo)')).to.equal(true)
})
it('should test string literal', function() {
lexical.isLiteral('""').should.equal(true);
lexical.isLiteral('"a\'b"').should.equal(true);
lexical.isLiteral("''").should.equal(true);
lexical.isLiteral("'a bcd'").should.equal(true);
});
it('should test string literal', function () {
expect(lexical.isLiteral('""')).to.equal(true)
expect(lexical.isLiteral('"a\'b"')).to.equal(true)
expect(lexical.isLiteral("''")).to.equal(true)
expect(lexical.isLiteral("'a bcd'")).to.equal(true)
})
describe('.isVariable()', function() {
it('should return true for foo', function() {
lexical.isVariable("foo").should.equal(true);
});
it('should return true for.bar.foo', function() {
lexical.isVariable("foo.bar.foo").should.equal(true);
});
it('should return true for foo[0].b', function() {
lexical.isVariable("foo[0].b").should.equal(true);
});
it('should return true for 0a', function() {
lexical.isVariable("0a").should.equal(true);
});
it('should return true for foo[a.b]', function() {
lexical.isVariable("foo[a.b]").should.equal(true);
});
it('should return true for foo[a.b]', function() {
lexical.isVariable("foo['a[0]']").should.equal(true);
});
it('should return true for "var-1"', function() {
lexical.isVariable("var-1").should.equal(true);
});
it('should return true for "-var"', function() {
lexical.isVariable("-var").should.equal(true);
});
it('should return true for "var-"', function() {
lexical.isVariable("var-").should.equal(true);
});
it('should return true for "3-4"', function() {
lexical.isVariable("3-4").should.equal(true);
});
});
describe('.isVariable()', function () {
it('should return true for foo', function () {
expect(lexical.isVariable('foo')).to.equal(true)
})
it('should return true for.bar.foo', function () {
expect(lexical.isVariable('foo.bar.foo')).to.equal(true)
})
it('should return true for foo[0].b', function () {
expect(lexical.isVariable('foo[0].b')).to.equal(true)
})
it('should return true for 0a', function () {
expect(lexical.isVariable('0a')).to.equal(true)
})
it('should return true for foo[a.b]', function () {
expect(lexical.isVariable('foo[a.b]')).to.equal(true)
})
it('should return true for foo[a.b]', function () {
expect(lexical.isVariable("foo['a[0]']")).to.equal(true)
})
it('should return true for "var-1"', function () {
expect(lexical.isVariable('var-1')).to.equal(true)
})
it('should return true for "-var"', function () {
expect(lexical.isVariable('-var')).to.equal(true)
})
it('should return true for "var-"', function () {
expect(lexical.isVariable('var-')).to.equal(true)
})
it('should return true for "3-4"', function () {
expect(lexical.isVariable('3-4')).to.equal(true)
})
})
it('should test none literal', function() {
lexical.isLiteral('2a').should.equal(false);
lexical.isLiteral('"x').should.equal(false);
lexical.isLiteral('a2').should.equal(false);
});
it('should test none literal', function () {
expect(lexical.isLiteral('2a')).to.equal(false)
expect(lexical.isLiteral('"x')).to.equal(false)
expect(lexical.isLiteral('a2')).to.equal(false)
})
it('should test none variable', function() {
lexical.isVariable("a.").should.equal(false);
lexical.isVariable(".b").should.equal(false);
lexical.isVariable(".").should.equal(false);
lexical.isVariable("[0][12].bar[0]").should.equal(false);
});
it('should test none variable', function () {
expect(lexical.isVariable('a.')).to.equal(false)
expect(lexical.isVariable('.b')).to.equal(false)
expect(lexical.isVariable('.')).to.equal(false)
expect(lexical.isVariable('[0][12].bar[0]')).to.equal(false)
})
it('should parse boolean literal', function() {
lexical.parseLiteral('true').should.equal(true);
lexical.parseLiteral('TrUE').should.equal(true);
lexical.parseLiteral('false').should.equal(false);
});
it('should parse boolean literal', function () {
expect(lexical.parseLiteral('true')).to.equal(true)
expect(lexical.parseLiteral('TrUE')).to.equal(true)
expect(lexical.parseLiteral('false')).to.equal(false)
})
it('should parse number literal', function() {
lexical.parseLiteral('2.3').should.equal(2.3);
lexical.parseLiteral('.32').should.equal(0.32);
lexical.parseLiteral('-23.').should.equal(-23);
lexical.parseLiteral('23').should.equal(23);
});
it('should parse number literal', function () {
expect(lexical.parseLiteral('2.3')).to.equal(2.3)
expect(lexical.parseLiteral('.32')).to.equal(0.32)
expect(lexical.parseLiteral('-23.')).to.equal(-23)
expect(lexical.parseLiteral('23')).to.equal(23)
})
it('should parse string literal', function() {
lexical.parseLiteral('"ab\'c"').should.equal("ab\'c");
});
it('should parse string literal', function () {
expect(lexical.parseLiteral('"ab\'c"')).to.equal("ab'c")
})
describe('.matchValue()', function(){
it('should match -5-5', function() {
var match = lexical.matchValue('-5-5');
expect(match && match[0]).to.equal('-5-5');
});
it('should match 4-3', function() {
var match = lexical.matchValue('4-3');
expect(match && match[0]).to.equal('4-3');
});
it('should match 4-3', function() {
var match = lexical.matchValue('4-3');
expect(match && match[0]).to.equal('4-3');
});
it('should match var-1', function() {
var match = lexical.matchValue('var-1');
expect(match && match[0]).to.equal('var-1');
});
});
});
describe('.matchValue()', function () {
it('should match -5-5', function () {
var match = lexical.matchValue('-5-5')
expect(match && match[0]).to.equal('-5-5')
})
it('should match 4-3', function () {
var match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match 4-3', function () {
var match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match var-1', function () {
var match = lexical.matchValue('var-1')
expect(match && match[0]).to.equal('var-1')
})
})
})
+223 -223
View File
@@ -1,226 +1,226 @@
const chai = require("chai");
const expect = chai.expect;
const Liquid = require('..');
const mock = require('mock-fs');
chai.use(require("chai-as-promised"));
const chai = require('chai')
const expect = chai.expect
const Liquid = require('..')
const mock = require('mock-fs')
chai.use(require('chai-as-promised'))
describe('liquid', function() {
var engine, strictEngine, ctx;
beforeEach(function() {
ctx = {
name: 'harttle',
arr: [-2, 'a'],
obj: {
foo: 'bar'
}
};
engine = Liquid({
root: '/root/',
extname: '.html'
});
strictEngine = Liquid({
root: '/root',
extname: '.html',
strict_filters: true
});
mock({
'/root/files/foo.html': 'foo',
'/root/files/name.html': 'My name is {{name}}.',
'/un-readable.html': mock.file({
mode: '0000'
})
});
});
afterEach(function() {
mock.restore();
});
describe('{{output}}', function() {
it('should output object', function() {
return engine.parseAndRender('{{obj}}', ctx).should.eventually.equal('{"foo":"bar"}');
});
it('should output array', function() {
return engine.parseAndRender('{{arr}}', ctx).should.eventually.equal('[-2,"a"]');
});
it('should output undefined to empty', function() {
return engine.parseAndRender('foo{{zzz}}bar', ctx).should.eventually.equal('foobar');
});
it('should render as null when filter undefined', function() {
return engine.parseAndRender('{{"foo" | filter1}}', ctx).should.eventually.equal('foo');
});
it('should throw upon undefined filter when strict_filters set', function() {
return expect(strictEngine.parseAndRender('{{arr | filter1}}', ctx)).to
.be.rejectedWith(/undefined filter: filter1/);
});
});
it('should parse html', function() {
(function() {
engine.parse('{{obj}}');
}).should.not.throw();
(function() {
engine.parse('<html><head>{{obj}}</head></html>');
}).should.not.throw();
});
it('should render template multiple times', function() {
var template = engine.parse('{{obj}}');
describe('liquid', function () {
var engine, strictEngine, ctx
beforeEach(function () {
ctx = {
name: 'harttle',
arr: [-2, 'a'],
obj: {
foo: 'bar'
}
}
engine = Liquid({
root: '/root/',
extname: '.html'
})
strictEngine = Liquid({
root: '/root',
extname: '.html',
strict_filters: true
})
mock({
'/root/files/foo.html': 'foo',
'/root/files/name.html': 'My name is {{name}}.',
'/un-readable.html': mock.file({
mode: '0000'
})
})
})
afterEach(function () {
mock.restore()
})
describe('{{output}}', function () {
it('should output object', function () {
return expect(engine.parseAndRender('{{obj}}', ctx)).to.eventually.equal('{"foo":"bar"}')
})
it('should output array', function () {
return expect(engine.parseAndRender('{{arr}}', ctx)).to.eventually.equal('[-2,"a"]')
})
it('should output undefined to empty', function () {
return expect(engine.parseAndRender('foo{{zzz}}bar', ctx)).to.eventually.equal('foobar')
})
it('should render as null when filter undefined', function () {
return expect(engine.parseAndRender('{{"foo" | filter1}}', ctx)).to.eventually.equal('foo')
})
it('should throw upon undefined filter when strict_filters set', function () {
return expect(strictEngine.parseAndRender('{{arr | filter1}}', ctx)).to
.be.rejectedWith(/undefined filter: filter1/)
})
})
it('should parse html', function () {
expect(function () {
engine.parse('{{obj}}')
}).to.not.throw()
expect(function () {
engine.parse('<html><head>{{obj}}</head></html>')
}).to.not.throw()
})
it('should render template multiple times', function () {
var template = engine.parse('{{obj}}')
return engine.render(template, ctx)
.then((result) => {
expect(result).to.equal('{"foo":"bar"}')
return engine.render(template, ctx)
.then((result) => {
expect(result).to.equal('{"foo":"bar"}');
return engine.render(template, ctx);
})
.then((result) => {
return expect(result).to.equal('{"foo":"bar"}');
});
});
it('should render filters', function() {
var template = engine.parse('<p>{{arr | join: "_"}}</p>');
return engine.render(template, ctx).should.eventually.equal('<p>-2_a</p>');
});
it('should render accessive filters', function() {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}';
return expect(engine.parseAndRender(src)).to.eventually.equal('apples');
});
describe('#renderFile()', function() {
it('should render file', function() {
return expect(engine.renderFile('/root/files/foo.html', ctx))
.to.eventually.equal('foo');
});
it('should accept relative path', function() {
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo');
});
it('should resolve array as root', function(){
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
});
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo');
});
it('should default root to cwd', function(){
var files = {};
files[process.cwd() + '/foo.html'] = 'FOO';
mock(files);
})
.then((result) => {
return expect(result).to.equal('{"foo":"bar"}')
})
})
it('should render filters', function () {
var template = engine.parse('<p>{{arr | join: "_"}}</p>')
return expect(engine.render(template, ctx)).to.eventually.equal('<p>-2_a</p>')
})
it('should render accessive filters', function () {
var src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return expect(engine.parseAndRender(src)).to.eventually.equal('apples')
})
describe('#renderFile()', function () {
it('should render file', function () {
return expect(engine.renderFile('/root/files/foo.html', ctx))
.to.eventually.equal('foo')
})
it('should accept relative path', function () {
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
})
it('should resolve array as root', function () {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
})
return expect(engine.renderFile('files/foo.html'))
.to.eventually.equal('foo')
})
it('should default root to cwd', function () {
var files = {}
files[process.cwd() + '/foo.html'] = 'FOO'
mock(files)
engine = Liquid({
extname: '.html'
});
return expect(engine.renderFile('foo.html'))
.to.eventually.equal('FOO');
});
it('should render file with context', function() {
return engine.renderFile('/root/files/name.html', ctx).should.eventually.equal('My name is harttle.');
});
it('should use default extname', function() {
return engine.renderFile('files/name', ctx).should.eventually.equal('My name is harttle.');
});
it('should throw with lookup list when file not exist', function() {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
});
return expect(engine.renderFile('/not/exist.html')).to
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i);
});
it('should throw when file not readable', function() {
return expect(engine.renderFile('/un-readable.html')).to
.be.rejectedWith(/EACCES/);
});
});
describe('strict', function() {
it('should not throw when strict_variables false (default)', function() {
return expect(engine.parseAndRender('before{{notdefined}}after', ctx)).to
.eventually.equal('beforeafter');
});
it('should throw when strict_variables true', function() {
var tpl = engine.parse('before{{notdefined}}after');
var opts = {
strict_variables: true
};
return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/);
});
it('should pass strict_variables to render by parseAndRender', function() {
var html = 'before{{notdefined}}after';
var opts = {
strict_variables: true
};
return expect(engine.parseAndRender(html, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/);
});
});
describe('cache', function() {
it('should be disabled by default', function() {
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('bar'));
});
it('should respect cache=true option', function() {
engine = Liquid({
root: '/root/',
extname: '.html',
cache: true
});
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('foo'));
});
});
describe('trim_left, trim_right', function() {
it('should trim_left for tags when trim_left=true', function() {
engine = Liquid({
trim_left: true
});
return engine.parseAndRender(' \n \t{%if true%}foo{%endif%} ')
.should.eventually.equal(' \nfoo ');
});
it('should trim_right for tags when trim_right=true', function() {
engine = Liquid({
trim_right: true
});
return engine.parseAndRender('\t{%if true%}foo{%endif%} \n')
.should.eventually.equal('\tfoo');
});
it('should trim all blanks before and after when greedy=true', function() {
engine = Liquid({
greedy: true
});
return engine.parseAndRender('\t{%-if true%}foo{%endif-%} \n \n')
.should.eventually.equal('foo');
});
it('should support trim using markup', function() {
engine = Liquid();
var src = [
'{%- assign username = "John G. Chalmers-Smith" -%}',
'{%- if username and username.length > 10 -%}',
' Wow, {{ username }}, you have a long name!',
'{%- else -%}',
' Hello there!',
'{%- endif -%}\n',
].join('\n');
var dst = ' Wow, John G. Chalmers-Smith, you have a long name!\n';
return engine.parseAndRender(src).should.eventually.equal(dst);
});
it('should not trim when not specified', function() {
engine = Liquid();
var src = [
'{% assign username = "John G. Chalmers-Smith" %}',
'{% if username and username.length > 10 %}',
' Wow, {{ username }}, you have a long name!',
'{% else %}',
' Hello there!',
'{% endif %}\n',
].join('\n');
var dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n\n';
return engine.parseAndRender(src).should.eventually.equal(dst);
});
});
});
engine = Liquid({
extname: '.html'
})
return expect(engine.renderFile('foo.html'))
.to.eventually.equal('FOO')
})
it('should render file with context', function () {
return expect(engine.renderFile('/root/files/name.html', ctx)).to.eventually.equal('My name is harttle.')
})
it('should use default extname', function () {
return expect(engine.renderFile('files/name', ctx)).to.eventually.equal('My name is harttle.')
})
it('should throw with lookup list when file not exist', function () {
engine = Liquid({
root: ['/boo', '/root/'],
extname: '.html'
})
return expect(engine.renderFile('/not/exist.html')).to
.be.rejectedWith(/failed to lookup \/not\/exist.html in: \/boo,\/root\//i)
})
it('should throw when file not readable', function () {
return expect(engine.renderFile('/un-readable.html')).to
.be.rejectedWith(/EACCES/)
})
})
describe('strict', function () {
it('should not throw when strict_variables false (default)', function () {
return expect(engine.parseAndRender('before{{notdefined}}after', ctx)).to
.eventually.equal('beforeafter')
})
it('should throw when strict_variables true', function () {
var tpl = engine.parse('before{{notdefined}}after')
var opts = {
strict_variables: true
}
return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
it('should pass strict_variables to render by parseAndRender', function () {
var html = 'before{{notdefined}}after'
var opts = {
strict_variables: true
}
return expect(engine.parseAndRender(html, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
})
describe('cache', function () {
it('should be disabled by default', function () {
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('bar'))
})
it('should respect cache=true option', function () {
engine = Liquid({
root: '/root/',
extname: '.html',
cache: true
})
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('foo'))
})
})
describe('trim_left, trim_right', function () {
it('should trim_left for tags when trim_left=true', function () {
engine = Liquid({
trim_left: true
})
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
.to.eventually.equal(' \nfoo ')
})
it('should trim_right for tags when trim_right=true', function () {
engine = Liquid({
trim_right: true
})
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
.to.eventually.equal('\tfoo')
})
it('should trim all blanks before and after when greedy=true', function () {
engine = Liquid({
greedy: true
})
return expect(engine.parseAndRender('\t{%-if true%}foo{%endif-%} \n \n'))
.to.eventually.equal('foo')
})
it('should support trim using markup', function () {
engine = Liquid()
var src = [
'{%- assign username = "John G. Chalmers-Smith" -%}',
'{%- if username and username.length > 10 -%}',
' Wow, {{ username }}, you have a long name!',
'{%- else -%}',
' Hello there!',
'{%- endif -%}\n'
].join('\n')
var dst = ' Wow, John G. Chalmers-Smith, you have a long name!\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
it('should not trim when not specified', function () {
engine = Liquid()
var src = [
'{% assign username = "John G. Chalmers-Smith" %}',
'{% if username and username.length > 10 %}',
' Wow, {{ username }}, you have a long name!',
'{% else %}',
' Hello there!',
'{% endif %}\n'
].join('\n')
var dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
})
})
+38 -40
View File
@@ -1,49 +1,47 @@
const chai = require("chai");
const sinon = require("sinon");
const sinonChai = require("sinon-chai");
const should = chai.should();
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
chai.use(sinonChai);
chai.use(require('sinon-chai'))
var filter = require('../src/filter.js')();
var tag = require('../src/tag.js')();
var Template = require('../src/parser.js');
var filter = require('../src/filter.js')()
var tag = require('../src/tag.js')()
var Template = require('../src/parser.js')
describe('template', function() {
var scope, template, add = (l, r) => l + r;
describe('template', function () {
var template
var add = (l, r) => l + r
beforeEach(function() {
filter.clear();
filter.register('add', add);
beforeEach(function () {
filter.clear()
filter.register('add', add)
tag.clear();
template = Template(tag, filter);
});
tag.clear()
template = Template(tag, filter)
})
it('should throw when output string illegal', function() {
expect(function() {
template.parseOutput('/');
}).to.throw(/illegal output string/);
});
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');
expect(tpl.initial).to.equal('foo');
expect(tpl.filters).to.deep.equal([]);
});
it('should parse output string', function () {
var tpl = template.parseOutput('foo')
expect(tpl.type).to.equal('output')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters).to.deep.equal([])
})
it('should parse output string with a simple filter', function() {
var tpl = template.parseOutput('foo | add: 3, "foo"');
expect(tpl.initial).to.equal('foo');
expect(tpl.filters.length).to.equal(1);
expect(tpl.filters[0].filter).to.equal(add);
});
it('should parse output string with a simple filter', function () {
var tpl = template.parseOutput('foo | add: 3, "foo"')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(1)
expect(tpl.filters[0].filter).to.equal(add)
})
it('should parse output string with filters', function() {
var tpl = template.parseOutput('foo | add: "|" | add');
expect(tpl.initial).to.equal('foo');
expect(tpl.filters.length).to.equal(2);
});
});
it('should parse output string with filters', function () {
var tpl = template.parseOutput('foo | add: "|" | add')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(2)
})
})
+58 -59
View File
@@ -1,67 +1,66 @@
const chai = require("chai");
const chaiAsPromised = require("chai-as-promised");
const should = chai.should();
const expect = chai.expect;
const sinonChai = require("sinon-chai");
const sinon = require("sinon");
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const expect = chai.expect
const sinonChai = require('sinon-chai')
const sinon = require('sinon')
chai.use(sinonChai);
chai.use(chaiAsPromised);
chai.use(sinonChai)
chai.use(chaiAsPromised)
var tag = require('../src/tag.js')();
var Scope = require('../src/scope.js');
var filter = require('../src/filter')();
var Render = require('../src/render.js');
var Template = require('../src/parser.js')(tag, filter);
var tag = require('../src/tag.js')()
var Scope = require('../src/scope.js')
var filter = require('../src/filter')()
var Render = require('../src/render.js')
var Template = require('../src/parser.js')(tag, filter)
describe('render', function() {
var scope, render;
describe('render', function () {
var scope, render
beforeEach(function() {
scope = Scope.factory({
foo: {
bar: ['a', 2]
}
});
filter.clear();
tag.clear();
render = Render();
});
beforeEach(function () {
scope = Scope.factory({
foo: {
bar: ['a', 2]
}
})
filter.clear()
tag.clear()
render = Render()
})
describe('.renderTemplates()', function(){
it('should throw when scope undefined', function() {
expect(function(){
render.renderTemplates([]);
}).to.throw(/scope undefined/);
});
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 render html', function () {
return expect(render.renderTemplates([{type: 'html', value: '<p>'}], scope)).to.eventually.equal('<p>')
})
})
it('should eval filter with correct arguments', function() {
var date = sinon.stub().returns('y');
var time = sinon.spy();
filter.register('date', date);
filter.register('time', time);
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2');
render.evalOutput(tpl, scope);
expect(date).to.have.been.calledWith('a', 'b');
expect(time).to.have.been.calledWith('y', 2);
});
it('should eval filter with correct arguments', function () {
var date = sinon.stub().returns('y')
var time = sinon.spy()
filter.register('date', date)
filter.register('time', time)
var tpl = Template.parseOutput('foo.bar[0] | date: "b" | time:2')
render.evalOutput(tpl, scope)
expect(date).to.have.been.calledWith('a', 'b')
expect(time).to.have.been.calledWith('y', 2)
})
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');
});
});
});
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')
})
})
})
+178 -178
View File
@@ -1,195 +1,195 @@
const chai = require("chai");
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
var Scope = require('../src/scope.js');
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);
});
describe('scope', function () {
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 1', function() {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo']);
});
it('should handle nested access 2', function() {
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo']);
});
it('should handle nested access 3', function() {
expect(scope.propertyAccessSeq('bar["foo"].zoo'))
.to.deep.equal(['bar', 'foo', 'zoo']);
});
});
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 1', function () {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 2', function () {
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 3', function () {
expect(scope.propertyAccessSeq('bar["foo"].zoo'))
.to.deep.equal(['bar', 'foo', 'zoo'])
})
})
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 when [] unbalanced', function() {
expect(function() {
scope.get('foo[bar');
}).to.throw(/unbalanced \[\]/);
});
it('should throw when [] unbalanced', function () {
expect(function () {
scope.get('foo[bar')
}).to.throw(/unbalanced \[\]/)
})
it('should throw when "" unbalanced', function() {
expect(function() {
scope.get('foo["bar]');
}).to.throw(/unbalanced "/);
});
it('should throw when "" unbalanced', function () {
expect(function () {
scope.get('foo["bar]')
}).to.throw(/unbalanced "/)
})
it("should throw when '' unbalanced", function() {
expect(function() {
scope.get("foo['bar]");
}).to.throw(/unbalanced '/);
});
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 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 access child property via [<String>] syntax', function() {
expect(scope.get('bar["zoo"]')).to.equal('coo');
});
it('should access child property via [<String>] syntax', function () {
expect(scope.get('bar["zoo"]')).to.equal('coo')
})
it('should access child property via [<Number>] syntax', function() {
expect(scope.get('bar.arr[0]')).to.equal('a');
});
it('should access child property via [<Number>] syntax', function () {
expect(scope.get('bar.arr[0]')).to.equal('a')
})
it('should access child property via [<Identifier>] syntax', function() {
expect(scope.get('bar[foo]')).to.equal('coo');
});
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');
});
});
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('strict_variables', function() {
var scope;
beforeEach(function(){
scope = Scope.factory(ctx, {
strict_variables: true
});
});
it('should throw undefined in strict mode', function() {
function fn() {
scope.get('notdefined');
}
expect(fn).to.throw(/undefined variable: notdefined/);
});
it('should find variable in parent scope', function() {
scope.set('foo', 'foo');
scope.push({
'bar': 'bar'
});
expect(scope.get('foo')).to.equal('foo');
});
});
describe('strict_variables', function () {
var scope
beforeEach(function () {
scope = Scope.factory(ctx, {
strict_variables: true
})
})
it('should throw undefined in strict mode', function () {
function fn () {
scope.get('notdefined')
}
expect(fn).to.throw(/undefined variable: notdefined/)
})
it('should find variable in parent scope', function () {
scope.set('foo', 'foo')
scope.push({
'bar': 'bar'
})
expect(scope.get('foo')).to.equal('foo')
})
})
describe('.getAll()', function() {
it('should get all properties when arguments empty', function() {
expect(scope.getAll()).deep.equal(ctx);
});
});
describe('.getAll()', function () {
it('should get all properties when arguments empty', function () {
expect(scope.getAll()).deep.equal(ctx)
})
})
describe('.push()', 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 hide deep properties by push', function(){
scope.set('bar', {bar: 'bar'});
scope.push({bar: {foo: 'foo'}});
expect(scope.get('bar.foo')).to.equal('foo');
expect(scope.get('bar.bar')).to.equal(undefined);
});
});
describe('.pop()', function() {
it('should pop scope', function() {
scope.push({
foo: 'foo'
});
scope.pop();
expect(scope.get('foo')).to.equal('zoo');
});
});
describe('.push()', 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 hide deep properties by push', function () {
scope.set('bar', {bar: 'bar'})
scope.push({bar: {foo: 'foo'}})
expect(scope.get('bar.foo')).to.equal('foo')
expect(scope.get('bar.bar')).to.equal(undefined)
})
})
describe('.pop()', function () {
it('should pop scope', function () {
scope.push({
foo: 'foo'
})
scope.pop()
expect(scope.get('foo')).to.equal('zoo')
})
})
describe('.unshift()', 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'
});
expect(scope.get('foo')).to.equal('zoo');
expect(scope.get('foo1')).to.equal('foo1');
});
});
describe('.shift()', function() {
it('should shift scope', function() {
scope.unshift({
foo: 'blue',
foo1: 'foo1'
});
scope.shift();
expect(scope.get('foo')).to.equal('zoo');
expect(scope.get('foo1')).to.equal(undefined);
});
});
});
describe('.unshift()', 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'
})
expect(scope.get('foo')).to.equal('zoo')
expect(scope.get('foo1')).to.equal('foo1')
})
})
describe('.shift()', function () {
it('should shift scope', function () {
scope.unshift({
foo: 'blue',
foo1: 'foo1'
})
scope.shift()
expect(scope.get('foo')).to.equal('zoo')
expect(scope.get('foo1')).to.equal(undefined)
})
})
})
+69 -70
View File
@@ -1,81 +1,80 @@
const chai = require("chai");
const expect = chai.expect;
var syntax = require('../src/syntax.js');
var Scope = require('../src/scope.js');
const chai = require('chai')
const expect = chai.expect
var syntax = require('../src/syntax.js')
var Scope = require('../src/scope.js')
var evalExp = syntax.evalExp;
var evalValue = syntax.evalValue;
var isTruthy = syntax.isTruthy;
var evalExp = syntax.evalExp
var evalValue = syntax.evalValue
var isTruthy = syntax.isTruthy
describe('expression', function() {
var scope;
describe('expression', function () {
var scope
beforeEach(function() {
scope = Scope.factory({
one: 1,
two: 2,
x: 'XXX',
y: undefined,
z: null
});
});
beforeEach(function () {
scope = Scope.factory({
one: 1,
two: 2,
x: 'XXX',
y: undefined,
z: null
})
})
it('should eval literals', function() {
expect(evalValue('2.3')).to.equal(2.3);
expect(evalValue('"foo"')).to.equal("foo");
});
it('should eval literals', function () {
expect(evalValue('2.3')).to.equal(2.3)
expect(evalValue('"foo"')).to.equal('foo')
})
it('should eval variables', function() {
expect(evalValue('23', scope)).to.equal(23);
expect(evalValue('one', scope)).to.equal(1);
expect(evalValue('x', scope)).to.equal('XXX');
});
it('should eval variables', function () {
expect(evalValue('23', scope)).to.equal(23)
expect(evalValue('one', scope)).to.equal(1)
expect(evalValue('x', scope)).to.equal('XXX')
})
describe('.isTruthy()', function() {
describe('.isTruthy()', function () {
// Spec: https://shopify.github.io/liquid/basics/truthy-and-falsy/
expect(isTruthy(true)).to.be.true;
expect(isTruthy(false)).to.be.false;
expect(isTruthy(null)).to.be.false;
expect(isTruthy('foo')).to.be.true;
expect(isTruthy('')).to.be.true;
expect(isTruthy(0)).to.be.true;
expect(isTruthy(1)).to.be.true;
expect(isTruthy(1.1)).to.be.true;
expect(isTruthy([1])).to.be.true;
expect(isTruthy([])).to.be.true;
expect(isTruthy(true)).to.be.true
expect(isTruthy(false)).to.be.false
expect(isTruthy(null)).to.be.false
expect(isTruthy('foo')).to.be.true
expect(isTruthy('')).to.be.true
expect(isTruthy(0)).to.be.true
expect(isTruthy(1)).to.be.true
expect(isTruthy(1.1)).to.be.true
expect(isTruthy([1])).to.be.true
expect(isTruthy([])).to.be.true
})
describe('.evalExp()', function () {
it('should throw when scope undefined', function () {
expect(function () {
evalExp('')
}).to.throw(/scope undefined/)
})
describe('.evalExp()', function() {
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('1 contains "x"', scope)).to.equal(false)
expect(evalExp('y contains "x"', scope)).to.equal(false)
expect(evalExp('z contains "x"', scope)).to.equal(false)
expect(evalExp('(1..5) contains 3', scope)).to.equal(true)
expect(evalExp('(1..5) contains 6', scope)).to.equal(false)
expect(evalExp('"<=" == "<="', scope)).to.equal(true)
})
it('should throw when scope undefined', function() {
expect(function() {
evalExp('');
}).to.throw(/scope undefined/);
});
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 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('1 contains "x"', scope)).to.equal(false);
expect(evalExp('y contains "x"', scope)).to.equal(false);
expect(evalExp('z contains "x"', scope)).to.equal(false);
expect(evalExp('(1..5) contains 3', scope)).to.equal(true);
expect(evalExp('(1..5) contains 6', scope)).to.equal(false);
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]);
});
});
});
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])
})
})
})
+85 -86
View File
@@ -1,99 +1,98 @@
const chai = require("chai");
const sinon = require("sinon");
const expect = chai.expect;
chai.use(require("sinon-chai"));
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
chai.use(require('sinon-chai'))
var tag = require('../src/tag.js')();
var Scope = require('../src/scope.js');
var tag = require('../src/tag.js')()
var Scope = require('../src/scope.js')
describe('tag', function() {
var scope;
before(function() {
scope = Scope.factory({
foo: 'bar',
arr: [2, 1],
bar: {
coo: 'uoo'
}
});
tag.clear();
});
describe('tag', function () {
var scope
before(function () {
scope = Scope.factory({
foo: 'bar',
arr: [2, 1],
bar: {
coo: 'uoo'
}
})
tag.clear()
})
it('should throw when not registered', function() {
expect(function() {
tag.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, []);
}).to.throw(/tag foo not found/);
});
it('should throw when not registered', function () {
expect(function () {
tag.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
}).to.throw(/tag foo not found/)
})
it('should register simple tag', function() {
expect(
function() {
tag.register('foo', {
render: x => 'bar'
});
}).not.throw();
});
it('should register simple tag', function () {
expect(function () {
tag.register('foo', {
render: x => 'bar'
})
}).not.throw()
})
it('should call tag.render', function() {
var spy = sinon.spy();
tag.register('foo', {
render: spy
});
return tag
it('should call tag.render', function () {
var spy = sinon.spy()
tag.register('foo', {
render: spy
})
return tag
.construct({
type: 'tag',
value: 'foo',
name: 'foo'
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
.render(scope, {})
.then(() => expect(spy).to.have.been.called);
});
.then(() => expect(spy).to.have.been.called)
})
describe('hash', function(){
var spy, token;
beforeEach(function(){
spy = sinon.spy();
tag.register('foo', {
render: spy
});
token = {
type: 'tag',
value: 'foo aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo',
name: 'foo',
args: 'aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo'
};
});
it('should call tag.render with scope', function() {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope));
});
it('should resolve identifier hash', function() {
return tag.construct(token, []).render(scope, {})
describe('hash', function () {
var spy, token
beforeEach(function () {
spy = sinon.spy()
tag.register('foo', {
render: spy
})
token = {
type: 'tag',
value: 'foo aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo',
name: 'foo',
args: 'aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo'
}
})
it('should call tag.render with scope', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope))
})
it('should resolve identifier hash', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch({}, {
aa: 'bar'
}));
});
it('should accept space between key/value', function() {
return tag.construct(token, []).render(scope, {})
aa: 'bar'
}))
})
it('should accept space between key/value', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch({}, {
bb: 2,
}));
});
it('should resolve number value hash', function() {
return tag.construct(token, []).render(scope, {})
bb: 2
}))
})
it('should resolve number value hash', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
cc: 2.3
}));
});
it('should resolve property access hash', function() {
return tag.construct(token, []).render(scope, {})
cc: 2.3
}))
})
it('should resolve property access hash', function () {
return tag.construct(token, []).render(scope, {})
.then(() => expect(spy).to.have.been.calledWithMatch(scope, {
dd: 'uoo'
}));
});
});
});
dd: 'uoo'
}))
})
})
})
+51 -51
View File
@@ -1,53 +1,53 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
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/);
});
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))
.to.eventually.equal('bar');
});
it('should assign as array', function() {
var src = '{% assign foo=(1..3) %}{{foo}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('[1,2,3]');
});
it('should assign as filter result', function() {
var src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A');
});
it('should assign var-1', function() {
var src = '{% assign var-1 = 5 %}{{ var-1 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign var-', function() {
var src = '{% assign var- = 5 %}{{ var- }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign -var', function() {
var src = '{% assign -var = 5 %}{{ -var }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign -5-5', function() {
var src = '{% assign -5-5 = 5 %}{{ -5-5 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should assign 4-3', function() {
var src = '{% assign 4-3 = 5 %}{{ 4-3 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('5');
});
it('should not assign -6', function() {
var src = '{% assign -6 = 5 %}{{ -6 }}';
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6');
});
});
it('should assign as string', function () {
var src = '{% assign foo="bar" %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar')
})
it('should assign as array', function () {
var src = '{% assign foo=(1..3) %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('[1,2,3]')
})
it('should assign as filter result', function () {
var src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A')
})
it('should assign var-1', function () {
var src = '{% assign var-1 = 5 %}{{ var-1 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign var-', function () {
var src = '{% assign var- = 5 %}{{ var- }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign -var', function () {
var src = '{% assign -var = 5 %}{{ -var }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign -5-5', function () {
var src = '{% assign -5-5 = 5 %}{{ -5-5 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign 4-3', function () {
var src = '{% assign 4-3 = 5 %}{{ 4-3 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should not assign -6', function () {
var src = '{% assign -6 = 5 %}{{ -6 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6')
})
})
+22 -22
View File
@@ -1,26 +1,26 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/capture', function() {
var liquid = Liquid();
describe('tags/capture', function () {
var liquid = Liquid()
it('should support capture', function() {
var src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A');
});
it('should support capture', function () {
var src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A')
})
it('should throw on invalid identifier', function() {
var src = '{% capture = %}{%endcapture%}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/= not valid identifier/);
});
it('should throw on invalid identifier', function () {
var src = '{% capture = %}{%endcapture%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/= not valid identifier/)
})
it('should throw when capture not closed', function() {
var src = '{%capture c%}{{c}}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/);
});
});
it('should throw when capture not closed', function () {
var src = '{%capture c%}{{c}}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
})
+39 -39
View File
@@ -1,45 +1,45 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/case', function() {
var liquid = Liquid();
describe('tags/case', function () {
var liquid = Liquid()
it('should support case 1', function() {
var src = '{% case "foo"%}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/);
});
it('should support case 2', function() {
var src = '{% case "foo"%}' +
it('should support case 1', function () {
var src = '{% case "foo"%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/)
})
it('should support case 2', function () {
var src = '{% case "foo"%}' +
'{% when "foo" %}foo{% when "bar"%}bar' +
'{%endcase%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('foo');
});
it('should support case 3', function() {
var src = '{% case empty %}' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('foo')
})
it('should support case 3', function () {
var src = '{% case empty %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}';
var ctx = {
empty: ''
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar');
});
it('should support case 4', function() {
var src = '{% case false %}' +
'{%endcase%}'
var ctx = {
empty: ''
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar')
})
it('should support case 4', function () {
var src = '{% case false %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('');
});
it('should support case 5', function() {
var src = '{% case "a" %}' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should support case 5', function () {
var src = '{% case "a" %}' +
'{% when "b" %}b{% when "c"%}c{%else %}d' +
'{%endcase%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('d');
});
});
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('d')
})
})
+22 -22
View File
@@ -1,23 +1,23 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/comment', function() {
var liquid = Liquid();
it('should support comment 1', function() {
var src = '{% comment %}{% raw%}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/);
});
it('should support comment 2', function() {
var src = 'My name is {% comment %}super{% endcomment %} Shopify.';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('My name is Shopify.');
});
it('should support comment 3', function() {
var src = '{% comment %}\n{{ foo}} \n{% endcomment %}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('');
});
});
describe('tags/comment', function () {
var liquid = Liquid()
it('should support comment 1', function () {
var src = '{% comment %}{% raw%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/)
})
it('should support comment 2', function () {
var src = 'My name is {% comment %}super{% endcomment %} Shopify.'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('My name is Shopify.')
})
it('should support comment 3', function () {
var src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
})
+33 -33
View File
@@ -1,39 +1,39 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/cycle', function() {
var liquid = Liquid();
describe('tags/cycle', function () {
var liquid = Liquid()
it('should support cycle', function() {
var src = "{% cycle '1', '2', '3' %}";
return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231');
});
it('should support cycle', function () {
var src = "{% cycle '1', '2', '3' %}"
return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231')
})
it('should throw when cycle candidates empty', function() {
return expect(liquid.parseAndRender('{%cycle%}'))
.to.be.rejectedWith(/empty candidates/);
});
it('should throw when cycle candidates empty', function () {
return expect(liquid.parseAndRender('{%cycle%}'))
.to.be.rejectedWith(/empty candidates/)
})
it('should support cycle in for block', function() {
var src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}';
var ctx = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1e1e1');
});
it('should support cycle in for block', function () {
var src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1e1e1')
})
it('should support cycle group', function() {
var src = "{% cycle one: '1', '2', '3'%}" +
it('should support cycle group', function () {
var src = "{% cycle one: '1', '2', '3'%}" +
"{% cycle 1: '1', '2', '3'%}" +
"{% cycle 2: '1', '2', '3'%}";
var ctx = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('121');
});
});
"{% cycle 2: '1', '2', '3'%}"
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('121')
})
})
+33 -33
View File
@@ -1,38 +1,38 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/decrement', function() {
var liquid = Liquid();
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 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 = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0');
});
it('should support decrement', function () {
var src = '{% decrement one %}{{one}}'
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0')
})
it('should decrement undefined', function() {
var src = '{% decrement empty %}{{empty}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1');
});
it('should decrement undefined', function () {
var src = '{% decrement empty %}{{empty}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1')
})
it('should support decrement multiple times', function() {
var src = '{% decrement foo %}{%decrement foo%}{{foo}}';
var ctx = {
foo: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('-1');
});
});
it('should support decrement multiple times', function () {
var src = '{% decrement foo %}{%decrement foo%}{{foo}}'
var ctx = {
foo: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('-1')
})
})
+83 -83
View File
@@ -1,101 +1,101 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/for', function() {
var liquid, ctx;
before(function() {
liquid = Liquid();
ctx = {
one: 1,
alpha: ['a', 'b', 'c'],
emptyArray: []
};
});
it('should support for', function() {
var src = '{%for c in alpha%}{{c}}{%endfor%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc');
});
describe('tags/for', function () {
var liquid, ctx
before(function () {
liquid = Liquid()
ctx = {
one: 1,
alpha: ['a', 'b', 'c'],
emptyArray: []
}
})
it('should support for', function () {
var src = '{%for c in alpha%}{{c}}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc')
})
it('should throw when for not closed', function() {
var src = '{%for c in alpha%}{{c}}';
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag .* not closed/);
});
it('should throw when for not closed', function () {
var src = '{%for c in alpha%}{{c}}'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag .* not closed/)
})
it('should return else when for in empty array', function() {
var src = '{%for c in emptyArray%}a{%else%}b{%endfor%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b');
});
it('should return else when for in empty array', function () {
var src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should support for else', function() {
var src = '{%for c in ""%}a{%else%}b{%endfor%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b');
});
it('should support for else', function () {
var src = '{%for c in ""%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should support for with forloop', function() {
var src = '{%for c in alpha%}' +
it('should support for with forloop', function () {
var src = '{%for c in alpha%}' +
'{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' +
'{{forloop.last}}.{{forloop.length}}.' +
'{{forloop.rindex}}.{{forloop.rindex0}}' +
'{{c}}\n' +
'{%endfor%}';
var dst = 'true.1.0.false.3.3.2a\n' +
'{%endfor%}'
var dst = 'true.1.0.false.3.3.2a\n' +
'false.2.1.false.3.2.1b\n' +
'false.3.2.true.3.1.0c\n';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal(dst);
});
'false.3.2.true.3.1.0c\n'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal(dst)
})
it('should support for with continue', function() {
var src = '{% for i in (1..5) %}' +
it('should support for with continue', function () {
var src = '{% for i in (1..5) %}' +
'{{i}}{% continue %}after' +
'{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345');
});
it('should support for with break', function() {
var src = '{% for i in (one..5) %}' +
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345')
})
it('should support for with break', function () {
var src = '{% for i in (one..5) %}' +
'{% if i == 4 %}{% break %}{% endif %}' +
'{{ i }}' +
'{% endfor %}';
//return liquid.parseAndRender(src, ctx).catch(e => {
//console.log(e.stack);
//});
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('123');
});
'{% endfor %}'
// return liquid.parseAndRender(src, ctx).catch(e => {
// console.log(e.stack);
// });
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('123')
})
it('should support for with limit', function() {
var src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12');
});
it('should support for with limit and offset', function() {
var src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67');
});
it('should support for with limit', function () {
var src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12')
})
it('should support for with limit and offset', function () {
var src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67')
})
it('should support for reversed in the last position', function() {
var src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21');
});
it('should support for reversed in the last position', function () {
var src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the first position', function() {
var src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21');
});
it('should support for reversed in the first position', function () {
var src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the middle position', function() {
var src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('543');
});
});
it('should support for reversed in the middle position', function () {
var src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('543')
})
})
+93 -94
View File
@@ -1,104 +1,103 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/if', function() {
var liquid = Liquid();
var ctx = {
one: 1,
two: 2,
emptyString: '',
emptyArray: []
};
describe('tags/if', function () {
var liquid = Liquid()
var ctx = {
one: 1,
two: 2,
emptyString: '',
emptyArray: []
}
it('should support if 1', function() {
var src = '{% if false%}yes';
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/);
});
it('should support if 2', function() {
var src = '{%if emptyArray%}a{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a');
});
it('should support if 3', function() {
var src = '{% if 2==3 %}yes{%else%}no{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should support if 4', function() {
var src = '{% if 1>=2 and one<two %}a{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('');
});
it('should support if 5', function() {
var src = '{% if one!=two %}yes{%else%}no{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes');
});
it('should support if 6', function() {
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2');
});
it('should support if 7', function() {
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}';
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('');
});
it('should return true if empty string', function() {
var src = "{%if emptyString%}a{%endif%}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a');
});
it('should support if 1', function () {
var src = '{% if false%}yes'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/)
})
it('should support if 2', function () {
var src = '{%if emptyArray%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
it('should support if 3', function () {
var src = '{% if 2==3 %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should support if 4', function () {
var src = '{% if 1>=2 and one<two %}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should support if 5', function () {
var src = '{% if one!=two %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes')
})
it('should support if 6', function () {
var src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
})
it('should support if 7', function () {
var src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should return true if empty string', function () {
var src = '{%if emptyString%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
it('should return else when comparison on null 1', function() {
var src = "{% if null < 10 %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should return else when comparison on null 1', function () {
var src = '{% if null < 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 2', function() {
var src = "{% if null <= 10 %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should return else when comparison on null 2', function () {
var src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 3', function() {
var src = "{% if null >= 10 %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should return else when comparison on null 3', function () {
var src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 4', function() {
var src = "{% if null > 10 %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should return else when comparison on null 4', function () {
var src = '{% if null > 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 5', function() {
var src = "{% if 10 < null %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should return else when comparison on null 5', function () {
var src = '{% if 10 < null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 6', function() {
var src = "{% if 10 <= null %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should return else when comparison on null 6', function () {
var src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 7', function() {
var src = "{% if 10 >= null %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
it('should return else when comparison on null 7', function () {
var src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should return else when comparison on null 8', function() {
var src = "{% if 10 > null %}yes{% else %}no{% endif %}";
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no');
});
});
it('should return else when comparison on null 8', function () {
var src = '{% if 10 > null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
})
+84 -85
View File
@@ -1,92 +1,91 @@
const Liquid = require('../..');
const mock = require('mock-fs');
const chai = require("chai");
const expect = chai.expect;
const ParseError = Liquid.Types.ParseError;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const mock = require('mock-fs')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/include', function() {
var liquid;
before(function() {
liquid = Liquid({
root: '/',
extname: '.html'
});
});
afterEach(function() {
mock.restore();
});
it('should support include', function() {
mock({
'/current.html': 'bar{% include "bar/foo.html" %}bar',
'/bar/foo.html': 'foo'
});
return expect(liquid.renderFile('/current.html')).to.
eventually.equal('barfoobar');
});
describe('tags/include', function () {
var liquid
before(function () {
liquid = Liquid({
root: '/',
extname: '.html'
})
})
afterEach(function () {
mock.restore()
})
it('should support include', function () {
mock({
'/current.html': 'bar{% include "bar/foo.html" %}bar',
'/bar/foo.html': 'foo'
})
return expect(liquid.renderFile('/current.html')).to
.eventually.equal('barfoobar')
})
it('should throw when illegal', function() {
mock({
'/illegal.html': '{%include%}',
});
return liquid.renderFile('/illegal.html').catch(function(e){
expect(e.name).to.equal('ParseError');
expect(e.message).to.match(/illegal token {%include%}/);
});
});
it('should throw when illegal', function () {
mock({
'/illegal.html': '{%include%}'
})
return liquid.renderFile('/illegal.html').catch(function (e) {
expect(e.name).to.equal('ParseError')
expect(e.message).to.match(/illegal token {%include%}/)
})
})
it('should support include with relative path', function() {
mock({
'/bar/foo.html': 'foo',
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar',
});
return expect(liquid.renderFile('foo/relative.html')).to.
eventually.equal('barfoobar');
});
it('should support include with relative path', function () {
mock({
'/bar/foo.html': 'foo',
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar'
})
return expect(liquid.renderFile('foo/relative.html')).to
.eventually.equal('barfoobar')
})
it('should support include: hash list', function() {
mock({
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
'/user.html': '{{name}} : {{role}} : {{alias}}',
});
return expect(liquid.renderFile('hash.html')).to.
eventually.equal('harttle : admin : harttle');
});
it('should support include: hash list', function () {
mock({
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
'/user.html': '{{name}} : {{role}} : {{alias}}'
})
return expect(liquid.renderFile('hash.html')).to
.eventually.equal('harttle : admin : harttle')
})
it('should support include: parent scope', function() {
mock({
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}',
});
return expect(liquid.renderFile('scope.html')).to.
eventually.equal('color:yellow, shape:triangle');
});
it('should support include: parent scope', function () {
mock({
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}'
})
return expect(liquid.renderFile('scope.html')).to
.eventually.equal('color:yellow, shape:triangle')
})
it('should support include: with', function() {
mock({
'/with.html': '{% include "color" with "red", shape: "rect" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}',
});
return expect(liquid.renderFile('with.html')).to.
eventually.equal('color:red, shape:rect');
});
it('should support include: with', function () {
mock({
'/with.html': '{% include "color" with "red", shape: "rect" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}'
})
return expect(liquid.renderFile('with.html')).to
.eventually.equal('color:red, shape:rect')
})
it('should support nested includes', function() {
mock({
'/personInfo.html': 'This is a person {% include "card.html" %}',
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
'/address.html': 'City: {{person.address.city}}'
});
var ctx = {
person: {
firstName: 'Joe',
lastName: 'Shmoe',
address: {
city: 'Dallas'
}
}
};
return expect(liquid.renderFile('personInfo.html', ctx)).to.
eventually.equal('This is a person <p>Joe Shmoe<br/>City: Dallas</p>');
});
});
it('should support nested includes', function () {
mock({
'/personInfo.html': 'This is a person {% include "card.html" %}',
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
'/address.html': 'City: {{person.address.city}}'
})
var ctx = {
person: {
firstName: 'Joe',
lastName: 'Shmoe',
address: {
city: 'Dallas'
}
}
}
return expect(liquid.renderFile('personInfo.html', ctx)).to
.eventually.equal('This is a person <p>Joe Shmoe<br/>City: Dallas</p>')
})
})
+28 -28
View File
@@ -1,32 +1,32 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/increment', function() {
var liquid = Liquid();
describe('tags/increment', function () {
var liquid = Liquid()
it('should support increment', function() {
var src = '{% increment one %}{{one}}';
var ctx = {
one: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2');
});
it('should support increment', function () {
var src = '{% increment one %}{{one}}'
var ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
})
it('should increment undefined', function() {
var src = '{% increment empty %}{{empty}}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('1');
});
it('should increment undefined', function () {
var src = '{% increment empty %}{{empty}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('1')
})
it('should support increment multiple times', function() {
var src = '{% increment foo %}{%increment foo%}{{foo}}';
var ctx = {
foo: 1
};
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('3');
});
});
it('should support increment multiple times', function () {
var src = '{% increment foo %}{%increment foo%}{{foo}}'
var ctx = {
foo: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('3')
})
})
+87 -87
View File
@@ -1,89 +1,89 @@
const Liquid = require('../..');
const mock = require('mock-fs');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const mock = require('mock-fs')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/layout', function() {
var liquid;
before(function() {
liquid = Liquid({
root: '/',
extname: '.html'
});
});
afterEach(function() {
mock.restore();
});
describe('tags/layout', function () {
var liquid
before(function () {
liquid = Liquid({
root: '/',
extname: '.html'
})
})
afterEach(function () {
mock.restore()
})
it('should throw when block not closed', function() {
mock({
'/parent.html': 'parent',
});
src = '{% layout "parent" %}{%block%}A';
return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/);
});
it('should handle anonymous block', function() {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y',
});
src = '{% layout "parent.html" %}{%block%}A{%endblock%}';
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY');
});
it('should handle named blocks', function() {
mock({
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z',
});
src = '{% layout "parent.html" %}' +
'{%block a%}A{%endblock%}' +
'{%block b%}B{%endblock%}';
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAYBZ');
});
it('should support default block content', function() {
mock({
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z',
});
src = '{% layout "parent.html" %}{%block a%}a{%endblock%}';
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XaYBZ');
});
it('should handle nested block', function() {
mock({
'/grand.html': 'X{%block a%}G{%endblock%}Y',
'/parent.html': '{%layout "grand" %}{%block a%}P{%endblock%}',
'/main.html': '{%layout "parent"%}{%block a%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('XAY');
});
it('should not bleed scope into included layout', function() {
mock({
'/parent.html': 'X{%block a%}{%endblock%}Y{%block b%}{%endblock%}Z',
'/main.html': '{%layout "parent"%}'+
'{%block a%}A{%endblock%}' +
'{%block b%}I{%include "included"%}J{%endblock%}',
'/included.html': '{%layout "parent"%}{%block a%}a{%endblock%}'
})
return expect(liquid.renderFile('main')).to
.eventually.equal('XAYIXaYZJZ');
});
it('should support hash list', function() {
mock({
'/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black"%}{%block%}A{%endblock%}'
});
return expect(liquid.renderFile('/main.html')).to.
eventually.equal('blackA');
});
it('should support multiple hash', function() {
mock({
'/parent.html': '{{color}}{{bg}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black", bg:"red"%}{%block%}A{%endblock%}'
});
return expect(liquid.renderFile('/main.html')).to.
eventually.equal('blackredA');
});
});
it('should throw when block not closed', function () {
mock({
'/parent.html': 'parent'
})
var src = '{% layout "parent" %}{%block%}A'
return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/)
})
it('should handle anonymous block', function () {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y'
})
var src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY')
})
it('should handle named blocks', function () {
mock({
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z'
})
var src = '{% layout "parent.html" %}' +
'{%block a%}A{%endblock%}' +
'{%block b%}B{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAYBZ')
})
it('should support default block content', function () {
mock({
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z'
})
var src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XaYBZ')
})
it('should handle nested block', function () {
mock({
'/grand.html': 'X{%block a%}G{%endblock%}Y',
'/parent.html': '{%layout "grand" %}{%block a%}P{%endblock%}',
'/main.html': '{%layout "parent"%}{%block a%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('XAY')
})
it('should not bleed scope into included layout', function () {
mock({
'/parent.html': 'X{%block a%}{%endblock%}Y{%block b%}{%endblock%}Z',
'/main.html': '{%layout "parent"%}' +
'{%block a%}A{%endblock%}' +
'{%block b%}I{%include "included"%}J{%endblock%}',
'/included.html': '{%layout "parent"%}{%block a%}a{%endblock%}'
})
return expect(liquid.renderFile('main')).to
.eventually.equal('XAYIXaYZJZ')
})
it('should support hash list', function () {
mock({
'/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black"%}{%block%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
it('should support multiple hash', function () {
mock({
'/parent.html': '{{color}}{{bg}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black", bg:"red"%}{%block%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('blackredA')
})
})
+23 -23
View File
@@ -1,24 +1,24 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/raw', function() {
var liquid = Liquid();
it('should support raw 1', function() {
return expect(liquid.parseAndRender('{% raw%}'))
.to.be.rejectedWith(/{% raw%} not closed/);
});
it('should support raw 2', function() {
var src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.';
var dst = '{{ 5 | plus: 6 }} is equal to 11.';
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst);
});
it('should support raw 3', function() {
var src = '{% raw %}\n{{ foo}} \n{% endraw %}';
var dst = '\n{{ foo}} \n';
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst);
});
});
describe('tags/raw', function () {
var liquid = Liquid()
it('should support raw 1', function () {
return expect(liquid.parseAndRender('{% raw%}'))
.to.be.rejectedWith(/{% raw%} not closed/)
})
it('should support raw 2', function () {
var src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
var dst = '{{ 5 | plus: 6 }} is equal to 11.'
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst)
})
it('should support raw 3', function () {
var src = '{% raw %}\n{{ foo}} \n{% endraw %}'
var dst = '\n{{ foo}} \n'
return expect(liquid.parseAndRender(src))
.to.eventually.equal(dst)
})
})
+54 -54
View File
@@ -1,70 +1,70 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/tablerow', function() {
var liquid = Liquid();
describe('tags/tablerow', function () {
var liquid = Liquid()
it('should support tablerow', function() {
var src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}';
var ctx = {
alpha: ['a', 'b', 'c']
};
var dst = '<table>' +
it('should support tablerow', function () {
var src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
var ctx = {
alpha: ['a', 'b', 'c']
}
var dst = '<table>' +
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
'<tr class="row2"><td class="col1">c</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst);
});
'</table>'
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
})
it('should support empty tablerow', function() {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}';
var dst = '<table></table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
it('should support empty tablerow', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
var dst = '<table></table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should throw when tablerow not closed', function() {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/);
});
it('should throw when tablerow not closed', function () {
var src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
it('should support tablerow with range', function() {
var src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}';
var dst = '<table>' +
it('should support tablerow with range', function () {
var src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' +
'<tr class="row3"><td class="col1">5</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('tablerow should throw on illegal cols 1', function() {
var src = '{% tablerow i in (1..5) cols:0 %}{{ i }}{% endtablerow %}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: 0/);
});
it('tablerow should throw on illegal cols 2', function() {
var src = '{% tablerow i in (1..5) %}{{ i }}{% endtablerow %}';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: undefined/);
});
it('tablerow should throw on illegal cols 1', function () {
var src = '{% tablerow i in (1..5) cols:0 %}{{ i }}{% endtablerow %}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: 0/)
})
it('tablerow should throw on illegal cols 2', function () {
var src = '{% tablerow i in (1..5) %}{{ i }}{% endtablerow %}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/illegal cols: undefined/)
})
it('should support tablerow with limit', function() {
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}';
var dst = '<table>' +
it('should support tablerow with limit', function () {
var src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with offset', function() {
var src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}';
var dst = '<table>' +
it('should support tablerow with offset', function () {
var src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
var dst = '<table>' +
'<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>' +
'</table>';
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst);
});
});
'</table>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
})
+32 -32
View File
@@ -1,35 +1,35 @@
const Liquid = require('../..');
const chai = require("chai");
const expect = chai.expect;
chai.use(require("chai-as-promised"));
const Liquid = require('../..')
const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/unless', function() {
var liquid = Liquid();
describe('tags/unless', function () {
var liquid = Liquid()
it('should render else when predicate yields true', function() {
it('should render else when predicate yields true', function () {
// 0 is truthy
var src = '{% unless 0 %}yes{%else%}no{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('no');
});
it('should render unless when predicate yields false', function() {
var src = '{% unless false %}yes{%else%}no{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes');
});
it('should reject when tag not closed', function() {
var src = '{% unless 1>2 %}yes';
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/);
});
it('should render unless when predicate yields false and else undefined', function() {
var src = '{% unless 1>2 %}yes{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes');
});
it('should render "" when predicate yields false and else undefined', function() {
var src = '{% unless 1<2 %}yes{%endunless%}';
return expect(liquid.parseAndRender(src))
.to.eventually.equal('');
});
});
var src = '{% unless 0 %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('no')
})
it('should render unless when predicate yields false', function () {
var src = '{% unless false %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should reject when tag not closed', function () {
var src = '{% unless 1>2 %}yes'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/)
})
it('should render unless when predicate yields false and else undefined', function () {
var src = '{% unless 1>2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should render "" when predicate yields false and else undefined', function () {
var src = '{% unless 1<2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
})
+108 -110
View File
@@ -1,116 +1,114 @@
const chai = require("chai");
const parse = require('../src/tokenizer.js').parse;
const whiteSpaceCtrl = require('../src/tokenizer.js').whiteSpaceCtrl;
const chai = require('chai')
const parse = require('../src/tokenizer.js').parse
const whiteSpaceCtrl = require('../src/tokenizer.js').whiteSpaceCtrl
const expect = chai.expect
const should = chai.should();
const expect = chai.expect;
describe('tokenizer', function () {
describe('parse', function () {
it('should handle plain HTML', function () {
var html = '<html><body><p>Lorem Ipsum</p></body></html>'
var tokens = parse(html)
describe('tokenizer', function() {
describe('parse', function() {
it('should handle plain HTML', function() {
var html = '<html><body><p>Lorem Ipsum</p></body></html>';
var tokens = parse(html);
expect(tokens.length).to.equal(1)
expect(tokens[0].value).to.equal(html)
expect(tokens[0].type).to.equal('html')
})
it('should throw when non-string passed in', function () {
expect(function () {
parse({})
}).to.throw('illegal input type')
})
it('should handle tag syntax', function () {
var html = '<p>{% for p in a[1]%}</p>'
var tokens = parse(html)
tokens.length.should.equal(1);
tokens[0].value.should.equal(html);
tokens[0].type.should.equal('html');
});
it('should throw when non-string passed in', function() {
expect(function() {
parse({});
}).to.throw('illegal input type');
});
it('should handle tag syntax', function() {
var html = '<p>{% for p in a[1]%}</p>';
var tokens = parse(html);
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('tag')
expect(tokens[1].value).to.equal('for p in a[1]')
})
it('should handle output syntax', function () {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
var tokens = parse(html)
tokens.length.should.equal(3);
tokens[1].type.should.equal('tag');
tokens[1].value.should.equal('for p in a[1]');
});
it('should handle output syntax', function() {
var html = '<p>{{foo | date: "%Y-%m-%d"}}</p>';
var tokens = parse(html);
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('output')
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
})
it('should handle successive outputs and tags', function () {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}'
var tokens = parse(html)
tokens.length.should.equal(3);
tokens[1].type.should.equal('output');
tokens[1].value.should.equal('foo | date: "%Y-%m-%d"');
});
it('should handle successive outputs and tags', function() {
var html = '{{foo}}{{bar}}{%foo%}{%bar%}';
var tokens = parse(html);
expect(tokens.length).to.equal(4)
expect(tokens[0].type).to.equal('output')
expect(tokens[3].type).to.equal('tag')
tokens.length.should.equal(4);
tokens[0].type.should.equal('output');
tokens[3].type.should.equal('tag');
tokens[1].value.should.equal('bar');
tokens[2].value.should.equal('foo');
});
it('should keep white spaces and newlines', function() {
var html = '{%foo%}\n{%bar %} \n {%alice%}';
var tokens = parse(html);
expect(tokens.length).to.equal(5);
expect(tokens[1].type).to.equal('html');
expect(tokens[1].raw).to.equal('\n');
expect(tokens[3].type).to.equal('html');
expect(tokens[3].raw).to.equal(' \n ');
});
it('should handle multiple lines tag', function() {
var html = '{%foo\na:a\nb:1.23\n%}';
var tokens = parse(html);
expect(tokens.length).to.equal(1);
expect(tokens[0].type).to.equal('tag');
expect(tokens[0].args).to.equal('a:a\nb:1.23');
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}');
});
it('should handle multiple lines output', function() {
var html = '{{foo\n|\date:\n"%Y-%m-%d"\n}}';
var tokens = parse(html);
expect(tokens.length).to.equal(1);
expect(tokens[0].type).to.equal('output');
expect(tokens[0].raw).to.equal('{{foo\n|\date:\n"%Y-%m-%d"\n}}');
});
});
describe('whitespace control', function() {
it('should not strip by default', function() {
expect(whiteSpaceCtrl('\n {%foo%} \n')).to.equal('\n {%foo%} \n');
});
it('should strip all blank characters before and after', function() {
expect(whiteSpaceCtrl(' \t\r{%-foo-%} \t\n')).to.equal('{%-foo-%}');
});
it('should not trim previous/next lines', function() {
expect(whiteSpaceCtrl(' \t\n {%-foo-%}')).to.equal(' \t\n{%-foo-%}');
expect(whiteSpaceCtrl('{%-foo-%} \n \tfoo')).to.equal('{%-foo-%} \tfoo');
});
it('should trim exactly one trailing CR', function() {
expect(whiteSpaceCtrl('{%-foo-%} \n\n')).to.equal('{%-foo-%}\n');
});
it('should trim all leading/trailing blanks when options.greedy set', function() {
expect(whiteSpaceCtrl(' \n \n\t\r{%-foo-%}\n \n', {
greedy: true
})).to.equal('{%-foo-%}');
});
it('should strip whitespaces when set trim_left', function() {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_left: true
})).to.equal('\n{%-foo%} \n');
});
it('should strip whitespaces when set trim_right', function() {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_right: true
})).to.equal('\n {%foo-%}');
});
it('markup should has priority over options', function() {
expect(whiteSpaceCtrl('\n {%-foo%} \n', {
trim_left: false
})).to.equal('\n{%-foo%} \n');
});
it('should support a mix of markup and options', function() {
expect(whiteSpaceCtrl(' {%-foo%} \n', {
trim_left: true,
trim_right: true
})).to.equal('{%-foo-%}');
});
});
});
expect(tokens[1].value).to.equal('bar')
expect(tokens[2].value).to.equal('foo')
})
it('should keep white spaces and newlines', function () {
var html = '{%foo%}\n{%bar %} \n {%alice%}'
var tokens = parse(html)
expect(tokens.length).to.equal(5)
expect(tokens[1].type).to.equal('html')
expect(tokens[1].raw).to.equal('\n')
expect(tokens[3].type).to.equal('html')
expect(tokens[3].raw).to.equal(' \n ')
})
it('should handle multiple lines tag', function () {
var html = '{%foo\na:a\nb:1.23\n%}'
var tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('tag')
expect(tokens[0].args).to.equal('a:a\nb:1.23')
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
})
it('should handle multiple lines output', function () {
var html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
var tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('output')
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
})
})
describe('whitespace control', function () {
it('should not strip by default', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n')).to.equal('\n {%foo%} \n')
})
it('should strip all blank characters before and after', function () {
expect(whiteSpaceCtrl(' \t\r{%-foo-%} \t\n')).to.equal('{%-foo-%}')
})
it('should not trim previous/next lines', function () {
expect(whiteSpaceCtrl(' \t\n {%-foo-%}')).to.equal(' \t\n{%-foo-%}')
expect(whiteSpaceCtrl('{%-foo-%} \n \tfoo')).to.equal('{%-foo-%} \tfoo')
})
it('should trim exactly one trailing CR', function () {
expect(whiteSpaceCtrl('{%-foo-%} \n\n')).to.equal('{%-foo-%}\n')
})
it('should trim all leading/trailing blanks when options.greedy set', function () {
expect(whiteSpaceCtrl(' \n \n\t\r{%-foo-%}\n \n', {
greedy: true
})).to.equal('{%-foo-%}')
})
it('should strip whitespaces when set trim_left', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_left: true
})).to.equal('\n{%-foo%} \n')
})
it('should strip whitespaces when set trim_right', function () {
expect(whiteSpaceCtrl('\n {%foo%} \n', {
trim_right: true
})).to.equal('\n {%foo-%}')
})
it('markup should has priority over options', function () {
expect(whiteSpaceCtrl('\n {%-foo%} \n', {
trim_left: false
})).to.equal('\n{%-foo%} \n')
})
it('should support a mix of markup and options', function () {
expect(whiteSpaceCtrl(' {%-foo%} \n', {
trim_left: true,
trim_right: true
})).to.equal('{%-foo-%}')
})
})
})
+344 -344
View File
@@ -1,386 +1,386 @@
const chai = require("chai");
const expect = chai.expect;
const mock = require('mock-fs');
chai.use(require("chai-as-promised"));
const chai = require('chai')
const expect = chai.expect
const mock = require('mock-fs')
chai.use(require('chai-as-promised'))
var engine = require('../..')();
var engine = require('../..')()
var strictEngine = require('../..')({
strict_variables: true,
strict_filters: true
});
strict_variables: true,
strict_filters: true
})
describe('error', function() {
afterEach(function() {
mock.restore();
});
describe('error', function () {
afterEach(function () {
mock.restore()
})
describe('TokenizationError', function() {
it('should throw TokenizationError when tag illegal', function() {
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually
describe('TokenizationError', function () {
it('should throw TokenizationError when tag illegal', function () {
return expect(engine.parseAndRender('{% . a %}', {})).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('TokenizationError');
expect(err.message).to.contain('illegal tag syntax');
});
});
it('should contain template content in err.message', function() {
var html = ['1st', '2nd', 'X{% . a %} Y', '4th'];
var message = [
' 1| 1st',
' 2| 2nd',
'>> 3| X{% . a %} Y',
' 4| 4th',
'TokenizationError: illegal tag syntax',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.then(function (err) {
expect(err.name).to.equal('TokenizationError')
expect(err.message).to.contain('illegal tag syntax')
})
})
it('should contain template content in err.message', function () {
var html = ['1st', '2nd', 'X{% . a %} Y', '4th']
var message = [
' 1| 1st',
' 2| 2nd',
'>> 3| X{% . a %} Y',
' 4| 4th',
'TokenizationError: illegal tag syntax'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('illegal tag syntax, line:3');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('TokenizationError');
});
});
it('should contain the whole template content in err.input', function() {
var html = 'bar\nfoo{% . a %}\nfoo';
return expect(engine.parseAndRender(html)).to.eventually
.then(function (err) {
expect(err.message).to.equal('illegal tag syntax, line:3')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('TokenizationError')
})
})
it('should contain the whole template content in err.input', function () {
var html = 'bar\nfoo{% . a %}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.input).to.equal(html);
});
});
it('should contain line number in err.line', function() {
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually
.then(function (err) {
expect(err.input).to.equal(html)
})
})
it('should contain line number in err.line', function () {
return expect(engine.parseAndRender('1\n2\n{% . a %}\n4', {})).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('TokenizationError');
expect(err.line).to.equal(3);
});
});
it('should contain stack in err.stack', function() {
return expect(engine.parseAndRender('{% . a %}')).to.eventually
.then(function (err) {
expect(err.name).to.equal('TokenizationError')
expect(err.line).to.equal(3)
})
})
it('should contain stack in err.stack', function () {
return expect(engine.parseAndRender('{% . a %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.stack).to.contain('illegal tag syntax');
expect(err.stack).to.contain('at Object.parse');
});
});
it('should contain file path in err.file', function() {
var html = '<html>\n<head>\n\n{% . a %}\n\n';
mock({
"/foo.html": html
});
return expect(engine.renderFile('/foo.html')).to.eventually
.then(function (err) {
expect(err.stack).to.contain('illegal tag syntax')
expect(err.stack).to.contain('at Object.parse')
})
})
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% . a %}\n\n'
mock({
'/foo.html': html
})
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function(err) {
mock.restore();
expect(err.name).to.equal('TokenizationError');
expect(err.file).to.equal('/foo.html');
});
});
});
.then(function (err) {
mock.restore()
expect(err.name).to.equal('TokenizationError')
expect(err.file).to.equal('/foo.html')
})
})
})
describe('RenderError', function() {
beforeEach(function() {
engine = require('../..')({
root: '/'
});
engine.registerTag('throwingTag', {
render: function() {
throw new Error('intended render error');
}
});
engine.registerTag('rejectingTag', {
render: function() {
return Promise.reject(new Error('intended render reject'));
}
});
engine.registerFilter('throwingFilter', () => {
throw new Error('throwed by filter');
});
});
it('should throw RenderError when tag throws', function() {
var src = '{%throwingTag%}';
return expect(engine.parseAndRender(src)).to.eventually
describe('RenderError', function () {
beforeEach(function () {
engine = require('../..')({
root: '/'
})
engine.registerTag('throwingTag', {
render: function () {
throw new Error('intended render error')
}
})
engine.registerTag('rejectingTag', {
render: function () {
return Promise.reject(new Error('intended render reject'))
}
})
engine.registerFilter('throwingFilter', () => {
throw new Error('throwed by filter')
})
})
it('should throw RenderError when tag throws', function () {
var src = '{%throwingTag%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('RenderError');
expect(err.message).to.contain('intended render error');
});
});
it('should throw RenderError when tag rejects', function() {
var src = '{%rejectingTag%}';
return expect(engine.parseAndRender(src)).to.eventually
.then(function (err) {
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render error')
})
})
it('should throw RenderError when tag rejects', function () {
var src = '{%rejectingTag%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('RenderError');
expect(err.message).to.contain('intended render reject');
});
});
it('should throw RenderError when filter throws', function() {
var src = '{{1|throwingFilter}}';
return expect(engine.parseAndRender(src)).to.eventually
.then(function (err) {
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render reject')
})
})
it('should throw RenderError when filter throws', function () {
var src = '{{1|throwingFilter}}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('RenderError');
expect(err.message).to.contain('throwed by filter');
});
});
it('should not throw when variable undefined by default', function() {
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY');
});
it('should throw RenderError when variable not defined', function() {
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually
.then(function (err) {
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('throwed by filter')
})
})
it('should not throw when variable undefined by default', function () {
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY')
})
it('should throw RenderError when variable not defined', function () {
return expect(strictEngine.parseAndRender('{{a}}')).to.eventually
.be.rejected
.then(function(e) {
expect(e).to.have.property('name', 'RenderError');
expect(e.message).to.contain('undefined variable: a');
});
});
it('should contain template context in err.stack', function() {
var html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th'];
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'Error: intended render error',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.then(function (e) {
expect(e).to.have.property('name', 'RenderError')
expect(e.message).to.contain('undefined variable: a')
})
})
it('should contain template context in err.stack', function () {
var html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'Error: intended render error'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('intended render error, line:4');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('RenderError');
});
});
it('should contain original error info for {% layout %}', function() {
mock({
'/throwing-tag.html': [
'1st',
'2nd',
'3rd',
'X{%throwingTag%} Y',
'5th',
'{%block%}{%endblock%}',
'7th'
].join('\n')
});
var html = '{%layout "throwing-tag.html"%}';
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| {%block%}{%endblock%}',
' 7| 7th',
'Error: intended render error',
];
return expect(engine.parseAndRender(html)).to.eventually
.then(function (err) {
expect(err.message).to.equal('intended render error, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
})
it('should contain original error info for {% layout %}', function () {
mock({
'/throwing-tag.html': [
'1st',
'2nd',
'3rd',
'X{%throwingTag%} Y',
'5th',
'{%block%}{%endblock%}',
'7th'
].join('\n')
})
var html = '{%layout "throwing-tag.html"%}'
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| {%block%}{%endblock%}',
' 7| 7th',
'Error: intended render error'
]
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
console.log(err.message);
console.log(err.stack);
expect(err.message).to.equal('intended render error, file:/throwing-tag.html, line:4');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('RenderError');
});
});
it('should contain original error info for {% include %}', function() {
var origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th'];
mock({
'/throwing-tag.html': origin.join('\n')
});
var html = '{%include "throwing-tag.html"%}';
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'Error: intended render error',
];
return expect(engine.parseAndRender(html)).to.eventually
.then(function (err) {
console.log(err.message)
console.log(err.stack)
expect(err.message).to.equal('intended render error, file:/throwing-tag.html, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
})
it('should contain original error info for {% include %}', function () {
var origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
mock({
'/throwing-tag.html': origin.join('\n')
})
var html = '{%include "throwing-tag.html"%}'
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'Error: intended render error'
]
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('intended render error, file:/throwing-tag.html, line:4');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('RenderError');
});
});
it('should contain the whole template content in err.input', function() {
var html = 'bar\nfoo{%throwingTag%}\nfoo';
return expect(engine.parseAndRender(html)).to.eventually
.then(function (err) {
expect(err.message).to.equal('intended render error, file:/throwing-tag.html, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
})
it('should contain the whole template content in err.input', function () {
var html = 'bar\nfoo{%throwingTag%}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.input).to.equal(html);
expect(err.name).to.equal('RenderError');
});
});
it('should contain line number in err.line', function() {
var src = '1\n2\n{{1|throwingFilter}}\n4';
return expect(engine.parseAndRender(src)).to.eventually
.then(function (err) {
expect(err.input).to.equal(html)
expect(err.name).to.equal('RenderError')
})
})
it('should contain line number in err.line', function () {
var src = '1\n2\n{{1|throwingFilter}}\n4'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.line).to.equal(3);
expect(err.name).to.equal('RenderError');
});
});
it('should contain stack in err.stack', function() {
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually
.then(function (err) {
expect(err.line).to.equal(3)
expect(err.name).to.equal('RenderError')
})
})
it('should contain stack in err.stack', function () {
return expect(engine.parseAndRender('{%rejectingTag%}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.stack).to.contain('intended render reject');
expect(err.stack).to.match(/at .*:\d+:\d+\)/);
});
});
.then(function (err) {
expect(err.stack).to.contain('intended render reject')
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
})
})
it('should contain file path in err.file', function() {
var html = '<html>\n<head>\n\n{% throwingTag %}\n\n';
mock({
"/foo.html": html
});
return expect(engine.renderFile('/foo.html')).to.eventually
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
mock({
'/foo.html': html
})
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function(err) {
mock.restore();
expect(err.name).to.equal('RenderError');
expect(err.file).to.equal('/foo.html');
});
});
});
.then(function (err) {
mock.restore()
expect(err.name).to.equal('RenderError')
expect(err.file).to.equal('/foo.html')
})
})
})
describe('ParseError', function() {
beforeEach(function() {
engine = require('../..')();
engine.registerTag('throwsOnParse', {
parse: function() {
throw new Error('intended parse error');
}
});
});
it('should throw RenderError when filter not defined', function() {
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually
describe('ParseError', function () {
beforeEach(function () {
engine = require('../..')()
engine.registerTag('throwsOnParse', {
parse: function () {
throw new Error('intended parse error')
}
})
})
it('should throw RenderError when filter not defined', function () {
return expect(strictEngine.parseAndRender('{{1 | a}}')).to.eventually
.be.rejected
.then(function(e) {
expect(e).to.have.property('name', 'ParseError');
expect(e.message).to.contain('undefined filter: a');
});
});
it('should throw ParseError when tag not closed', function() {
return expect(engine.parseAndRender('{% if %}')).to.eventually
.then(function (e) {
expect(e).to.have.property('name', 'ParseError')
expect(e.message).to.contain('undefined filter: a')
})
})
it('should throw ParseError when tag not closed', function () {
return expect(engine.parseAndRender('{% if %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('tag {% if %} not closed');
});
});
it('should throw ParseError when tag parse throws', function() {
var src = '{%throwsOnParse%}';
return expect(engine.parseAndRender(src)).to.eventually
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag {% if %} not closed')
})
})
it('should throw ParseError when tag parse throws', function () {
var src = '{%throwsOnParse%}'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('intended parse error');
});
});
it('should throw ParseError when tag not found', function() {
var src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3';
return expect(engine.parseAndRender(src)).to.eventually
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('intended parse error')
})
})
it('should throw ParseError when tag not found', function () {
var src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
return expect(engine.parseAndRender(src)).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('tag -a not found');
});
});
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag -a not found')
})
})
it('should throw ParseError when tag not exist', function() {
return expect(engine.parseAndRender('{% a %}')).to.eventually
it('should throw ParseError when tag not exist', function () {
return expect(engine.parseAndRender('{% a %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.name).to.equal('ParseError');
expect(err.message).to.contain('tag a not found');
});
});
.then(function (err) {
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag a not found')
})
})
it('should contain template context in err.stack', function() {
var html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th'];
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{% a %} {% enda %} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'AssertionError: tag a not found',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
it('should contain template context in err.stack', function () {
var html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
var message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{% a %} {% enda %} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'AssertionError: tag a not found'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('tag a not found, line:4');
expect(err.stack).to.contain(message.join('\n'));
expect(err.name).to.equal('ParseError');
});
});
.then(function (err) {
expect(err.message).to.equal('tag a not found, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('ParseError')
})
})
it('should handle err.message when context not enough', function() {
var html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th'];
var message = [
' 1| 1st',
'>> 2| X{% a %} {% enda %} Y',
' 3| 3rd',
' 4| 4th',
'AssertionError: tag a not found',
];
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
it('should handle err.message when context not enough', function () {
var html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
var message = [
' 1| 1st',
'>> 2| X{% a %} {% enda %} Y',
' 3| 3rd',
' 4| 4th',
'AssertionError: tag a not found'
]
return expect(engine.parseAndRender(html.join('\n'))).to.eventually
.be.rejected
.then(function(err) {
expect(err.message).to.equal('tag a not found, line:2');
expect(err.stack).to.contain(message.join('\n'));
});
});
.then(function (err) {
expect(err.message).to.equal('tag a not found, line:2')
expect(err.stack).to.contain(message.join('\n'))
})
})
it('should contain the whole template content in err.input', function() {
var html = 'bar\nfoo{% a %}\nfoo';
return expect(engine.parseAndRender(html)).to.eventually
it('should contain the whole template content in err.input', function () {
var html = 'bar\nfoo{% a %}\nfoo'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.input).to.equal(html);
});
});
.then(function (err) {
expect(err.input).to.equal(html)
})
})
it('should contain line number in err.line', function() {
var html = '<html>\n<head>\n\n{% raw %}\n\n';
return expect(engine.parseAndRender(html)).to.eventually
it('should contain line number in err.line', function () {
var html = '<html>\n<head>\n\n{% raw %}\n\n'
return expect(engine.parseAndRender(html)).to.eventually
.be.rejected
.then(function(err) {
expect(err.line).to.equal(4);
});
});
.then(function (err) {
expect(err.line).to.equal(4)
})
})
it('should contain stack in err.stack', function() {
return expect(engine.parseAndRender('{% -a %}')).to.eventually
it('should contain stack in err.stack', function () {
return expect(engine.parseAndRender('{% -a %}')).to.eventually
.be.rejected
.then(function(err) {
expect(err.stack).to.contain('AssertionError: tag -a not found');
expect(err.stack).to.match(/at .*:\d+:\d+\)/);
});
});
.then(function (err) {
expect(err.stack).to.contain('AssertionError: tag -a not found')
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
})
})
it('should contain file path in err.file', function() {
var html = '<html>\n<head>\n\n{% raw %}\n\n';
mock({
"/foo.html": html
});
return expect(engine.renderFile('/foo.html')).to.eventually
it('should contain file path in err.file', function () {
var html = '<html>\n<head>\n\n{% raw %}\n\n'
mock({
'/foo.html': html
})
return expect(engine.renderFile('/foo.html')).to.eventually
.be.rejected
.then(function(err) {
mock.restore();
expect(err.name).to.equal('ParseError');
expect(err.file).to.equal('/foo.html');
});
});
});
});
.then(function (err) {
mock.restore()
expect(err.name).to.equal('ParseError')
expect(err.file).to.equal('/foo.html')
})
})
})
})
+92 -90
View File
@@ -1,92 +1,94 @@
const chai = require("chai");
const sinon = require('sinon');
const expect = chai.expect;
chai.use(require("chai-as-promised"));
chai.use(require("sinon-chai"));
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
chai.use(require('chai-as-promised'))
chai.use(require('sinon-chai'))
var P = require('../../src/util/promise.js');
var P = require('../../src/util/promise.js')
describe('util/promise', function() {
describe('.anySeries()', function() {
it('should resolve in series', function() {
var spy1 = sinon.spy(),
spy2 = sinon.spy();
return P
.anySeries(
['first', 'second'],
(item, idx) => new Promise(function(resolve, reject) {
if (idx === 0) {
setTimeout(function() {
spy1();
reject(new Error('first cb'));
}, 10);
} else {
spy2();
resolve('foo');
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1));
});
it('should reject when all rejected', function() {
var p = P.anySeries(['first', 'second', 'third'],
item => Promise.reject(new Error(item)));
return expect(p).to.be.rejectedWith("third");
});
it('should resolve the value that first callback resolved', () => {
var p = P.anySeries(['first', 'second'],
item => Promise.resolve(item));
return expect(p).to.eventually.equal('first');
});
it('should not call rest of callbacks once resolved', () => {
var spy = sinon.spy();
return P.anySeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy();
}
return Promise.resolve(item);
})
.then(() => expect(spy).to.not.have.been.called);
});
});
describe('.mapSeries()', function() {
it('should resolve when all resolved', function() {
var p = P.mapSeries(['first', 'second', 'third'],
item => Promise.resolve(item));
return expect(p).to.eventually.deep.equal(['first', 'second', "third"]);
});
it('should reject with the error that first callback rejected', () => {
var p = P.mapSeries(['first', 'second'],
item => Promise.reject(item));
return expect(p).to.rejectedWith('first');
});
it('should resolve in series', function() {
var spy1 = sinon.spy(),
spy2 = sinon.spy();
return P
.mapSeries(
['first', 'second'],
(item, idx) => new Promise(function(resolve, reject) {
if (idx === 0) {
setTimeout(function() {
spy1();
resolve('first cb');
}, 10);
} else {
spy2();
resolve('foo');
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1));
});
it('should not call rest of callbacks once rejected', () => {
var spy = sinon.spy();
return P.mapSeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy();
}
return Promise.reject(new Error(item));
})
.catch(() => expect(spy).to.not.have.been.called);
});
});
});
describe('util/promise', function () {
describe('.anySeries()', function () {
it('should resolve in series', function () {
var spy1 = sinon.spy()
var spy2 = sinon.spy()
return P
.anySeries(
['first', 'second'],
(item, idx) => new Promise(function (resolve, reject) {
if (idx === 0) {
setTimeout(function () {
spy1()
reject(new Error('first cb'))
}, 10)
} else {
spy2()
resolve('foo')
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
})
it('should reject when all rejected', function () {
var p = P.anySeries(['first', 'second', 'third'],
item => Promise.reject(new Error(item)))
return expect(p).to.be.rejectedWith('third')
})
it('should resolve the value that first callback resolved', () => {
var p = P.anySeries(['first', 'second'],
item => Promise.resolve(item))
return expect(p).to.eventually.equal('first')
})
it('should not call rest of callbacks once resolved', () => {
var spy = sinon.spy()
return P
.anySeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy()
}
return Promise.resolve(item)
})
.then(() => expect(spy).to.not.have.been.called)
})
})
describe('.mapSeries()', function () {
it('should resolve when all resolved', function () {
var p = P.mapSeries(['first', 'second', 'third'],
item => Promise.resolve(item))
return expect(p).to.eventually.deep.equal(['first', 'second', 'third'])
})
it('should reject with the error that first callback rejected', () => {
var p = P.mapSeries(['first', 'second'],
item => Promise.reject(item))
return expect(p).to.rejectedWith('first')
})
it('should resolve in series', function () {
var spy1 = sinon.spy()
var spy2 = sinon.spy()
return P
.mapSeries(
['first', 'second'],
(item, idx) => new Promise(function (resolve, reject) {
if (idx === 0) {
setTimeout(function () {
spy1()
resolve('first cb')
}, 10)
} else {
spy2()
resolve('foo')
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
})
it('should not call rest of callbacks once rejected', () => {
var spy = sinon.spy()
return P
.mapSeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy()
}
return Promise.reject(new Error(item))
})
.catch(() => expect(spy).to.not.have.been.called)
})
})
})
+110 -110
View File
@@ -1,120 +1,120 @@
const chai = require("chai");
const expect = chai.expect;
const chai = require('chai')
const expect = chai.expect
var t = require('../../src/util/strftime.js');
var t = require('../../src/util/strftime.js')
describe('util/strftime', function() {
var now;
before(function() {
mockUTC();
now = new Date('2016-01-04T13:15:23');
then = new Date('2016-03-06T03:05:03');
});
after(function() {
restoreUTC();
});
describe('util/strftime', function () {
var now
var then
before(function () {
mockUTC()
now = new Date('2016-01-04T13:15:23')
then = new Date('2016-03-06T03:05:03')
})
after(function () {
restoreUTC()
})
it('should format UTC datetime', function() {
expect(t(now, '%Y-%m-%dT%H:%M:%S')).to.equal('2016-01-04T13:15:23');
});
it('should format %A as Monday', function() {
expect(t(now, '%A')).to.equal('Monday');
});
it('should format %B as month name', function() {
expect(t(now, '%B')).to.equal('January');
});
it('should format %C as century', function() {
expect(t(now, '%C')).to.equal('20');
});
it('should format %c as local string', function() {
expect(t(now, '%c')).to.equal(now.toLocaleString());
});
it('should format %e as space padded date', function() {
expect(t(now, '%e')).to.equal(' 4');
});
it('should format %I as 0 padded hour12', function() {
expect(t(now, '%I')).to.equal('01');
});
it('should format %j as day of year', function() {
expect(t(then, '%j')).to.equal('066');
});
it('should format %k as space padded hour', function() {
expect(t(then, '%k')).to.equal(' 3');
});
it('should format %l as space padded hour12', function() {
expect(t(now, '%l')).to.equal(' 1');
});
it('should format %L as 0 padded millisecond', function() {
expect(t(then, '%L')).to.equal('000');
});
it('should format %p as upper cased am/pm', function() {
expect(t(now, '%p')).to.equal('PM');
expect(t(then, '%p')).to.equal('AM');
});
it('should format %P as lower cased am/pm', function() {
expect(t(now, '%P')).to.equal('pm');
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');
});
it('should format %s as UNIX seconds', function(){
expect(t(now, '%s')).to.be.match(/\d+/);
});
it('should format %u as day of week(1-7)', function(){
expect(t(now, '%u')).to.be.equal('1');
expect(t(then, '%u')).to.be.equal('7');
});
it('should format %U as week of year, starts with 0', function() {
expect(t(now, '%U')).to.equal('01');
});
it('should format %w as day of month(0-7)', function(){
expect(t(now, '%w')).to.be.equal('1');
expect(t(then, '%w')).to.be.equal('0');
});
it('should format %W as week of year, starts with 1', function(){
expect(t(now, '%W')).to.be.equal('01');
});
it('should format %x as local date string', function() {
expect(t(now, '%x')).to.equal(now.toLocaleDateString());
});
it('should format %X as local time string', function() {
expect(t(now, '%X')).to.equal(now.toLocaleTimeString());
});
it('should format %y as 2-digit year', function() {
expect(t(now, '%y')).to.equal('16');
});
it('should format %z as time zone', function() {
expect(t(now, '%z')).to.equal('+0800');
});
it('should escape %% as %', function() {
expect(t(now, '%%')).to.equal('%');
});
});
it('should format UTC datetime', function () {
expect(t(now, '%Y-%m-%dT%H:%M:%S')).to.equal('2016-01-04T13:15:23')
})
it('should format %A as Monday', function () {
expect(t(now, '%A')).to.equal('Monday')
})
it('should format %B as month name', function () {
expect(t(now, '%B')).to.equal('January')
})
it('should format %C as century', function () {
expect(t(now, '%C')).to.equal('20')
})
it('should format %c as local string', function () {
expect(t(now, '%c')).to.equal(now.toLocaleString())
})
it('should format %e as space padded date', function () {
expect(t(now, '%e')).to.equal(' 4')
})
it('should format %I as 0 padded hour12', function () {
expect(t(now, '%I')).to.equal('01')
})
it('should format %j as day of year', function () {
expect(t(then, '%j')).to.equal('066')
})
it('should format %k as space padded hour', function () {
expect(t(then, '%k')).to.equal(' 3')
})
it('should format %l as space padded hour12', function () {
expect(t(now, '%l')).to.equal(' 1')
})
it('should format %L as 0 padded millisecond', function () {
expect(t(then, '%L')).to.equal('000')
})
it('should format %p as upper cased am/pm', function () {
expect(t(now, '%p')).to.equal('PM')
expect(t(then, '%p')).to.equal('AM')
})
it('should format %P as lower cased am/pm', function () {
expect(t(now, '%P')).to.equal('pm')
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')
})
it('should format %s as UNIX seconds', function () {
expect(t(now, '%s')).to.be.match(/\d+/)
})
it('should format %u as day of week(1-7)', function () {
expect(t(now, '%u')).to.be.equal('1')
expect(t(then, '%u')).to.be.equal('7')
})
it('should format %U as week of year, starts with 0', function () {
expect(t(now, '%U')).to.equal('01')
})
it('should format %w as day of month(0-7)', function () {
expect(t(now, '%w')).to.be.equal('1')
expect(t(then, '%w')).to.be.equal('0')
})
it('should format %W as week of year, starts with 1', function () {
expect(t(now, '%W')).to.be.equal('01')
})
it('should format %x as local date string', function () {
expect(t(now, '%x')).to.equal(now.toLocaleDateString())
})
it('should format %X as local time string', function () {
expect(t(now, '%X')).to.equal(now.toLocaleTimeString())
})
it('should format %y as 2-digit year', function () {
expect(t(now, '%y')).to.equal('16')
})
it('should format %z as time zone', function () {
expect(t(now, '%z')).to.equal('+0800')
})
it('should escape %% as %', function () {
expect(t(now, '%%')).to.equal('%')
})
})
function mockUTC () {
var p = Date.prototype
function mockUTC() {
var p = Date.prototype;
p._getHours = p.getHours
p.getHours = p.getUTCHours
p._getHours = p.getHours;
p.getHours = p.getUTCHours;
p._getDays = p.getDays
p.getDays = p.getUTCDays
p._getDays = p.getDays;
p.getDays = p.getUTCDays;
p._getTimezoneOffset = p._getTimezoneOffset;
p.getTimezoneOffset = () => -480;
p._getTimezoneOffset = p._getTimezoneOffset
p.getTimezoneOffset = () => -480
}
function restoreUTC() {
var p = Date.prototype;
p.getHours = p._getHours;
p.getDays = p._getDays;
p.getTimezoneOffset = p._getTimezoneOffset;
function restoreUTC () {
var p = Date.prototype
p.getHours = p._getHours
p.getDays = p._getDays
p.getTimezoneOffset = p._getTimezoneOffset
}
+126 -126
View File
@@ -1,128 +1,128 @@
const chai = require("chai");
const sinon = require('sinon');
const expect = chai.expect;
const Errors = require('../../src/util/error.js');
chai.use(require("sinon-chai"));
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
const Errors = require('../../src/util/error.js')
chai.use(require('sinon-chai'))
var _ = require('../../src/util/underscore.js');
var _ = require('../../src/util/underscore.js')
describe('util/underscore', function() {
describe('.isError()', function() {
it('should return true for new Error', function() {
expect(_.isError(new Error())).to.be.true;
});
it('should return true for RenderError', function() {
var tpl = {
token: {
input: 'xx'
}
};
expect(_.isError(new Errors.RenderError(new Error(), tpl))).to.be.true;
});
it('should return true for RenderBreakError', function() {
expect(_.isError(new Errors.RenderBreakError())).to.be.true;
});
});
describe('.isString()', function() {
it('should return true for literal string', function() {
expect(_.isString('foo')).to.be.true;
});
it('should return true String instance', function() {
expect(_.isString(String('foo'))).to.be.true;
});
it('should return false for 123 ', function() {
expect(_.isString(123)).to.be.false;
});
});
describe('.forOwn()', function() {
it('should iterate all properties', function() {
var spy = sinon.spy();
var obj = {
foo: "bar"
};
_.forOwn(obj, spy);
expect(spy).to.have.been.calledWith('bar', 'foo', obj);
});
it('should not iterate over properties on prototype', function() {
var spy = sinon.spy();
var obj = Object.create({
bar: 'foo'
});
obj.foo = 'bar';
_.forOwn(obj, spy);
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;
});
});
describe('.isArray()', function() {
it('should return true for []', function() {
expect(_.isArray([])).to.be.true;
});
it('should return false for "foo"', function() {
expect(_.isArray("foo")).to.be.false;
});
});
describe('.echo()', function() {
it('should be transparent', function() {
expect(_.echo('foo')('bar')).to.equal('bar');
});
it('should log the arguments', function() {
var log = sinon.spy(console, 'log');
_.echo('foo')('bar');
expect(log).to.have.been.calledWith('[foo]', 'bar');
});
});
describe('.assign()', function() {
it('should handle null dst', function() {
expect(_.assign(null, {
foo: 'bar'
})).to.deep.equal({
foo: 'bar'
});
});
it('should assign 2 objects', function() {
var src = {
foo: 'foo',
bar: 'bar'
};
var dst = {
foo: 'bar',
kaa: 'kaa'
};
expect(_.assign(dst, src)).to.deep.equal({
foo: 'foo',
bar: 'bar',
kaa: 'kaa'
});
});
it('should assign 3 objects', function() {
expect(_.assign({
foo: 'foo'
}, {
bar: 'bar'
}, {
car: 'car'
})).to.deep.equal({
foo: 'foo',
bar: 'bar',
car: 'car'
});
});
});
describe('.uniq()', function() {
it('should handle empty array', function() {
expect(_.uniq([])).to.deep.equal([]);
});
it('should do uniq', function() {
expect(_.uniq([1, 'a', 'a', 1])).to.deep.equal([1, 'a']);
});
});
});
describe('util/underscore', function () {
describe('.isError()', function () {
it('should return true for new Error', function () {
expect(_.isError(new Error())).to.be.true
})
it('should return true for RenderError', function () {
var tpl = {
token: {
input: 'xx'
}
}
expect(_.isError(new Errors.RenderError(new Error(), tpl))).to.be.true
})
it('should return true for RenderBreakError', function () {
expect(_.isError(new Errors.RenderBreakError())).to.be.true
})
})
describe('.isString()', function () {
it('should return true for literal string', function () {
expect(_.isString('foo')).to.be.true
})
it('should return true String instance', function () {
expect(_.isString(String('foo'))).to.be.true
})
it('should return false for 123 ', function () {
expect(_.isString(123)).to.be.false
})
})
describe('.forOwn()', function () {
it('should iterate all properties', function () {
var spy = sinon.spy()
var obj = {
foo: 'bar'
}
_.forOwn(obj, spy)
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
})
it('should not iterate over properties on prototype', function () {
var spy = sinon.spy()
var obj = Object.create({
bar: 'foo'
})
obj.foo = 'bar'
_.forOwn(obj, spy)
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
})
})
describe('.isArray()', function () {
it('should return true for []', function () {
expect(_.isArray([])).to.be.true
})
it('should return false for "foo"', function () {
expect(_.isArray('foo')).to.be.false
})
})
describe('.echo()', function () {
it('should be transparent', function () {
expect(_.echo('foo')('bar')).to.equal('bar')
})
it('should log the arguments', function () {
var log = sinon.spy(console, 'log')
_.echo('foo')('bar')
expect(log).to.have.been.calledWith('[foo]', 'bar')
})
})
describe('.assign()', function () {
it('should handle null dst', function () {
expect(_.assign(null, {
foo: 'bar'
})).to.deep.equal({
foo: 'bar'
})
})
it('should assign 2 objects', function () {
var src = {
foo: 'foo',
bar: 'bar'
}
var dst = {
foo: 'bar',
kaa: 'kaa'
}
expect(_.assign(dst, src)).to.deep.equal({
foo: 'foo',
bar: 'bar',
kaa: 'kaa'
})
})
it('should assign 3 objects', function () {
expect(_.assign({
foo: 'foo'
}, {
bar: 'bar'
}, {
car: 'car'
})).to.deep.equal({
foo: 'foo',
bar: 'bar',
car: 'car'
})
})
})
describe('.uniq()', function () {
it('should handle empty array', function () {
expect(_.uniq([])).to.deep.equal([])
})
it('should do uniq', function () {
expect(_.uniq([1, 'a', 'a', 1])).to.deep.equal([1, 'a'])
})
})
})