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