feature: get nyc, babel and coveralls working

This commit is contained in:
harttle
2018-08-26 21:54:35 +08:00
parent d828c4021e
commit 31c39561c9
50 changed files with 361 additions and 482 deletions
+92
View File
@@ -0,0 +1,92 @@
import chai from 'chai'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
import Filter from '../../src/filter.js'
import {factory as scopeFactory} from '../../src/scope.js'
chai.use(sinonChai)
const expect = chai.expect
const filter = Filter()
describe('filter', function () {
let scope
beforeEach(function () {
filter.clear()
scope = scopeFactory()
})
it('should return default filter when not registered', function () {
const result = filter.construct('foo')
expect(result.name).to.equal('foo')
})
it('should throw when filter name illegal', function () {
expect(function () {
filter.construct('/')
}).to.throw(/illegal filter/)
})
it('should parse argument syntax', function () {
filter.register('foo', x => x)
const f = filter.construct('foo: a, "b"')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['a', '"b"'])
})
it('should register a simple filter', function () {
filter.register('upcase', x => x.toUpperCase())
expect(filter.construct('upcase').render('foo', scope)).to.equal('FOO')
})
it('should register a argumented filter', function () {
filter.register('add', (a, b) => a + b)
expect(filter.construct('add: 2').render(3, scope)).to.equal(5)
})
it('should register a multi-argumented filter', function () {
filter.register('add', (a, b, c) => a + b + c)
expect(filter.construct('add: 2, "c"').render(3, scope)).to.equal('5c')
})
it('should call filter with corrct arguments', function () {
const spy = sinon.spy()
filter.register('foo', spy)
filter.construct('foo: 33').render('foo', scope)
expect(spy).to.have.been.calledWith('foo', 33)
})
it('should support arguments as named key/values', function () {
filter.register('foo', x => x)
const f = filter.construct('foo: key1: "literal1", key2: value2')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
})
it('should support arguments as named key/values with inline literals', function () {
filter.register('foo', x => x)
const f = filter.construct('foo: "test0", key1: "literal1", key2: value2')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ '"test0"', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
})
it('should support arguments as named key/values with inline values', function () {
filter.register('foo', x => x)
const f = filter.construct('foo: test0, key1: "literal1", key2: value2')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal([ 'test0', '\'key1\'', '"literal1"', '\'key2\'', 'value2' ])
})
it('should support argument values named same as keys', function () {
filter.register('foo', x => x)
const f = filter.construct('foo: a: a')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['\'a\'', 'a'])
})
it('should support argument literals named same as keys', function () {
filter.register('foo', x => x)
const f = filter.construct('foo: a: "a"')
expect(f.name).to.equal('foo')
expect(f.args).to.deep.equal(['\'a\'', '"a"'])
})
})
+412
View File
@@ -0,0 +1,412 @@
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import Liquid from '../../src/index'
chai.use(chaiAsPromised)
const liquid = new Liquid()
const expect = chai.expect
const ctx = {
date: new Date(),
foo: 'bar',
arr: [-2, 'a'],
obj: {
foo: 'bar'
},
func: function () {},
posts: [{
category: 'foo'
}, {
category: 'bar'
}]
}
function test (src, dst) {
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
}
describe('filters', function () {
describe('abs', function () {
it('should return 3 for -3', () => test('{{ -3 | abs }}', '3'))
it('should return 2 for arr[0]', () => test('{{ arr[0] | abs }}', '2'))
it('should return convert string', () => test('{{ "-3" | abs }}', '3'))
})
describe('append', function () {
it('should return "-3abc" for -3, "abc"',
() => test('{{ -3 | append: "abc" }}', '-3abc'))
it('should return "abar" for "a",foo', () => test('{{ "a" | append: foo }}', 'abar'))
})
it('should support capitalize', () => test('{{ "i am good" | capitalize }}', 'I am good'))
describe('ceil', function () {
it('should return "2" for 1.2', () => test('{{ 1.2 | ceil }}', '2'))
it('should return "2" for 2.0', () => test('{{ 2.0 | ceil }}', '2'))
it('should return "4" for 3.5', () => test('{{ "3.5" | ceil }}', '4'))
it('should return "184" for 183.357', () => test('{{ 183.357 | ceil }}', '184'))
})
describe('concat', function () {
it('should concat arrays', () => test(`
{%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
{%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
{%- assign everything = fruits | concat: vegetables -%}
{%- for item in everything -%}
- {{ item }}
{% endfor -%}`, `- apples
- oranges
- peaches
- carrots
- turnips
- potatoes
`))
it('should support chained concat', () => test(`
{%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
{%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
{%- assign furniture = "chairs, tables, shelves" | split: ", " -%}
{%- assign everything = fruits | concat: vegetables | concat: furniture -%}
{%- for item in everything -%}
- {{ item }}
{% endfor -%}`, `- apples
- oranges
- peaches
- carrots
- turnips
- potatoes
- chairs
- tables
- shelves
`))
})
describe('date', function () {
it('should support date: %a %b %d %Y', function () {
const str = ctx.date.toDateString()
return test('{{ date | date:"%a %b %d %Y"}}', str)
})
it('should create a new Date when given "now"', function () {
return test('{{ "now" | date: "%Y"}}', (new Date()).getFullYear().toString())
})
it('should parse as Date when given UTC string', function () {
return test('{{ "1991-02-22T00:00:00" | date: "%Y"}}', '1991')
})
it('should render string as string if not valid', function () {
return test('{{ "foo" | date: "%Y"}}', 'foo')
})
it('should render object as string if not valid', function () {
return test('{{ obj | date: "%Y"}}', '{"foo":"bar"}')
})
})
describe('default', function () {
it('should use default when falsy', () => test('{{false |default: "a"}}', 'a'))
it('should not use default when truthy', () => test('{{true |default: "a"}}', 'true'))
})
describe('divided_by', function () {
it('should return 2 for 4,2', () => test('{{4 | divided_by: 2}}', '2'))
it('should return 4 for 16,4', () => test('{{16 | divided_by: 4}}', '4'))
it('should return 1 for 5,3', () => test('{{5 | divided_by: 3}}', (5 / 3).toString()))
it('should convert string to number', () => test('{{"6" | divided_by: "3"}}', '2'))
})
describe('downcase', function () {
it('should return "parker moore" for "Parker Moore"',
() => test('{{ "Parker Moore" | downcase }}', 'parker moore'))
it('should return "apple" for "apple"',
() => test('{{ "apple" | downcase }}', 'apple'))
})
describe('escape', function () {
it('should escape \' and &', function () {
return test('{{ "Have you read \'James & the Giant Peach\'?" | escape }}',
'Have you read 'James & the Giant Peach'?')
})
it('should escape normal string', function () {
return test('{{ "Tetsuro Takara" | escape }}', 'Tetsuro Takara')
})
it('should escape function', function () {
return test('{{ func | escape }}', 'function func() {}')
})
})
describe('escape_once', function () {
it('should do escape', () =>
test('{{ "1 < 2 & 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
it('should not escape twice',
() => test('{{ "1 &lt; 2 &amp; 3" | escape_once }}', '1 &lt; 2 &amp; 3'))
})
it('should support split/first', function () {
const src = '{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}' +
'{{ my_array | first }}'
return test(src, 'apples')
})
describe('floor', function () {
it('should return "1" for 1.2', () => test('{{ 1.2 | floor }}', '1'))
it('should return "2" for 2.0', () => test('{{ 2.0 | floor }}', '2'))
it('should return "183" for 183.357', () => test('{{ 183.357 | floor }}', '183'))
it('should return "3" for 3.5', () => test('{{ "3.5" | floor }}', '3'))
})
it('should support join', function () {
const src = '{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{{ beatles | join: " and " }}'
return test(src, 'John and Paul and George and Ringo')
})
it('should support split/last', function () {
const src = '{% assign my_array = "zebra, octopus, giraffe, tiger" | split: ", " %}' +
'{{ my_array|last }}'
return test(src, 'tiger')
})
it('should support lstrip', function () {
const src = '{{ " So much room for activities! " | lstrip }}'
return test(src, 'So much room for activities! ')
})
it('should support map', function () {
return test('{{posts | map: "category"}}', '["foo","bar"]')
})
describe('minus', function () {
it('should return "2" for 4,2', () => test('{{ 4 | minus: 2 }}', '2'))
it('should return "12" for 16,4', () => test('{{ 16 | minus: 4 }}', '12'))
it('should return "171.357" for 183.357,12',
() => test('{{ 183.357 | minus: 12 }}', '171.357'))
it('should convert first arg as number', () => test('{{ "4" | minus: 1 }}', '3'))
it('should convert both args as number', () => test('{{ "4" | minus: "1" }}', '3'))
})
describe('modulo', function () {
it('should return "1" for 3,2', () => test('{{ 3 | modulo: 2 }}', '1'))
it('should return "3" for 24,7', () => test('{{ 24 | modulo: 7 }}', '3'))
it('should return "3.357" for 183.357,12',
() => test('{{ 183.357 | modulo: 12 }}', '3.357'))
it('should convert string', () => test('{{ "24" | modulo: "7" }}', '3'))
})
it('should support string_with_newlines', function () {
const src = '{% capture string_with_newlines %}\n' +
'Hello\n' +
'there\n' +
'{% endcapture %}' +
'{{ string_with_newlines | newline_to_br }}'
const dst = '<br />' +
'Hello<br />' +
'there<br />'
return test(src, dst)
})
describe('plus', function () {
it('should return "6" for 4,2', () => test('{{ 4 | plus: 2 }}', '6'))
it('should return "20" for 16,4', () => test('{{ 16 | plus: 4 }}', '20'))
it('should return "195.357" for 183.357,12',
() => test('{{ 183.357 | plus: 12 }}', '195.357'))
it('should convert first arg as number', () => test('{{ "4" | plus: 2 }}', '6'))
it('should convert both args as number', () => test('{{ "4" | plus: "2" }}', '6'))
})
it('should support prepend', function () {
return test('{% assign url = "liquidmarkup.com" %}' +
'{{ "/index.html" | prepend: url }}',
'liquidmarkup.com/index.html')
})
it('should support remove', function () {
return test('{{ "I strained to see the train through the rain" | remove: "rain" }}',
'I sted to see the t through the ')
})
it('should support remove_first', function () {
return test('{{ "I strained to see the train through the rain" | remove_first: "rain" }}',
'I sted to see the train through the rain')
})
it('should support replace', function () {
return test('{{ "Take my protein pills and put my helmet on" | replace: "my", "your" }}',
'Take your protein pills and put your helmet on')
})
it('should support replace_first', function () {
return test('{% assign my_string = "Take my protein pills and put my helmet on" %}\n' +
'{{ my_string | replace_first: "my", "your" }}',
'\nTake your protein pills and put my helmet on')
})
it('should support reverse', function () {
return test('{{ "Ground control to Major Tom." | split: "" | reverse | join: "" }}',
'.moT rojaM ot lortnoc dnuorG')
})
describe('round', function () {
it('should return "1" for 1.2', () => test('{{1.2|round}}', '1'))
it('should return "3" for 2.7', () => test('{{2.7|round}}', '3'))
it('should return "183.36" for 183.357,2',
() => test('{{183.357|round: 2}}', '183.36'))
it('should convert string to number', () => test('{{"2.7"|round}}', '3'))
})
it('should support rstrip', function () {
return test('{{ " So much room for activities! " | rstrip }}',
' So much room for activities!')
})
describe('size', function () {
it('should return string length',
() => test('{{ "Ground control to Major Tom." | size }}', '28'))
it('should return array size', function () {
return test('{% assign my_array = "apples, oranges, peaches, plums"' +
' | split: ", " %}{{ my_array | size }}',
'4')
})
it('should also be used with dot notation - string',
() => test('{% assign my_string = "Ground control to Major Tom." %}{{ my_string.size }}', '28'))
it('should also be used with dot notation - array',
() => test('{% assign my_array = "apples, oranges, peaches, plums" | split: ", " %}{{ my_array.size }}', '4'))
})
describe('slice', function () {
it('should slice first char by 0', () => test('{{ "Liquid" | slice: 0 }}', 'L'))
it('should slice third char by 2', () => test('{{ "Liquid" | slice: 2 }}', 'q'))
it('should slice substr by 2,5', () => test('{{ "Liquid" | slice: 2, 5 }}', 'quid'))
it('should slice substr by -3,2', () => test('{{ "Liquid" | slice: -3, 2 }}', 'ui'))
})
it('should support sort', function () {
return test('{% assign my_array = "zebra, octopus, giraffe, Sally Snake"' +
' | split: ", " %}' +
'{{ my_array | sort | join: ", " }}',
'Sally Snake, giraffe, octopus, zebra')
})
it('should support split', function () {
return test('{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}' +
'{% for member in beatles %}' +
'{{ member }} ' +
'{% endfor %}',
'John Paul George Ringo ')
})
it('should support strip', function () {
return test('{{ " So much room for activities! " | strip }}',
'So much room for activities!')
})
describe('strip_html', function () {
it('should strip all tags', function () {
return test('{{ "Have <em>you</em> read <cite><a href=&quot;https://en.wikipedia.org/wiki/Ulysses_(novel)&quot;>Ulysses</a></cite>?" | strip_html }}',
'Have you read Ulysses?')
})
it('should strip all comment tags', function () {
return test('{{ "<!--Have you read-->Ulysses?" | strip_html }}',
'Ulysses?')
})
it('should strip all style tags and their contents', function () {
return test('{{ "<style>cite { font-style: italic; }</style><cite>Ulysses<cite>?" | strip_html }}',
'Ulysses?')
})
it('should strip all scripts tags and their contents', function () {
return test('{{ "<script async>console.log(\'hello world\')</script><cite>Ulysses<cite>?" | strip_html }}',
'Ulysses?')
})
it('should strip until empty', function () {
return test('{{"<br/><br />< p ></p></ p >" | strip_html }}', '')
})
})
it('should support strip_newlines', function () {
return test('{% capture string_with_newlines %}\n' +
'Hello\nthere\n{% endcapture %}' +
'{{ string_with_newlines | strip_newlines }}',
'Hellothere')
})
describe('times', function () {
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'))
it('should return "168" for 24,7', () => test('{{ 24 | times: 7 }}', '168'))
it('should return "2200.284" for 183.357,12',
() => test('{{ 183.357 | times: 12 }}', '2200.284'))
it('should convert string to number', () => test('{{ "24" | times: "7" }}', '168'))
})
describe('truncate', function () {
it('should truncate when string too long', function () {
return test('{{ "Ground control to Major Tom." | truncate: 20 }}',
'Ground control to...')
})
it('should not truncate when string not long enough', function () {
return test('{{ "Ground control to Major Tom." | truncate: 80 }}',
'Ground control to Major Tom.')
})
it('should truncate with custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncate: 25,", and so on" }}',
'Ground control, and so on')
})
it('should truncate with empty custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncate: 20, "" }}',
'Ground control to Ma')
})
it('should not truncate when short enough', function () {
return test('{{ "12345" | truncate: 5 }}', '12345')
})
it('should default to 16', function () {
return test('{{ "1234567890abcdefghi" | truncate }}', '1234567890abc...')
})
})
describe('truncatewords', function () {
it('should truncate when too many words', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
'Ground control to...')
})
it('should not truncate when not enough words', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 8 }}',
'Ground control to Major Tom.')
})
it('should truncate with custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "--" }}',
'Ground control to--')
})
it('should truncate with empty custom ellipsis', function () {
return test('{{ "Ground control to Major Tom." | truncatewords: 3, "" }}',
'Ground control to')
})
})
describe('uniq', function () {
it('should uniq string list', function () {
return test(
'{% assign my_array = "ants, bugs, bees, bugs, ants" | split: ", " %}' +
'{{ my_array | uniq | join: ", " }}',
'ants, bugs, bees'
)
})
it('should uniq falsy value', function () {
return test('{{"" | uniq | join: ","}}', '')
})
})
it('should support upcase', () => test('{{ "Parker Moore" | upcase }}', 'PARKER MOORE'))
describe('url_encode', function () {
it('should encode @',
() => test('{{ "[email protected]" | url_encode }}', 'john%40liquid.com'))
it('should encode <space>',
() => test('{{ "Tetsuro Takara" | url_encode }}', 'Tetsuro%20Takara'))
})
describe('obj_test', function () {
liquid.registerFilter('obj_test', function () {
return Array.prototype.slice.call(arguments).join(',')
})
it('should support object', () => test(`{{ "a" | obj_test: k1: "v1", k2: foo }}`, 'a,k1,v1,k2,bar'))
it('should support mixed object', () => test(`{{ "a" | obj_test: "something", k1: "v1", k2: foo }}`, 'a,something,k1,v1,k2,bar'))
})
})
+131
View File
@@ -0,0 +1,131 @@
const chai = require('chai')
const expect = chai.expect
const lexical = require('../../src/lexical.js')
describe('lexical', function () {
it('should test filter syntax', function () {
expect(lexical.filterLine.test('abs')).to.equal(true)
expect(lexical.filterLine.test('plus:1')).to.equal(true)
expect(lexical.filterLine.test('replace: "a", b')).to.equal(true)
expect(lexical.filterLine.test('foo: a, "b"')).to.equal(true)
expect(lexical.filterLine.test('abs | another')).to.equal(false)
expect(lexical.filterLine.test('join: "," | another')).to.equal(false)
expect(lexical.filterLine.test('obj_test: k1: "v1", k2: "v2"')).to.equal(true)
})
it('should test boolean literal', function () {
expect(lexical.isLiteral('true')).to.equal(true)
expect(lexical.isLiteral('TrUE')).to.equal(true)
expect(lexical.isLiteral('false')).to.equal(true)
})
it('should test number literal', function () {
expect(lexical.isLiteral('2.3')).to.equal(true)
expect(lexical.isLiteral('.3')).to.equal(true)
expect(lexical.isLiteral('-3.')).to.equal(true)
expect(lexical.isLiteral('23')).to.equal(true)
})
it('should test range literal', function () {
expect(lexical.isRange('(12..32)')).to.equal(true)
expect(lexical.isRange('(12..foo)')).to.equal(true)
expect(lexical.isRange('(foo.bar..foo)')).to.equal(true)
})
it('should test string literal', function () {
expect(lexical.isLiteral('""')).to.equal(true)
expect(lexical.isLiteral('"a\'b"')).to.equal(true)
expect(lexical.isLiteral("''")).to.equal(true)
expect(lexical.isLiteral("'a bcd'")).to.equal(true)
})
describe('.isVariable()', function () {
it('should return true for foo', function () {
expect(lexical.isVariable('foo')).to.equal(true)
})
it('should return true for.bar.foo', function () {
expect(lexical.isVariable('foo.bar.foo')).to.equal(true)
})
it('should return true for foo[0].b', function () {
expect(lexical.isVariable('foo[0].b')).to.equal(true)
})
it('should return true for 0a', function () {
expect(lexical.isVariable('0a')).to.equal(true)
})
it('should return true for foo[a.b]', function () {
expect(lexical.isVariable('foo[a.b]')).to.equal(true)
})
it('should return true for foo[a.b]', function () {
expect(lexical.isVariable("foo['a[0]']")).to.equal(true)
})
it('should return true for "var-1"', function () {
expect(lexical.isVariable('var-1')).to.equal(true)
})
it('should return true for "-var"', function () {
expect(lexical.isVariable('-var')).to.equal(true)
})
it('should return true for "var-"', function () {
expect(lexical.isVariable('var-')).to.equal(true)
})
it('should return true for "3-4"', function () {
expect(lexical.isVariable('3-4')).to.equal(true)
})
})
it('should test none literal', function () {
expect(lexical.isLiteral('2a')).to.equal(false)
expect(lexical.isLiteral('"x')).to.equal(false)
expect(lexical.isLiteral('a2')).to.equal(false)
})
it('should test none variable', function () {
expect(lexical.isVariable('a.')).to.equal(false)
expect(lexical.isVariable('.b')).to.equal(false)
expect(lexical.isVariable('.')).to.equal(false)
expect(lexical.isVariable('[0][12].bar[0]')).to.equal(false)
})
describe('.parseLiteral()', function () {
it('should parse boolean literal', function () {
expect(lexical.parseLiteral('true')).to.equal(true)
expect(lexical.parseLiteral('TrUE')).to.equal(true)
expect(lexical.parseLiteral('false')).to.equal(false)
})
it('should parse number literal', function () {
expect(lexical.parseLiteral('2.3')).to.equal(2.3)
expect(lexical.parseLiteral('.32')).to.equal(0.32)
expect(lexical.parseLiteral('-23.')).to.equal(-23)
expect(lexical.parseLiteral('23')).to.equal(23)
})
it('should parse string literal', function () {
expect(lexical.parseLiteral('"ab\'c"')).to.equal("ab'c")
})
it('should throw if non-literal', function () {
const fn = () => lexical.parseLiteral('a')
expect(fn).to.throw("cannot parse 'a' as literal")
})
})
describe('.matchValue()', function () {
it('should match -5-5', function () {
const match = lexical.matchValue('-5-5')
expect(match && match[0]).to.equal('-5-5')
})
it('should match 4-3', function () {
const match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match 4-3', function () {
const match = lexical.matchValue('4-3')
expect(match && match[0]).to.equal('4-3')
})
it('should match var-1', function () {
const match = lexical.matchValue('var-1')
expect(match && match[0]).to.equal('var-1')
})
})
})
+44
View File
@@ -0,0 +1,44 @@
import chai from 'chai'
import mock from 'mock-fs'
import Liquid from '../../../src'
import chaiAsPromised from 'chai-as-promised'
const expect = chai.expect
chai.use(chaiAsPromised)
describe('cache options', function () {
let engine
beforeEach(function () {
engine = Liquid({
root: '/root/',
extname: '.html'
})
mock({ '/root/files/foo.html': 'foo' })
})
afterEach(function () {
mock.restore()
})
it('should be disabled by default', function () {
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('bar'))
})
it('should respect cache=true option', function () {
engine = Liquid({
root: '/root/',
extname: '.html',
cache: true
})
return engine.renderFile('files/foo')
.then(x => expect(x).to.equal('foo'))
.then(() => mock({
'/root/files/foo.html': 'bar'
}))
.then(() => engine.renderFile('files/foo'))
.then(x => expect(x).to.equal('foo'))
})
})
+36
View File
@@ -0,0 +1,36 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('strict options', function () {
let engine
const ctx = {}
beforeEach(function () {
engine = Liquid({
root: '/root/',
extname: '.html'
})
})
it('should not throw when strict_variables false (default)', function () {
return expect(engine.parseAndRender('before{{notdefined}}after', ctx)).to
.eventually.equal('beforeafter')
})
it('should throw when strict_variables true', function () {
const tpl = engine.parse('before{{notdefined}}after')
const opts = {
strict_variables: true
}
return expect(engine.render(tpl, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
it('should pass strict_variables to render by parseAndRender', function () {
const html = 'before{{notdefined}}after'
const opts = {
strict_variables: true
}
return expect(engine.parseAndRender(html, ctx, opts)).to
.be.rejectedWith(/undefined variable: notdefined/)
})
})
+86
View File
@@ -0,0 +1,86 @@
import chai from 'chai'
import Liquid from '../../../src'
import chaiAsPromised from 'chai-as-promised'
const expect = chai.expect
chai.use(chaiAsPromised)
describe('trimming', function () {
const ctx = {name: 'harttle'}
describe('tag trimming', function () {
it('should respect trim_tag_left', function () {
const engine = Liquid({ trim_tag_left: true })
return expect(engine.parseAndRender(' \n \t{%if true%}foo{%endif%} '))
.to.eventually.equal('foo ')
})
it('should respect trim_tag_right', function () {
const engine = Liquid({ trim_tag_right: true })
return expect(engine.parseAndRender('\t{%if true%}foo{%endif%} \n'))
.to.eventually.equal('\tfoo')
})
it('should not trim value', function () {
const engine = Liquid({ trim_tag_left: true, trim_tag_right: true })
return expect(engine.parseAndRender('{%if true%}a {{name}} b{%endif%}', ctx))
.to.eventually.equal('a harttle b')
})
})
describe('value trimming', function () {
it('should respect trim_value_left', function () {
const engine = Liquid({ trim_value_left: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal('harttle ')
})
it('should respect trim_value_right', function () {
const engine = Liquid({ trim_value_right: true })
return expect(engine.parseAndRender(' \n \t{{name}} ', ctx))
.to.eventually.equal(' \n \tharttle')
})
it('should respect not trim tag', function () {
const engine = Liquid({ trim_value_left: true, trim_value_right: true })
return expect(engine.parseAndRender('\t{% if true %} aha {%endif%}\t'))
.to.eventually.equal('\t aha \t')
})
})
describe('greedy', function () {
const src = '\n {%-if true-%}\n a \n{{-name-}}{%-endif-%}\n '
it('should enable greedy by default', function () {
const engine = Liquid()
return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('aharttle')
})
it('should respect to greedy:false by default', function () {
const engine = Liquid({greedy: false})
return expect(engine.parseAndRender(src, ctx))
.to.eventually.equal('\n a \nharttle ')
})
})
describe('markup', function () {
it('should support trim using markup', function () {
const engine = Liquid()
const src = [
'{%- assign username = "John G. Chalmers-Smith" -%}',
'{%- if username and username.length > 10 -%}',
' Wow, {{ username }}, you have a long name!',
'{%- else -%}',
' Hello there!',
'{%- endif -%}'
].join('\n')
const dst = 'Wow, John G. Chalmers-Smith, you have a long name!'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
it('should not trim when not specified', function () {
const engine = Liquid()
const src = [
'{% assign username = "John G. Chalmers-Smith" %}',
'{% if username and username.length > 10 %}',
' Wow, {{ username }}, you have a long name!',
'{% else %}',
' Hello there!',
'{% endif %}'
].join('\n')
const dst = '\n\n Wow, John G. Chalmers-Smith, you have a long name!\n'
return expect(engine.parseAndRender(src)).to.eventually.equal(dst)
})
})
})
+49
View File
@@ -0,0 +1,49 @@
import chai from 'chai'
import sinonChai from 'sinon-chai'
import Filter from '../../src/filter.js'
import Tag from '../../src/tag.js'
import Template from '../../src/parser.js'
const expect = chai.expect
const filter = Filter()
const tag = Tag()
chai.use(sinonChai)
describe('template', function () {
let template
const add = (l, r) => l + r
beforeEach(function () {
filter.clear()
filter.register('add', add)
tag.clear()
template = Template(tag, filter)
})
it('should throw when value string illegal', function () {
expect(function () {
template.parseValue('/')
}).to.throw(/illegal value string/)
})
it('should parse value string', function () {
const tpl = template.parseValue('foo')
expect(tpl.type).to.equal('value')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters).to.deep.equal([])
})
it('should parse value string with a simple filter', function () {
const tpl = template.parseValue('foo | add: 3, "foo"')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(1)
expect(tpl.filters[0].filter).to.equal(add)
})
it('should parse value string with filters', function () {
const tpl = template.parseValue('foo | add: "|" | add')
expect(tpl.initial).to.equal('foo')
expect(tpl.filters.length).to.equal(2)
})
})
+102
View File
@@ -0,0 +1,102 @@
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import sinonChai from 'sinon-chai'
import sinon from 'sinon'
import Tag from '../../src/tag.js'
import {factory as scopeFactory} from '../../src/scope.js'
import Filter from '../../src/filter'
import Render from '../../src/render.js'
import parser from '../../src/parser.js'
chai.use(sinonChai)
chai.use(chaiAsPromised)
const expect = chai.expect
const tag = Tag()
const filter = Filter()
const Template = parser(tag, filter)
let render
describe('render', function () {
beforeEach(function () {
filter.clear()
tag.clear()
render = Render()
})
describe('.renderTemplates()', function () {
it('should throw when scope undefined', function () {
expect(render.renderTemplates([])).to.be.rejectedWith(/scope undefined/)
})
it('should render html', function () {
const scope = scopeFactory({})
return expect(render.renderTemplates([{type: 'html', value: '<p>'}], scope)).to.eventually.equal('<p>')
})
})
describe('.renderValue()', function () {
it('should respect to .to_liquid() method', function () {
const scope = scopeFactory({
bar: { to_liquid: x => 'custom' }
})
const tpl = Template.parseValue('bar')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('custom')
})
it('should stringify objects', function () {
const scope = scopeFactory({
foo: { obj: { arr: ['a', 2] } }
})
const tpl = Template.parseValue('foo')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"obj":{"arr":["a",2]}}')
})
it('should skip circular property', function () {
const ctx = { foo: { num: 2 }, bar: 'bar' }
ctx.foo.circular = ctx
const scope = scopeFactory(ctx)
const tpl = Template.parseValue('foo')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"num":2,"circular":{"bar":"bar"}}')
})
it('should skip function property', function () {
const scope = scopeFactory({obj: {foo: 'foo', bar: x => x}})
const tpl = Template.parseValue('obj')
return expect(render.renderValue(tpl, scope)).to.eventually.equal('{"foo":"foo"}')
})
})
describe('.evalValue()', function () {
it('should throw when scope undefined', function () {
expect(function () {
render.evalValue()
}).to.throw(/scope undefined/)
})
it('should eval value', function () {
filter.register('date', (l, r) => l + r)
filter.register('time', (l, r) => l + 3 * r)
const tpl = Template.parseValue('foo.bar[0] | date: "b" | time:2')
const scope = scopeFactory({
foo: { bar: ['a'] }
})
expect(render.evalValue(tpl, scope)).to.equal('ab6')
})
it('should reserve type', function () {
filter.register('arr', () => [1])
const tpl = Template.parseValue('"x" | arr')
expect(render.evalValue(tpl, scopeFactory())).to.deep.equal([1])
})
it('should eval filter with correct arguments', function () {
const date = sinon.stub().returns('y')
const time = sinon.spy()
filter.register('date', date)
filter.register('time', time)
const tpl = Template.parseValue('foo.bar | date: "b" | time:2')
const scope = scopeFactory({
foo: {bar: 'bar'}
})
render.evalValue(tpl, scope)
expect(date).to.have.been.calledWith('bar', 'b')
expect(time).to.have.been.calledWith('y', 2)
})
})
})
+250
View File
@@ -0,0 +1,250 @@
import chai from 'chai'
import {factory as scopeFactory} from '../../src/scope.js'
const expect = chai.expect
describe('scope', function () {
let scope, ctx
beforeEach(function () {
ctx = {
foo: 'zoo',
bar: {
zoo: 'coo',
'Mr.Smith': 'John',
arr: ['a', 'b']
}
}
scope = scopeFactory(ctx)
})
describe('#propertyAccessSeq()', function () {
it('should handle dot syntax', function () {
expect(scope.propertyAccessSeq('foo.bar'))
.to.deep.equal(['foo', 'bar'])
})
it('should handle [<String>] syntax', function () {
expect(scope.propertyAccessSeq('foo["bar"]'))
.to.deep.equal(['foo', 'bar'])
})
it('should handle [<Identifier>] syntax', function () {
expect(scope.propertyAccessSeq('foo[foo]'))
.to.deep.equal(['foo', 'zoo'])
})
it('should handle nested access 1', function () {
expect(scope.propertyAccessSeq('foo[bar.zoo]'))
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 2', function () {
expect(scope.propertyAccessSeq('foo[bar["zoo"]]'))
.to.deep.equal(['foo', 'coo'])
})
it('should handle nested access 3', function () {
expect(scope.propertyAccessSeq('bar["foo"].zoo'))
.to.deep.equal(['bar', 'foo', 'zoo'])
})
it('should handle nested access 4', function () {
expect(scope.propertyAccessSeq('foo[0].bar'))
.to.deep.equal(['foo', '0', 'bar'])
})
})
describe('#get()', function () {
it('should get direct property', function () {
expect(scope.get('foo')).equal('zoo')
})
it('should get undefined property', function () {
function fn () {
scope.get('notdefined')
}
expect(fn).to.not.throw()
expect(scope.get('notdefined')).to.equal(undefined)
expect(scope.get(false)).to.equal(undefined)
})
it('should throw for invalid path', function () {
function fn () {
scope.get('')
}
expect(fn).to.throw('invalid path:""')
})
it('should throw when [] unbalanced', function () {
expect(function () {
scope.get('foo[bar')
}).to.throw(/unbalanced \[\]/)
})
it('should throw when "" unbalanced', function () {
expect(function () {
scope.get('foo["bar]')
}).to.throw(/unbalanced "/)
})
it("should throw when '' unbalanced", function () {
expect(function () {
scope.get("foo['bar]")
}).to.throw(/unbalanced '/)
})
it('should respect to to_liquid', function () {
const scope = scopeFactory({foo: {
to_liquid: () => ({bar: 'BAR'}),
bar: 'bar'
}})
expect(scope.get('foo.bar')).to.equal('BAR')
})
it('should respect to toLiquid', function () {
const scope = scopeFactory({foo: {
toLiquid: () => ({bar: 'BAR'}),
bar: 'bar'
}})
expect(scope.get('foo.bar')).to.equal('BAR')
})
it('should access child property via dot syntax', function () {
expect(scope.get('bar.zoo')).to.equal('coo')
expect(scope.get('bar.arr')).to.deep.equal(['a', 'b'])
})
it('should access child property via [<String>] syntax', function () {
expect(scope.get('bar["zoo"]')).to.equal('coo')
})
it('should access child property via [<Number>] syntax', function () {
expect(scope.get('bar.arr[0]')).to.equal('a')
})
it('should access child property via [<Identifier>] syntax', function () {
expect(scope.get('bar[foo]')).to.equal('coo')
})
it('should return undefined when not exist', function () {
expect(scope.get('foo.foo.foo')).to.be.undefined
})
})
describe('#set', function () {
it('should set nested value', function () {
scope.set('posts', {
'first': {
'name': 'A Nice Day'
}
})
scope.set('category', {
'diary': ['first']
})
expect(scope.get('posts[category.diary[0]].name'), 'A Nice Day')
})
it('should create parent if needed', function () {
scope.set('a.b.c.d', 'COO')
expect(scope.get('a.b.c.d')).to.equal('COO')
})
it('should keep other properties of parent', function () {
scope.push({obj: {foo: 'FOO'}})
scope.set('obj.bar', 'BAR')
expect(scope.get('obj.foo')).to.equal('FOO')
})
it('should abort if property cannot be set', function () {
scope.push({obj: {foo: 'FOO'}})
scope.set('obj.foo.bar', 'BAR')
expect(scope.get('obj.foo')).to.equal('FOO')
})
it("should set parents' corresponding value", function () {
scope.push({})
scope.set('foo', 'bar')
scope.pop()
expect(scope.get('foo')).to.equal('bar')
})
})
describe('strict_variables', function () {
let scope
beforeEach(function () {
scope = scopeFactory(ctx, {
strict_variables: true
})
})
it('should throw when variable not defined', function () {
function fn () {
scope.get('notdefined')
}
expect(fn).to.throw(/undefined variable: notdefined/)
})
it('should throw when deep variable not exist', function () {
scope.set('foo', 'FOO')
function fn () {
scope.get('foo.bar.not.defined')
}
expect(fn).to.throw(/undefined variable: bar/)
})
it('should throw when itself not defined', function () {
scope.set('foo', 'bar')
function fn () {
scope.get('foo.BAR')
}
expect(fn).to.throw(/undefined variable: BAR/)
})
it('should find variable in parent scope', function () {
scope.set('foo', 'foo')
scope.push({
'bar': 'bar'
})
expect(scope.get('foo')).to.equal('foo')
})
})
describe('.getAll()', function () {
it('should get all properties when arguments empty', function () {
expect(scope.getAll()).deep.equal(ctx)
})
})
describe('.push()', function () {
it('should push scope', function () {
scope.set('bar', 'bar')
scope.push({
foo: 'foo'
})
expect(scope.get('foo')).to.equal('foo')
expect(scope.get('bar')).to.equal('bar')
})
it('should hide deep properties by push', function () {
scope.set('bar', {bar: 'bar'})
scope.push({bar: {foo: 'foo'}})
expect(scope.get('bar.foo')).to.equal('foo')
expect(scope.get('bar.bar')).to.equal(undefined)
})
})
describe('.pop()', function () {
it('should pop scope', function () {
scope.push({
foo: 'foo'
})
scope.pop()
expect(scope.get('foo')).to.equal('zoo')
})
})
it('should pop specified scope', function () {
const scope1 = {
foo: 'foo'
}
const scope2 = {
bar: 'bar'
}
scope.push(scope1)
scope.push(scope2)
expect(scope.get('foo')).to.equal('foo')
expect(scope.get('bar')).to.equal('bar')
scope.pop(scope1)
expect(scope.get('foo')).to.equal('zoo')
expect(scope.get('bar')).to.equal('bar')
})
it('should throw when specified scope not found', function () {
const scope1 = {
foo: 'foo'
}
expect(() => scope.pop(scope1)).to.throw('scope not found, cannot pop')
})
})
+99
View File
@@ -0,0 +1,99 @@
const chai = require('chai')
const expect = chai.expect
const syntax = require('../../src/syntax.js')
const Scope = require('../../src/scope.js')
const evalExp = syntax.evalExp
const evalValue = syntax.evalValue
const isTruthy = syntax.isTruthy
describe('expression', function () {
let scope
beforeEach(function () {
scope = Scope.factory({
one: 1,
two: 2,
empty: '',
x: 'XXX',
y: undefined,
z: null,
'has_value?': true
})
})
describe('.evalValue()', function () {
it('should eval literals', function () {
expect(evalValue('2.3')).to.equal(2.3)
expect(evalValue('"foo"')).to.equal('foo')
})
it('should eval variables', function () {
expect(evalValue('23', scope)).to.equal(23)
expect(evalValue('one', scope)).to.equal(1)
expect(evalValue('has_value?', scope)).to.equal(true)
expect(evalValue('x', scope)).to.equal('XXX')
})
it('should throw if not valid', function () {
const fn = () => evalValue('===')
expect(fn).to.throw("cannot eval '===' as value")
})
})
describe('.isTruthy()', function () {
// Spec: https://shopify.github.io/liquid/basics/truthy-and-falsy/
expect(isTruthy(true)).to.be.true
expect(isTruthy(false)).to.be.false
expect(isTruthy(null)).to.be.false
expect(isTruthy('foo')).to.be.true
expect(isTruthy('')).to.be.true
expect(isTruthy(0)).to.be.true
expect(isTruthy(1)).to.be.true
expect(isTruthy(1.1)).to.be.true
expect(isTruthy([1])).to.be.true
expect(isTruthy([])).to.be.true
})
describe('.evalExp()', function () {
it('should throw when scope undefined', function () {
expect(function () {
evalExp('')
}).to.throw(/scope undefined/)
})
it('should eval simple expression', function () {
expect(evalExp('1<2', scope)).to.equal(true)
expect(evalExp('2<=2', scope)).to.equal(true)
expect(evalExp('one<=two', scope)).to.equal(true)
expect(evalExp('x contains "x"', scope)).to.equal(false)
expect(evalExp('x contains "X"', scope)).to.equal(true)
expect(evalExp('1 contains "x"', scope)).to.equal(false)
expect(evalExp('y contains "x"', scope)).to.equal(false)
expect(evalExp('z contains "x"', scope)).to.equal(false)
expect(evalExp('(1..5) contains 3', scope)).to.equal(true)
expect(evalExp('(1..5) contains 6', scope)).to.equal(false)
expect(evalExp('"<=" == "<="', scope)).to.equal(true)
})
describe('complex expression', function () {
it('should support value or value', function () {
expect(evalExp('false or true', scope)).to.equal(true)
})
it('should support < and contains', function () {
expect(evalExp('1<2 and x contains "x"', scope)).to.equal(false)
})
it('should support < or contains', function () {
expect(evalExp('1<2 or x contains "x"', scope)).to.equal(true)
})
it('should support value and !=', function () {
expect(evalExp('empty and empty != ""', scope)).to.equal(false)
})
})
it('should eval range expression', function () {
expect(evalExp('(2..4)', scope)).to.deep.equal([2, 3, 4])
expect(evalExp('(two..4)', scope)).to.deep.equal([2, 3, 4])
})
})
})
+99
View File
@@ -0,0 +1,99 @@
import chai from 'chai'
import Tag from '../../src/tag.js'
import {factory as scopeFactory} from '../../src/scope.js'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
chai.use(sinonChai)
const expect = chai.expect
const tag = Tag()
describe('tag', function () {
let scope
before(function () {
scope = scopeFactory({
foo: 'bar',
arr: [2, 1],
bar: {
coo: 'uoo'
}
})
tag.clear()
})
it('should throw when not registered', function () {
expect(function () {
tag.construct({
type: 'tag',
value: 'foo',
name: 'foo'
}, [])
}).to.throw(/tag foo not found/)
})
it('should register simple tag', function () {
expect(function () {
tag.register('foo', {
render: x => 'bar'
})
}).not.throw()
})
it('should call tag.render', async function () {
const spy = sinon.spy()
tag.register('foo', {
render: spy
})
const token = {
type: 'tag',
value: 'foo',
name: 'foo'
}
await tag.construct(token, []).render(scope, {})
expect(spy).to.have.been.called
})
describe('hash', function () {
let spy, token
beforeEach(function () {
spy = sinon.spy()
tag.register('foo', {
render: spy
})
token = {
type: 'tag',
value: 'foo aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo',
name: 'foo',
args: 'aa:foo bb: arr[0] cc: 2.3\ndd:bar.coo'
}
})
it('should call tag.render with scope', async function () {
await tag.construct(token, []).render(scope, {})
expect(spy).to.have.been.calledWithMatch(scope)
})
it('should resolve identifier hash', async function () {
await tag.construct(token, []).render(scope, {})
expect(spy).to.have.been.calledWithMatch({}, {
aa: 'bar'
})
})
it('should accept space between key/value', async function () {
await tag.construct(token, []).render(scope, {})
expect(spy).to.have.been.calledWithMatch({}, {
bb: 2
})
})
it('should resolve number value hash', async function () {
await tag.construct(token, []).render(scope, {})
expect(spy).to.have.been.calledWithMatch(scope, {
cc: 2.3
})
})
it('should resolve property access hash', async function () {
await tag.construct(token, []).render(scope, {})
expect(spy).to.have.been.calledWithMatch(scope, {
dd: 'uoo'
})
})
})
})
+68
View File
@@ -0,0 +1,68 @@
import Liquid from '../../../src'
import chai from 'chai'
import sinonChai from 'chai-as-promised'
chai.use(sinonChai)
const expect = chai.expect
describe('tags/assign', function () {
const liquid = Liquid()
it('should throw when variable expression illegal', function () {
const src = '{% assign / %}'
const ctx = {}
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
})
it('should support assign to a string', function () {
const src = '{% assign foo="bar" %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar')
})
it('should support assign to a number', function () {
const src = '{% assign foo=10086 %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('10086')
})
it('should shading rather than overwriting', function () {
const ctx = {foo: 'foo'}
const src = '{% assign foo="FOO" %}{{foo}}'
return liquid.parseAndRender(src, ctx)
.then(x => {
expect(x).to.equal('FOO')
expect(ctx.foo).to.equal('foo')
})
})
it('should assign as array', function () {
const src = '{% assign foo=(1..3) %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('[1,2,3]')
})
it('should assign as filter result', function () {
const src = '{% assign foo="a b" | capitalize | split: " " | first %}{{foo}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A')
})
it('should assign var-1', function () {
const src = '{% assign var-1 = 5 %}{{ var-1 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign var-', function () {
const src = '{% assign var- = 5 %}{{ var- }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign -var', function () {
const src = '{% assign -let = 5 %}{{ -let }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign -5-5', function () {
const src = '{% assign -5-5 = 5 %}{{ -5-5 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should assign 4-3', function () {
const src = '{% assign 4-3 = 5 %}{{ 4-3 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('5')
})
it('should not assign -6', function () {
const src = '{% assign -6 = 5 %}{{ -6 }}'
return expect(liquid.parseAndRender(src)).to.eventually.equal('-6')
})
})
+37
View File
@@ -0,0 +1,37 @@
import Liquid from '../../../src/index'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/capture', function () {
const liquid = Liquid()
it('should support capture', function () {
const src = '{% capture f %}{{"a" | capitalize}}{%endcapture%}{{f}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('A')
})
it('should shading rather than overwriting', function () {
const src = '{% capture var %}10{% endcapture %}{{var}}'
const ctx = {'var': 20}
return liquid.parseAndRender(src, ctx)
.then(x => {
expect(x).to.equal('10')
expect(ctx.var).to.equal(20)
})
})
it('should throw on invalid identifier', function () {
const src = '{% capture = %}{%endcapture%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/= not valid identifier/)
})
it('should throw when capture not closed', function () {
const src = '{%capture c%}{{c}}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
})
+53
View File
@@ -0,0 +1,53 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/case', function () {
const liquid = Liquid()
it('should reject if not closed', function () {
const src = '{% case "foo"%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% case "foo"%} not closed/)
})
it('should hit the specified case', function () {
const src = '{% case "foo"%}' +
'{% when "foo" %}foo{% when "bar"%}bar' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('foo')
})
it('should resolve empty string if not hit', function () {
const src = '{% case empty %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}'
const ctx = {
empty: ''
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('bar')
})
it('should accept empty string as branch name', function () {
const src = '{% case false %}' +
'{% when "foo" %}foo{% when ""%}bar' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should support boolean case', function () {
const src = '{% case false %}' +
'{% when "foo" %}foo{% when false%}bar' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('bar')
})
it('should support else branch', function () {
const src = '{% case "a" %}' +
'{% when "b" %}b{% when "c"%}c{%else %}d' +
'{%endcase%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('d')
})
})
+34
View File
@@ -0,0 +1,34 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/comment', function () {
const liquid = Liquid()
it('should support empty content', function () {
const src = '{% comment %}{% raw%}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/{% comment %} not closed/)
})
it('should ignore plain string', function () {
const src = 'My name is {% comment %}super{% endcomment %} Shopify.'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('My name is Shopify.')
})
it('should ignore output tokens', function () {
const src = '{% comment %}\n{{ foo}} \n{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should ignore tag tokens', function () {
const src = '{% comment %}{%if true%}true{%else%}false{%endif%}{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
it('should ignore un-balenced tag tokens', function () {
const src = '{% comment %}{%if true%}true{%else%}false{% endcomment %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
})
+40
View File
@@ -0,0 +1,40 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/cycle', function () {
const liquid = Liquid()
it('should support cycle', function () {
const src = "{% cycle '1', '2', '3' %}"
return expect(liquid.parseAndRender(src + src + src + src))
.to.eventually.equal('1231')
})
it('should throw when cycle candidates empty', function () {
return expect(liquid.parseAndRender('{%cycle%}'))
.to.be.rejectedWith(/empty candidates/)
})
it('should support cycle in for block', function () {
const src = '{% for i in (1..5) %}{% cycle one, "e"%}{% endfor %}'
const ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1e1e1')
})
it('should support cycle group', function () {
const src = "{% cycle one: '1', '2', '3'%}" +
"{% cycle 1: '1', '2', '3'%}" +
"{% cycle 2: '1', '2', '3'%}"
const ctx = {
one: 1
}
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('121')
})
})
+60
View File
@@ -0,0 +1,60 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/decrement', function () {
const liquid = Liquid()
it('should throw when variable expression illegal', function () {
const src = '{% decrement / %}{{var}}'
const ctx = {}
return expect(liquid.parseAndRender(src, ctx)).to.be.rejectedWith(/illegal/)
})
it('should decrement undefined variable', function () {
const src = '{% decrement var %}{% decrement var %}{% decrement var %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3')
})
it('should decrement defined variable', function () {
const src = '{% decrement var %}{% decrement var %}{% decrement var %}'
const ctx = {'var': 10}
return liquid.parseAndRender(src, ctx)
.then(x => {
expect(x).to.equal('987')
expect(ctx.var).to.equal(7)
})
})
it('should be independent from assign', function () {
const src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3')
})
it('should be independent from capture', function () {
const src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3')
})
it('should not shading assign', function () {
const src = '{% assign var=10 %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3 10')
})
it('should not shading capture', function () {
const src = '{% capture var %}10{% endcapture %}{% decrement var %}{% decrement var %}{% decrement var %} {{var}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('-1-2-3 10')
})
it('should share the same variable with increment', function () {
const src = '{%increment var%}{%increment var%}{%decrement var%}{%decrement var%}{%increment var%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('01100')
})
})
+203
View File
@@ -0,0 +1,203 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/for', function () {
let liquid, ctx
before(function () {
liquid = Liquid()
liquid.registerTag('throwingTag', {
render: function () { throw new Error('intended render error') }
})
ctx = {
one: 1,
// eslint-disable-next-line
strObj: new String(''),
emptyObj: {},
nullProtoObj: Object.create(null),
obj: {foo: 'bar', coo: 'haa'},
alpha: ['a', 'b', 'c'],
emptyArray: []
}
})
it('should support array', function () {
const src = '{%for c in alpha%}{{c}}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('abc')
})
it('should support object', function () {
const src = '{%for item in obj%}{{item[0]}},{{item[1]}}-{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('foo,bar-coo,haa-')
})
describe('scope', function () {
it('should read super scope', function () {
const src = '{%for a in (1..2)%}{{num}}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('11')
})
it('should write super scope', function () {
const src = '{%for a in (1..2)%}{{num}}{%assign num = 2%}{%endfor%}'
return expect(liquid.parseAndRender(src, {num: 1}))
.to.eventually.equal('12')
})
})
describe('illegal', function () {
it('should reject when for not closed', function () {
const src = '{%for c in alpha%}{{c}}'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag .* not closed/)
})
it('should reject when inner templates rejected', function () {
const src = '{%for c in alpha%}{%throwingTag%}{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/intended render error/)
})
})
describe('else', function () {
it('should goto else for empty array', function () {
const src = '{%for c in emptyArray%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should treat non-empty string as one single element', function () {
const src = '{%for c in "abc"%}x{{c}}{%else%}y{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('xabc')
})
it('should goto else for empty string', function () {
const src = '{%for c in ""%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for empty string object', function () {
// it should be false although `new String` is none-conform
const src = '{%for c in strObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for empty object', function () {
const src = '{%for c in emptyObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
it('should goto else for null-prototyped object', function () {
const src = '{%for c in nullProtoObj%}a{%else%}b{%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('b')
})
})
it('should support for with forloop', function () {
const src = '{%for c in alpha%}' +
'{{forloop.first}}.{{forloop.index}}.{{forloop.index0}}.' +
'{{forloop.last}}.{{forloop.length}}.' +
'{{forloop.rindex}}.{{forloop.rindex0}}' +
'{{c}}\n' +
'{%endfor%}'
const dst = 'true.1.0.false.3.3.2a\n' +
'false.2.1.false.3.2.1b\n' +
'false.3.2.true.3.1.0c\n'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal(dst)
})
it('should support for with continue', function () {
const src = '{% for i in (1..5) %}' +
'{{i}}{% continue %}after' +
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12345')
})
it('should support for with break', function () {
const src = '{% for i in (one..5) %}' +
'{% if i == 4 %}{% break %}{% endif %}' +
'{{ i }}' +
'{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('123')
})
describe('limit', function () {
it('should support for with limit', function () {
const src = '{% for i in (1..5) limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('12')
})
it('should set forloop.last properly', function () {
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.last}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('false true ')
})
it('should set forloop.first properly', function () {
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.first}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('true false ')
})
it('should set forloop.length properly', function () {
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.length}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 2 ')
})
})
describe('offset', function () {
it('should support offset with limit', function () {
const src = '{% for i in (1..10) limit:2 offset:5%}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('67')
})
it('should set index properly', function () {
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 2 ')
})
it('should set index0 properly', function () {
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.index0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('0 1 ')
})
it('should set rindex properly', function () {
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2 1 ')
})
it('should set rindex0 properly', function () {
const src = '{%for i in (1..10) limit:2 offset:3%}{{forloop.rindex0}} {%endfor%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('1 0 ')
})
})
describe('reverse', function () {
it('should support for reversed in the last position', function () {
const src = '{% for i in (1..5) limit:2 reversed %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the first position', function () {
const src = '{% for i in (1..5) reversed limit:2 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('21')
})
it('should support for reversed in the middle position', function () {
const src = '{% for i in (1..5) offset:2 reversed limit:4 %}{{ i }}{% endfor %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('543')
})
})
})
+116
View File
@@ -0,0 +1,116 @@
import Liquid from '../../../src/index'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/if', function () {
const liquid = Liquid()
const ctx = {
one: 1,
two: 2,
emptyString: '',
emptyArray: []
}
it('should throw if not closed', function () {
const src = '{% if false%}yes'
return expect(liquid.parseAndRender(src, ctx))
.to.be.rejectedWith(/tag {% if false%} not closed/)
})
it('should support nested', function () {
const src = '{%if false%}{%if true%}{%else%}a{%endif%}{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
describe('single value as condition', function () {
it('should support boolean', function () {
const src = '{% if false %}1{%elsif true%}2{%else%}3{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('2')
})
it('should treat Array truthy', function () {
const src = '{%if emptyArray%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
it('should return true if empty string', function () {
const src = '{%if emptyString%}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('a')
})
})
describe('expression as condition', function () {
it('should support ==', function () {
const src = '{% if 2==3 %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should support >=', function () {
const src = '{% if 1>=2 and one<two %}a{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('')
})
it('should support !=', function () {
const src = '{% if one!=two %}yes{%else%}no{%endif%}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('yes')
})
it('should support value and expression', function () {
const src = `X{%if version and version != '' %}x{{version}}y{%endif%}Y`
const ctx = { 'version': '' }
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('XY')
})
})
describe('comparasion to null', function () {
it('should evaluate false for null < 10', function () {
const src = '{% if null < 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for null > 10', function () {
const src = '{% if null > 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for null <= 10', function () {
const src = '{% if null <= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for null >= 10', function () {
const src = '{% if null >= 10 %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 < null', function () {
const src = '{% if 10 < null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 > null', function () {
const src = '{% if 10 > null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 <= null', function () {
const src = '{% if 10 <= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
it('should evaluate false for 10 >= null', function () {
const src = '{% if 10 >= null %}yes{% else %}no{% endif %}'
return expect(liquid.parseAndRender(src, ctx))
.to.eventually.equal('no')
})
})
})
+152
View File
@@ -0,0 +1,152 @@
import Liquid from '../../../src'
import mock from 'mock-fs'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/include', function () {
let liquid
before(function () {
liquid = Liquid({
root: '/',
extname: '.html'
})
})
afterEach(function () {
mock.restore()
})
it('should support include', function () {
mock({
'/current.html': 'bar{% include "bar/foo.html" %}bar',
'/bar/foo.html': 'foo'
})
return expect(liquid.renderFile('/current.html')).to
.eventually.equal('barfoobar')
})
it('should support template string', function () {
mock({
'/current.html': 'bar{% include "bar/{{name}}" %}bar',
'/bar/foo.html': 'foo'
})
return expect(liquid.renderFile('/current.html', {name: 'foo.html'})).to
.eventually.equal('barfoobar')
})
it('should throw when not specified', function () {
mock({
'/parent.html': '{%include%}'
})
return liquid.renderFile('/parent.html').catch(function (e) {
expect(e.name).to.equal('RenderError')
expect(e.message).to.match(/cannot include with empty filename/)
})
})
it('should throw when not exist', function () {
mock({
'/parent.html': '{%include not-exist%}'
})
return liquid.renderFile('/parent.html').catch(function (e) {
expect(e.name).to.equal('RenderError')
expect(e.message).to.match(/cannot include with empty filename/)
})
})
it('should support include with relative path', function () {
mock({
'/bar/foo.html': 'foo',
'/foo/relative.html': 'bar{% include "../bar/foo.html" %}bar'
})
return expect(liquid.renderFile('foo/relative.html')).to
.eventually.equal('barfoobar')
})
it('should support include: hash list', function () {
mock({
'/hash.html': '{% assign name="harttle" %}{% include "user.html", role: "admin", alias: name %}',
'/user.html': '{{name}} : {{role}} : {{alias}}'
})
return expect(liquid.renderFile('hash.html')).to
.eventually.equal('harttle : admin : harttle')
})
it('should support include: parent scope', function () {
mock({
'/scope.html': '{% assign shape="triangle" %}{% assign color="yellow" %}{% include "color.html" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}'
})
return expect(liquid.renderFile('scope.html')).to
.eventually.equal('color:yellow, shape:triangle')
})
it('should support include: with', function () {
mock({
'/with.html': '{% include "color" with "red", shape: "rect" %}',
'/color.html': 'color:{{color}}, shape:{{shape}}'
})
return expect(liquid.renderFile('with.html')).to
.eventually.equal('color:red, shape:rect')
})
it('should support nested includes', function () {
mock({
'/personInfo.html': 'This is a person {% include "card.html" %}',
'/card.html': '<p>{{person.firstName}} {{person.lastName}}<br/>{% include "address" %}</p>',
'/address.html': 'City: {{person.address.city}}'
})
const ctx = {
person: {
firstName: 'Joe',
lastName: 'Shmoe',
address: {
city: 'Dallas'
}
}
}
return expect(liquid.renderFile('personInfo.html', ctx)).to
.eventually.equal('This is a person <p>Joe Shmoe<br/>City: Dallas</p>')
})
describe('static partial', function () {
it('should support filename with extention', function () {
mock({
'/parent.html': 'X{% include child.html color:"red" %}Y',
'/child.html': 'child with {{color}}'
})
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('Xchild with redY')
})
it('should support parent paths', function () {
mock({
'/parent.html': 'X{% include bar/./../foo/child.html %}Y',
'/foo/child.html': 'child'
})
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('XchildY')
})
it('should support subpaths', function () {
mock({
'/parent.html': 'X{% include foo/child.html %}Y',
'/foo/child.html': 'child'
})
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('XchildY')
})
it('should support comma separated arguments', function () {
mock({
'/parent.html': 'X{% include child.html, color:"red" %}Y',
'/child.html': 'child with {{color}}'
})
const staticLiquid = new Liquid({dynamicPartials: false, root: '/'})
return expect(staticLiquid.renderFile('parent.html')).to
.eventually.equal('Xchild with redY')
})
})
})
+49
View File
@@ -0,0 +1,49 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/increment', function () {
const liquid = Liquid()
it('should increment undefined variable', function () {
const src = '{% increment one %}{% increment one %}{% increment one %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('012')
})
it('should increment defined variable', function () {
const src = '{% increment one %}{% increment one %}{% increment one %}'
const ctx = {one: 7}
return liquid.parseAndRender(src, ctx)
.then(x => {
expect(x).to.equal('789')
expect(ctx.one).to.equal(10)
})
})
it('should be independent from assign', function () {
const src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('012')
})
it('should be independent from capture', function () {
const src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('012')
})
it('should not shading assign', function () {
const src = '{% assign var=10 %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('012 10')
})
it('should not shading capture', function () {
const src = '{% capture var %}10{% endcapture %}{% increment var %}{% increment var %}{% increment var %} {{var}}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('012 10')
})
})
+141
View File
@@ -0,0 +1,141 @@
import Liquid from '../../../src'
import mock from 'mock-fs'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/layout', function () {
let liquid
before(function () {
liquid = Liquid({
root: '/',
extname: '.html'
})
})
afterEach(function () {
mock.restore()
})
it('should throw when block not closed', function () {
mock({
'/parent.html': 'parent'
})
const src = '{% layout "parent" %}{%block%}A'
return expect(liquid.parseAndRender(src)).to
.be.rejectedWith(/tag {%block%} not closed/)
})
it('should throw when filename not specified', function () {
mock({
'/parent.html': '{%layout%}'
})
return liquid.renderFile('/parent.html').catch(function (e) {
expect(e.name).to.equal('RenderError')
expect(e.message).to.match(/cannot apply layout with empty filename/)
})
})
describe('anonymous block', function () {
it('should handle anonymous block', function () {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y'
})
const src = '{% layout "parent.html" %}{%block%}A{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY')
})
it('should handle top level contents as anonymous block', function () {
mock({
'/parent.html': 'X{%block%}{%endblock%}Y'
})
const src = '{% layout "parent.html" %}A'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAY')
})
})
it('should handle named blocks', function () {
mock({
'/parent.html': 'X{% block "a"%}{% endblock %}Y{% block b%}{%endblock%}Z'
})
const src = '{% layout "parent.html" %}' +
'{%block a%}A{%endblock%}' +
'{%block b%}B{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XAYBZ')
})
it('should support default block content', function () {
mock({
'/parent.html': 'X{% block "a"%}A{% endblock %}Y{% block b%}B{%endblock%}Z'
})
const src = '{% layout "parent.html" %}{%block a%}a{%endblock%}'
return expect(liquid.parseAndRender(src)).to
.eventually.equal('XaYBZ')
})
it('should handle nested block', function () {
mock({
'/grand.html': 'X{%block a%}G{%endblock%}Y',
'/parent.html': '{%layout "grand" %}{%block a%}P{%endblock%}',
'/main.html': '{%layout "parent"%}{%block a%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('XAY')
})
it('should not bleed scope into included layout', function () {
mock({
'/parent.html': 'X{%block a%}{%endblock%}Y{%block b%}{%endblock%}Z',
'/main.html': '{%layout "parent"%}' +
'{%block a%}A{%endblock%}' +
'{%block b%}I{%include "included"%}J{%endblock%}',
'/included.html': '{%layout "parent"%}{%block a%}a{%endblock%}'
})
return expect(liquid.renderFile('main')).to
.eventually.equal('XAYIXaYZJZ')
})
it('should support hash list', function () {
mock({
'/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black"%}{%block%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
it('should support multiple hash', function () {
mock({
'/parent.html': '{{color}}{{bg}}{%block%}{%endblock%}',
'/main.html': '{% layout "parent.html" color:"black", bg:"red"%}{%block%}A{%endblock%}'
})
return expect(liquid.renderFile('/main.html')).to
.eventually.equal('blackredA')
})
describe('static partial', function () {
it('should support filename with extention', function () {
mock({
'/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout parent.html color:"black"%}{%block%}A{%endblock%}'
})
const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
it('should support parent paths', function () {
mock({
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout bar/../foo/parent.html color:"black"%}{%block%}A{%endblock%}'
})
const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
it('should support subpaths', function () {
mock({
'/foo/parent.html': '{{color}}{%block%}{%endblock%}',
'/main.html': '{% layout foo/parent.html color:"black"%}{%block%}A{%endblock%}'
})
const staticLiquid = Liquid({ root: '/', dynamicPartials: false })
return expect(staticLiquid.renderFile('/main.html')).to
.eventually.equal('blackA')
})
})
})
+23
View File
@@ -0,0 +1,23 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/raw', function () {
const liquid = Liquid()
it('should support raw 1', async function () {
const p = liquid.parseAndRender('{% raw%}')
return expect(p).be.rejectedWith(/{% raw%} not closed/)
})
it('should support raw 2', async function () {
const src = '{% raw %}{{ 5 | plus: 6 }}{% endraw %} is equal to 11.'
const dst = '{{ 5 | plus: 6 }} is equal to 11.'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support raw 3', function () {
const src = '{% raw %}\n{{ foo}} \n{% endraw %}'
const dst = '\n{{ foo}} \n'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
})
+73
View File
@@ -0,0 +1,73 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/tablerow', function () {
const liquid = Liquid()
it('should support tablerow', function () {
const src = '{% tablerow i in (1..3)%}{{ i }}{% endtablerow %}'
const dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support cols', function () {
const src = '{% tablerow i in alpha cols:2 %}{{ i }}{% endtablerow %}'
const ctx = {
alpha: ['a', 'b', 'c']
}
const dst =
'<tr class="row1"><td class="col1">a</td><td class="col2">b</td></tr>' +
'<tr class="row2"><td class="col1">c</td></tr>'
return expect(liquid.parseAndRender(src, ctx)).to.eventually.equal(dst)
})
it('should support cols set to 0', function () {
const src = '{% tablerow i in (1..3) cols:0 %}{{ i }}{% endtablerow %}'
const dst = '<tr class="row1"><td class="col1">1</td><td class="col2">2</td><td class="col3">3</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support empty tablerow', function () {
const src = '{% tablerow i in (1..0) cols:2 %}{{ i }}{% endtablerow %}'
const dst = ''
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support empty array', function () {
const src = '{% tablerow i in alpha.z cols:2 %}{{ i }}{% endtablerow %}'
const dst = ''
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should throw when tablerow not closed', function () {
const src = '{% tablerow i in (1..0) cols:2 %}{{ i }}'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag .* not closed/)
})
it('should support tablerow with range', function () {
const src = '{% tablerow i in (1..5) cols:2 %}{{ i }}{% endtablerow %}'
const dst =
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td><td class="col2">4</td></tr>' +
'<tr class="row3"><td class="col1">5</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with limit', function () {
const src = '{% tablerow i in (1..5) cols:2 limit:3 %}{{ i }}{% endtablerow %}'
const dst =
'<tr class="row1"><td class="col1">1</td><td class="col2">2</td></tr>' +
'<tr class="row2"><td class="col1">3</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
it('should support tablerow with offset', function () {
const src = '{% tablerow i in (1..5) cols:2 offset:3 %}{{ i }}{% endtablerow %}'
const dst = '<tr class="row1"><td class="col1">4</td><td class="col2">5</td></tr>'
return expect(liquid.parseAndRender(src)).to.eventually.equal(dst)
})
})
+36
View File
@@ -0,0 +1,36 @@
import Liquid from '../../../src'
import chai from 'chai'
const expect = chai.expect
chai.use(require('chai-as-promised'))
describe('tags/unless', function () {
const liquid = Liquid()
it('should render else when predicate yields true', function () {
// 0 is truthy
const src = '{% unless 0 %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('no')
})
it('should render unless when predicate yields false', function () {
const src = '{% unless false %}yes{%else%}no{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should reject when tag not closed', function () {
const src = '{% unless 1>2 %}yes'
return expect(liquid.parseAndRender(src))
.to.be.rejectedWith(/tag {% unless 1>2 %} not closed/)
})
it('should render unless when predicate yields false and else undefined', function () {
const src = '{% unless 1>2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('yes')
})
it('should render "" when predicate yields false and else undefined', function () {
const src = '{% unless 1<2 %}yes{%endunless%}'
return expect(liquid.parseAndRender(src))
.to.eventually.equal('')
})
})
+72
View File
@@ -0,0 +1,72 @@
const chai = require('chai')
const parse = require('../../src/tokenizer.js').parse
const expect = chai.expect
describe('tokenizer', function () {
describe('parse', function () {
it('should handle plain HTML', function () {
const html = '<html><body><p>Lorem Ipsum</p></body></html>'
const tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].value).to.equal(html)
expect(tokens[0].type).to.equal('html')
})
it('should throw when non-string passed in', function () {
expect(function () {
parse({})
}).to.throw('illegal input')
})
it('should handle tag syntax', function () {
const html = '<p>{% for p in a[1]%}</p>'
const tokens = parse(html)
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('tag')
expect(tokens[1].value).to.equal('for p in a[1]')
})
it('should handle value syntax', function () {
const html = '<p>{{foo | date: "%Y-%m-%d"}}</p>'
const tokens = parse(html)
expect(tokens.length).to.equal(3)
expect(tokens[1].type).to.equal('value')
expect(tokens[1].value).to.equal('foo | date: "%Y-%m-%d"')
})
it('should handle consecutive value and tags', function () {
const html = '{{foo}}{{bar}}{%foo%}{%bar%}'
const tokens = parse(html)
expect(tokens.length).to.equal(4)
expect(tokens[0].type).to.equal('value')
expect(tokens[3].type).to.equal('tag')
expect(tokens[1].value).to.equal('bar')
expect(tokens[2].value).to.equal('foo')
})
it('should keep white spaces and newlines', function () {
const html = '{%foo%}\n{%bar %} \n {%alice%}'
const tokens = parse(html)
expect(tokens.length).to.equal(5)
expect(tokens[1].type).to.equal('html')
expect(tokens[1].raw).to.equal('\n')
expect(tokens[3].type).to.equal('html')
expect(tokens[3].raw).to.equal(' \n ')
})
it('should handle multiple lines tag', function () {
const html = '{%foo\na:a\nb:1.23\n%}'
const tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('tag')
expect(tokens[0].args).to.equal('a:a\nb:1.23')
expect(tokens[0].raw).to.equal('{%foo\na:a\nb:1.23\n%}')
})
it('should handle multiple lines value', function () {
const html = '{{foo\n|date:\n"%Y-%m-%d"\n}}'
const tokens = parse(html)
expect(tokens.length).to.equal(1)
expect(tokens[0].type).to.equal('value')
expect(tokens[0].raw).to.equal('{{foo\n|date:\n"%Y-%m-%d"\n}}')
})
})
})
+19
View File
@@ -0,0 +1,19 @@
import chai from 'chai'
import assert from '../../../src/util/assert.js'
const expect = chai.expect
describe('assert', function () {
it('should not throw if predicate is truthy', function () {
const fn = () => assert('foo', 'bar')
expect(fn).to.not.throw()
})
it('should not throw if predicate is truthy', function () {
const fn = () => assert('', 'bar')
expect(fn).to.throw(/bar/)
})
it('should populate default message', function () {
const fn = () => assert(false)
expect(fn).to.throw(/expect false to be true/)
})
})
+308
View File
@@ -0,0 +1,308 @@
import Liquid from '../../../src'
import mock from 'mock-fs'
import chai from 'chai'
import path from 'path'
const expect = chai.expect
chai.use(require('chai-as-promised'))
let engine = Liquid()
const strictEngine = Liquid({
strict_variables: true,
strict_filters: true
})
describe('error', function () {
afterEach(function () {
mock.restore()
})
describe('TokenizationError', function () {
it('should throw TokenizationError when tag illegal', async function () {
const err = await expect(engine.parseAndRender('{% . a %}', {})).be.rejected
expect(err.name).to.equal('TokenizationError')
expect(err.message).to.contain('illegal tag syntax')
})
it('should contain template content in err.message', async function () {
const html = ['1st', '2nd', 'X{% . a %} Y', '4th']
const message = [
' 1| 1st',
' 2| 2nd',
'>> 3| X{% . a %} Y',
' 4| 4th',
'TokenizationError'
]
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
expect(err.message).to.equal('illegal tag syntax, line:3')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('TokenizationError')
})
it('should contain the whole template content in err.input', async function () {
const html = 'bar\nfoo{% . a %}\nfoo'
const err = await expect(engine.parseAndRender(html)).be.rejected
expect(err.input).to.equal(html)
})
it('should contain line number in err.line', async function () {
const err = await expect(engine.parseAndRender('1\n2\n{% . a %}\n4')).be.rejected
expect(err.name).to.equal('TokenizationError')
expect(err.line).to.equal(3)
})
it('should contain stack in err.stack', async function () {
const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
expect(err.message).to.contain('illegal tag syntax')
expect(err.stack).to.contain('at Object.parse')
})
describe('captureStackTrace compatibility', function () {
const captureStackTrace = Error.captureStackTrace
before(() => (Error.captureStackTrace = null))
after(() => (Error.captureStackTrace = captureStackTrace))
it('should be empty when captureStackTrace undefined', async function () {
const err = await expect(engine.parseAndRender('{% . a %}')).be.rejected
expect(err.stack).to.contain('illegal tag syntax')
expect(err.stack).to.not.contain('at Object.parse')
})
})
it('should contain file path in err.file', async function () {
const html = '<html>\n<head>\n\n{% . a %}\n\n'
mock({
'/foo.html': html
})
const err = await expect(engine.renderFile('/foo.html')).be.rejected
mock.restore()
expect(err.name).to.equal('TokenizationError')
expect(err.file).to.equal(path.resolve('/foo.html'))
})
})
describe('RenderError', function () {
beforeEach(function () {
engine = Liquid({
root: '/'
})
engine.registerTag('throwingTag', {
render: function () {
throw new Error('intended render error')
}
})
engine.registerTag('rejectingTag', {
render: async function () {
throw new Error('intended render reject')
}
})
engine.registerFilter('throwingFilter', () => {
throw new Error('throwed by filter')
})
})
it('should throw RenderError when tag throws', async function () {
const src = '{%throwingTag%}'
const err = await expect(engine.parseAndRender(src)).be.rejected
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render error')
})
it('should throw RenderError when tag rejects', async function () {
const src = '{%rejectingTag%}'
const err = await expect(engine.parseAndRender(src)).be.rejected
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('intended render reject')
})
it('should throw RenderError when filter throws', async function () {
const src = '{{1|throwingFilter}}'
const err = await expect(engine.parseAndRender(src)).be.rejected
expect(err.name).to.equal('RenderError')
expect(err.message).to.contain('throwed by filter')
})
it('should not throw when variable undefined by default', function () {
return expect(engine.parseAndRender('X{{a}}Y')).to.eventually.equal('XY')
})
it('should throw RenderError when variable not defined', async function () {
const err = await expect(strictEngine.parseAndRender('{{a}}')).be.rejected
expect(err).to.have.property('name', 'RenderError')
expect(err.message).to.contain('undefined variable: a')
})
it('should contain template context in err.stack', async function () {
const html = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
const message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'RenderError'
]
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
expect(err.message).to.equal('intended render error, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
it('should contain original error info for {% layout %}', async function () {
mock({
'/throwing-tag.html': [
'1st',
'2nd',
'3rd',
'X{%throwingTag%} Y',
'5th',
'{%block%}{%endblock%}',
'7th'
].join('\n')
})
const html = '{%layout "throwing-tag.html"%}'
const message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| {%block%}{%endblock%}',
' 7| 7th',
'RenderError'
]
const err = await expect(engine.parseAndRender(html)).be.rejected
console.log(err.message)
console.log(err.stack)
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
it('should contain original error info for {% include %}', async function () {
const origin = ['1st', '2nd', '3rd', 'X{%throwingTag%} Y', '5th', '6th', '7th']
mock({
'/throwing-tag.html': origin.join('\n')
})
const html = '{%include "throwing-tag.html"%}'
const message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{%throwingTag%} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'RenderError'
]
const err = await expect(engine.parseAndRender(html)).be.rejected
expect(err.message).to.equal(`intended render error, file:${path.resolve('/throwing-tag.html')}, line:4`)
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('RenderError')
})
it('should contain the whole template content in err.input', async function () {
const html = 'bar\nfoo{%throwingTag%}\nfoo'
const err = await expect(engine.parseAndRender(html)).be.rejected
expect(err.input).to.equal(html)
expect(err.name).to.equal('RenderError')
})
it('should contain line number in err.line', async function () {
const src = '1\n2\n{{1|throwingFilter}}\n4'
const err = await expect(engine.parseAndRender(src)).be.rejected
expect(err.line).to.equal(3)
expect(err.name).to.equal('RenderError')
})
it('should contain stack in err.stack', async function () {
const err = await expect(engine.parseAndRender('{%rejectingTag%}')).be.rejected
expect(err.message).to.contain('intended render reject')
expect(err.stack).to.match(/at .*:\d+:\d+/)
})
it('should contain file path in err.file', async function () {
const html = '<html>\n<head>\n\n{% throwingTag %}\n\n'
mock({
'/foo.html': html
})
const err = await expect(engine.renderFile('/foo.html')).be.rejected
mock.restore()
console.log(err, err.name)
expect(err.name).to.equal('RenderError')
expect(err.file).to.equal(path.resolve('/foo.html'))
})
})
describe('ParseError', function () {
beforeEach(function () {
engine = Liquid()
engine.registerTag('throwsOnParse', {
parse: function () {
throw new Error('intended parse error')
}
})
})
it('should throw RenderError when filter not defined', async function () {
const err = await expect(strictEngine.parseAndRender('{{1 | a}}')).be.rejected
expect(err).to.have.property('name', 'ParseError')
expect(err.message).to.contain('undefined filter: a')
})
it('should throw ParseError when tag not closed', async function () {
const err = await expect(engine.parseAndRender('{% if %}')).be.rejected
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag {% if %} not closed')
})
it('should throw ParseError when tag parse throws', async function () {
const err = await expect(engine.parseAndRender('{%throwsOnParse%}')).be.rejected
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('intended parse error')
})
it('should throw ParseError when tag not found', async function () {
const src = '{%if true%}\naaa{%endif%}\n{% -a %}\n3'
const err = await expect(engine.parseAndRender(src)).be.rejected
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag -a not found')
})
it('should throw ParseError when tag not exist', async function () {
const err = await expect(engine.parseAndRender('{% a %}')).be.rejected
expect(err.name).to.equal('ParseError')
expect(err.message).to.contain('tag a not found')
})
it('should contain template context in err.stack', async function () {
const html = ['1st', '2nd', '3rd', 'X{% a %} {% enda %} Y', '5th', '6th', '7th']
const message = [
' 2| 2nd',
' 3| 3rd',
'>> 4| X{% a %} {% enda %} Y',
' 5| 5th',
' 6| 6th',
' 7| 7th',
'ParseError: tag a not found'
]
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
expect(err.message).to.equal('tag a not found, line:4')
expect(err.stack).to.contain(message.join('\n'))
expect(err.name).to.equal('ParseError')
})
it('should handle err.message when context not enough', async function () {
const html = ['1st', 'X{% a %} {% enda %} Y', '3rd', '4th']
const message = [
' 1| 1st',
'>> 2| X{% a %} {% enda %} Y',
' 3| 3rd',
' 4| 4th',
'ParseError: tag a not found'
]
const err = await expect(engine.parseAndRender(html.join('\n'))).be.rejected
expect(err.message).to.equal('tag a not found, line:2')
expect(err.stack).to.contain(message.join('\n'))
})
it('should contain line number in err.line', async function () {
const html = '<html>\n<head>\n\n{% raw %}\n\n'
const err = await expect(engine.parseAndRender(html)).be.rejected
expect(err.line).to.equal(4)
})
it('should contain stack in err.stack', async function () {
const err = await expect(engine.parseAndRender('{% -a %}')).be.rejected
expect(err.stack).to.contain('ParseError: tag -a not found')
expect(err.stack).to.match(/at .*:\d+:\d+\)/)
})
it('should contain file path in err.file', async function () {
const html = '<html>\n<head>\n\n{% raw %}\n\n'
mock({
'/foo.html': html
})
const err = await expect(engine.renderFile('/foo.html')).be.rejected
mock.restore()
expect(err.name).to.equal('ParseError')
expect(err.file).to.equal(path.resolve('/foo.html'))
})
})
})
+94
View File
@@ -0,0 +1,94 @@
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
chai.use(require('chai-as-promised'))
chai.use(require('sinon-chai'))
const P = require('../../../src/util/promise.js')
describe('util/promise', function () {
describe('.anySeries()', function () {
it('should resolve in series', function () {
const spy1 = sinon.spy()
const spy2 = sinon.spy()
return P
.anySeries(
['first', 'second'],
(item, idx) => new Promise(function (resolve, reject) {
if (idx === 0) {
setTimeout(function () {
spy1()
reject(new Error('first cb'))
}, 10)
} else {
spy2()
resolve('foo')
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
})
it('should reject when all rejected', function () {
const p = P.anySeries(['first', 'second', 'third'],
item => Promise.reject(new Error(item)))
return expect(p).to.be.rejectedWith('third')
})
it('should resolve the value that first callback resolved', () => {
const p = P.anySeries(['first', 'second'],
item => Promise.resolve(item))
return expect(p).to.eventually.equal('first')
})
it('should not call rest of callbacks once resolved', () => {
const spy = sinon.spy()
return P
.anySeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy()
}
return Promise.resolve(item)
})
.then(() => expect(spy).to.not.have.been.called)
})
})
describe('.mapSeries()', function () {
it('should resolve when all resolved', function () {
const p = P.mapSeries(['first', 'second', 'third'],
item => Promise.resolve(item))
return expect(p).to.eventually.deep.equal(['first', 'second', 'third'])
})
it('should reject with the error that first callback rejected', () => {
const p = P.mapSeries(['first', 'second'],
item => Promise.reject(item))
return expect(p).to.rejectedWith('first')
})
it('should resolve in series', function () {
const spy1 = sinon.spy()
const spy2 = sinon.spy()
return P
.mapSeries(
['first', 'second'],
(item, idx) => new Promise(function (resolve, reject) {
if (idx === 0) {
setTimeout(function () {
spy1()
resolve('first cb')
}, 10)
} else {
spy2()
resolve('foo')
}
}))
.then(() => expect(spy2).to.have.been.calledAfter(spy1))
})
it('should not call rest of callbacks once rejected', () => {
const spy = sinon.spy()
return P
.mapSeries(['first', 'second'], (item, idx) => {
if (idx > 0) {
spy()
}
return Promise.reject(new Error(item))
})
.catch(() => expect(spy).to.not.have.been.called)
})
})
})
+146
View File
@@ -0,0 +1,146 @@
import chai from 'chai'
import t from '../../../src/util/strftime.js'
const expect = chai.expect
describe('util/strftime', function () {
let now
let then
before(function () {
mockUTC()
now = new Date('2016-01-04T13:15:23.000Z')
then = new Date('2016-03-06T03:05:03.000Z')
})
after(function () {
restoreUTC()
})
it('should format UTC datetime', function () {
expect(t(now, '%Y-%m-%dT%H:%M:%S')).to.equal('2016-01-04T13:15:23')
})
it('should format %A as Monday', function () {
expect(t(now, '%A')).to.equal('Monday')
})
it('should format %B as month name', function () {
expect(t(now, '%B')).to.equal('January')
})
it('should format %C as century', function () {
expect(t(now, '%C')).to.equal('20')
})
it('should format %c as local string', function () {
expect(t(now, '%c')).to.equal(now.toLocaleString())
})
it('should format %e as space padded date', function () {
expect(t(now, '%e')).to.equal(' 4')
})
it('should format %I as 0 padded hour12', function () {
expect(t(now, '%I')).to.equal('01')
})
it('should format %I as 12 for 00:00', function () {
const date = new Date('2016-01-01T00:00:00.000Z')
expect(t(date, '%I')).to.equal('12')
})
describe('%j', function () {
it('should format %j as day of year', function () {
expect(t(then, '%j')).to.equal('066')
})
it('should take count of leap years', function () {
const date = new Date('2001-03-01')
expect(t(date, '%j')).to.equal('060')
})
it('should take count of leap years', function () {
const date = new Date('2000-03-01')
expect(t(date, '%j')).to.equal('061')
})
})
it('should format %k as space padded hour', function () {
expect(t(then, '%k')).to.equal(' 3')
})
it('should format %l as space padded hour12', function () {
expect(t(now, '%l')).to.equal(' 1')
})
it('should format %l as 12 for 00:00', function () {
const date = new Date('2016-01-01T00:00:00.000Z')
expect(t(date, '%l')).to.equal('12')
})
it('should format %L as 0 padded millisecond', function () {
expect(t(then, '%L')).to.equal('000')
})
it('should format %p as upper cased am/pm', function () {
expect(t(now, '%p')).to.equal('PM')
expect(t(then, '%p')).to.equal('AM')
})
it('should format %P as lower cased am/pm', function () {
expect(t(now, '%P')).to.equal('pm')
expect(t(then, '%P')).to.equal('am')
})
it('should format %q as date suffix', function () {
const st = new Date('2016-03-01T03:05:03.000Z')
const nd = new Date('2016-03-02T03:05:03.000Z')
const rd = new Date('2016-03-03T03:05:03.000Z')
expect(t(st, '%q')).to.equal('st')
expect(t(nd, '%q')).to.equal('nd')
expect(t(rd, '%q')).to.equal('rd')
expect(t(now, '%q')).to.equal('th')
})
it('should format %s as UNIX seconds', function () {
expect(t(now, '%s')).to.be.match(/\d+/)
})
it('should format %u as day of week(1-7)', function () {
expect(t(now, '%u')).to.be.equal('1')
expect(t(then, '%u')).to.be.equal('7')
})
it('should format %U as week of year, starts with 0', function () {
expect(t(now, '%U')).to.equal('01')
})
it('should format %w as day of month(0-7)', function () {
expect(t(now, '%w')).to.be.equal('1')
expect(t(then, '%w')).to.be.equal('0')
})
it('should format %W as week of year, starts with 1', function () {
expect(t(now, '%W')).to.be.equal('01')
})
it('should format %x as local date string', function () {
expect(t(now, '%x')).to.equal(now.toLocaleDateString())
})
it('should format %X as local time string', function () {
expect(t(now, '%X')).to.equal(now.toLocaleTimeString())
})
it('should format %y as 2-digit year', function () {
expect(t(now, '%y')).to.equal('16')
})
it('should format %z as time zone', function () {
expect(t(now, '%z')).to.equal('+0800')
})
it('should format %z as negative time zone', function () {
const date = new Date('2016-01-04T13:15:23.000Z')
date.getTimezoneOffset = () => 480
expect(t(date, '%z')).to.equal('-0800')
})
it('should escape %% as %', function () {
expect(t(now, '%%')).to.equal('%')
})
it('should retain un-recognized formaters', function () {
expect(t(now, '%o')).to.equal('%o')
})
})
function mockUTC () {
const p = Date.prototype
p._getHours = p.getHours
p.getHours = p.getUTCHours
p._getDays = p.getDays
p.getDays = p.getUTCDays
p._getTimezoneOffset = p.getTimezoneOffset
p.getTimezoneOffset = () => -480
}
function restoreUTC () {
const p = Date.prototype
p.getHours = p._getHours
p.getDays = p._getDays
p.getTimezoneOffset = p._getTimezoneOffset
}
+155
View File
@@ -0,0 +1,155 @@
import chai from 'chai'
import sinonChai from 'sinon-chai'
import sinon from 'sinon'
import {RenderError, RenderBreakError} from '../../../src/util/error.js'
import * as _ from '../../../src/util/underscore.js'
const expect = chai.expect
chai.use(sinonChai)
describe('util/underscore', function () {
describe('.isError()', function () {
it('should return true for new Error', function () {
expect(_.isError(new Error())).to.be.true
})
it('should return true for RenderError', function () {
const tpl = {
token: {
input: 'xx'
}
}
expect(_.isError(new RenderError(new Error(), tpl))).to.be.true
})
it('should return true for RenderBreakError', function () {
expect(_.isError(new RenderBreakError())).to.be.true
})
})
describe('.isString()', function () {
it('should return true for literal string', function () {
expect(_.isString('foo')).to.be.true
})
it('should return true String instance', function () {
expect(_.isString(String('foo'))).to.be.true
})
it('should return false for 123 ', function () {
expect(_.isString(123)).to.be.false
})
})
describe('.stringify()', function () {
it('should respect to to_liquid() method', function () {
expect(_.stringify({to_liquid: () => 'foo'})).to.equal('foo')
})
it('should respect to toLiquid() method', function () {
expect(_.stringify({toLiquid: () => 'foo'})).to.equal('foo')
})
it('should recursively call toLiquid()', function () {
expect(_.stringify({toLiquid: () => ({toLiquid: () => 'foo'})})).to.equal('foo')
})
it('should return "null" for null', function () {
expect(_.stringify(null)).to.equal('null')
})
it('should return "undefined" for undefined', function () {
expect(_.stringify(undefined)).to.equal('undefined')
})
})
describe('.forOwn()', function () {
it('should iterate all properties', function () {
const spy = sinon.spy()
const obj = {
foo: 'bar'
}
_.forOwn(obj, spy)
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
})
it('should default to empty object', function () {
const spy = sinon.spy()
_.forOwn(undefined, spy)
expect(spy).to.have.not.been.called
})
it('should not iterate over properties on prototype', function () {
const spy = sinon.spy()
const obj = Object.create({
bar: 'foo'
})
obj.foo = 'bar'
_.forOwn(obj, spy)
expect(spy).to.have.been.calledOnce
expect(spy).to.have.been.calledWith('bar', 'foo', obj)
})
it('should break when returned false', function () {
const spy = sinon.stub().returns(false)
_.forOwn({
'foo': 'foo',
'bar': 'foo'
}, spy)
expect(spy).to.have.been.calledOnce
})
})
describe('.range()', function () {
it('should return a range of integers', function () {
expect(_.range(3, 5)).to.deep.equal([3, 4])
})
it('should treat start as 0 if omitted', function () {
expect(_.range(3)).to.deep.equal([0, 1, 2])
})
})
describe('.isObject()', function () {
it('should return true for function', function () {
expect(_.isObject(x => x)).to.be.true
})
it('should return true for plain object', function () {
expect(_.isObject({})).to.be.true
})
it('should return false for null', function () {
expect(_.isObject(null)).to.be.false
})
it('should return false for number', function () {
expect(_.isObject(2)).to.be.false
})
})
describe('.assign()', function () {
it('should handle null dst', function () {
expect(_.assign(null, {
foo: 'bar'
})).to.deep.equal({
foo: 'bar'
})
})
it('should assign 2 objects', function () {
const src = {
foo: 'foo',
bar: 'bar'
}
const dst = {
foo: 'bar',
kaa: 'kaa'
}
expect(_.assign(dst, src)).to.deep.equal({
foo: 'foo',
bar: 'bar',
kaa: 'kaa'
})
})
it('should assign 3 objects', function () {
expect(_.assign({
foo: 'foo'
}, {
bar: 'bar'
}, {
car: 'car'
})).to.deep.equal({
foo: 'foo',
bar: 'bar',
car: 'car'
})
})
})
describe('.uniq()', function () {
it('should handle empty array', function () {
expect(_.uniq([])).to.deep.equal([])
})
it('should do uniq', function () {
expect(_.uniq([1, 'a', 'a', 1])).to.deep.equal([1, 'a'])
})
})
})
+63
View File
@@ -0,0 +1,63 @@
import {extname, resolve} from '../../../src/util/url.js'
import chai from 'chai'
const expect = chai.expect
describe('util/url', function () {
if (process.version.match(/^v(\d+)/)[1] < 8) {
return
}
const JSDOM = require('jsdom').JSDOM
let dom
beforeEach(function () {
dom = new JSDOM(``, {
url: 'https://example.com/foo/bar/',
contentType: 'text/html',
includeNodeLocations: true
})
global.document = dom.window.document
})
afterEach(function () {
delete global.document
})
describe('resolve', function () {
describe('root', function () {
it('should support relative root', function () {
expect(resolve('./views', 'foo'))
.to.equal('https://example.com/foo/bar/views/foo')
expect(resolve('./views/', 'foo'))
.to.equal('https://example.com/foo/bar/views/foo')
})
it('should support absolute root', function () {
expect(resolve('/views', 'foo'))
.to.equal('https://example.com/views/foo')
expect(resolve('/views/', 'foo'))
.to.equal('https://example.com/views/foo')
})
it('should support empty root', function () {
expect(resolve('', 'page.html'))
.to.equal('https://example.com/foo/bar/page.html')
})
it('should support full url as root', function () {
expect(resolve('https://example.com/views', 'page.html'))
.to.equal('https://example.com/views/page.html')
expect(resolve('https://example.com/views/', 'page.html'))
.to.equal('https://example.com/views/page.html')
})
it('should get the first value when argument is array', function () {
expect(resolve(['https://example.com/views', 'https://google.com/views'], 'page.html'))
.to.equal('https://example.com/views/page.html')
expect(resolve(['https://example.com/views/', 'https://google.com/views'], 'page.html'))
.to.equal('https://example.com/views/page.html')
})
})
describe('extname', function () {
it('should support relative path', function () {
expect(extname('./views/page.html')).to.equal('.html')
})
it('should support absolute path', function () {
expect(extname('/views/page.xml')).to.equal('.xml')
})
})
})
})