{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n+\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":27,"string":"27"},"commit_subject":{"kind":"string","value":"chore(dgeni): Created basic index page"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".html"},"lang":{"kind":"string","value":"template"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676458,"cells":{"id":{"kind":"string","value":"10072108"},"text":{"kind":"string","value":" indexPage.template.html\n ADDFILE\n chore(dgeni): Created basic index page\n\n @@ -0,0 +1,27 @@\n+\n+\n+\n+ \n+ Semantic-UI-Angular\n+ \n+\n+\n+
\n+
\n+

Semantic-UI-Angular

\n+ API Documentation\n+ \n+
v. 0.0.0
\n+
\n+
\n+
\n+
\n+
\n+
\n+
\n+
Built by Dgeni - Open Source ©2014
\n+
\n+
\n+
\n+\n+\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":27,"string":"27"},"commit_subject":{"kind":"string","value":"chore(dgeni): Created basic index page"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".html"},"lang":{"kind":"string","value":"template"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676459,"cells":{"id":{"kind":"string","value":"10072109"},"text":{"kind":"string","value":" indexPage.template.html\n ADDFILE\n chore(dgeni): Created basic index page\n\n @@ -0,0 +1,27 @@\n+\n+\n+\n+ \n+ Semantic-UI-Angular\n+ \n+\n+\n+
\n+
\n+

Semantic-UI-Angular

\n+ API Documentation\n+ \n+
v. 0.0.0
\n+
\n+
\n+
\n+
\n+
\n+
\n+
\n+
Built by Dgeni - Open Source ©2014
\n+
\n+
\n+
\n+\n+\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":27,"string":"27"},"commit_subject":{"kind":"string","value":"chore(dgeni): Created basic index page"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".html"},"lang":{"kind":"string","value":"template"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676460,"cells":{"id":{"kind":"string","value":"10072110"},"text":{"kind":"string","value":" tests.py\n import unittest\nimport StringIO\nfrom djangopypi.views import parse_distutils_request, simple\nfrom djangopypi.models import Project, Classifier\nfrom django.test.client import Client\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\nfrom django.http import HttpRequest\n\ndef create_post_data(action):\n data = {\n \":action\": action,\n \"metadata_version\": \"1.0\",\n \"name\": \"foo\",\n \"version\": \"0.1.0-pre2\",\n \"summary\": \"The quick brown fox jumps over the lazy dog.\",\n \"home_page\": \"http://example.com\",\n \"author\": \"Foo Bar Baz\",\n \"author_email\": \"foobarbaz@example.com\",\n \"license\": \"Apache\",\n \"keywords\": \"foo bar baz\",\n \"platform\": \"UNKNOWN\",\n \"classifiers\": [\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Web Environment\",\n \"Framework :: Django\",\n \"Operating System :: OS Independent\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: BSD License\",\n \"Topic :: System :: Software Distribution\",\n \"Programming Language :: Python\",\n ],\n \"download_url\": \"\",\n \"provides\": \"\",\n \"requires\": \"\",\n \"obsoletes\": \"\",\n \"description\": \"\"\"\n=========\nFOOBARBAZ\n=========\n\nIntroduction\n------------\n ``foo`` :class:`bar`\n *baz*\n [foaoa]\n \"\"\",\n }\n return data\n\ndef create_request(data):\n boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'\n sep_boundary = '\\n--' + boundary\n end_boundary = sep_boundary + '--'\n body = StringIO.StringIO()\n for key, value in data.items():\n # handle multiple entries for the same name\n if type(value) not in (type([]), type( () )):\n value = [value]\n for value in value:\n value = unicode(value).encode(\"utf-8\")\n body.write(sep_boundary)\n body.write('\\nContent-Disposition: form-data; name=\"%s\"'%key)\n body.write(\"\\n\\n\")\n body.write(value)\n if value and value[-1] == '\\r':\n body.write('\\n') # write an extra newline (lurve Macs)\n body.write(end_boundary)\n body.write(\"\\n\")\n\n return body.getvalue()\n\n\nclass MockRequest(object):\n\n def __init__(self, raw_post_data):\n self.raw_post_data = raw_post_data\n self.META = {}\n data = create_post_data(\"submit\")\n raw_post_data = create_request(data)\n post, files = parse_distutils_request(MockRequest(raw_post_data))\n print(\"post: %s files: %s\" % (post, files))\n self.assertTrue(post)\n\n for key in post.keys():\n if isinstance(data[key], list):\n self.assertEquals(data[key], post.getlist(key))\n else:\n self.assertEquals(post[key], data[key])\n self.assertEquals(data[key], post.getlist(key))\n elif data[key] == \"UNKNOWN\":\n self.assertTrue(post[key] is None)\n else:\n self.assertEquals(post[key], data[key])\n\n\n\nclient = Client()\n\nclass TestSearch(unittest.TestCase):\n \n def setUp(self):\n dummy_user = User.objects.create(username='krill', password='12345',\n email='krill@opera.com')\n Project.objects.create(name='foo', license='Gnu',\n summary=\"The quick brown fox jumps over the lazy dog.\",\n owner=dummy_user) \n \n def test_search_for_package(self): \n response = client.post(reverse('djangopypi-search'), {'search_term': 'foo'})\n self.assertTrue(\"The quick brown fox jumps over the lazy dog.\" in response.content)\n \nclass TestSimpleView(unittest.TestCase):\n \n def create_distutils_httprequest(self, user_data={}):\n self.post_data = create_post_data(action='user') \n self.post_data.update(user_data)\n self.raw_post_data = create_request(self.post_data)\n request = HttpRequest()\n request.POST = self.post_data\n request.method = \"POST\"\n request.raw_post_data = self.raw_post_data\n return request \n \n def test_user_registration(self): \n request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'parker@dailybugle.com',\n 'password':'spiderman'})\n response = simple(request)\n self.assertEquals(200, response.status_code)\n \n def test_user_registration_with_wrong_data(self):\n request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'parker@dailybugle.com',\n 'password':'',})\n response = simple(request)\n self.assertEquals(400, response.status_code)\n \n \n Fixes broken unittest. \"test-suite\" now passes again.\n\n @@ -80,11 +80,12 @@ class TestParseWeirdPostData(unittest.TestCase):\n data = create_post_data(\"submit\")\n raw_post_data = create_request(data)\n post, files = parse_distutils_request(MockRequest(raw_post_data))\n- print(\"post: %s files: %s\" % (post, files))\n self.assertTrue(post)\n \n for key in post.keys():\n if isinstance(data[key], list):\n self.assertEquals(data[key], post.getlist(key))\n+ elif data[key] == \"UNKNOWN\":\n+ self.assertTrue(post[key] is None)\n else:\n self.assertEquals(post[key], data[key])\n"},"addition_count":{"kind":"number","value":2,"string":"2"},"commit_subject":{"kind":"string","value":"Fixes broken unittest. \"test-suite\" now passes again."},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".py"},"lang":{"kind":"string","value":"py"},"license":{"kind":"string","value":"bsd-3-clause"},"repo_name":{"kind":"string","value":"ask/chishop"}}},{"rowIdx":10676461,"cells":{"id":{"kind":"string","value":"10072111"},"text":{"kind":"string","value":" convert.ts\n import { equal } from 'assert';\nimport parser, { ParserOptions } from '../src';\nimport stringify from './assets/stringify-node';\n\nfunction parse(abbr: string, options?: ParserOptions) {\n return stringify(parser(abbr, options));\n}\n\ndescribe('Convert token abbreviations', () => {\n it('basic', () => {\n equal(parse('input[value=\"text$\"]*2'), '');\n\n equal(parse('ul>li.item$*3'), '
');\n equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '
    foo$bar$
');\n equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '
    item 1item 2
');\n equal(parse('ul>li.item$*'), '
');\n equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '
    foo.barhello.world
');\n\n equal(parse('p{hi}', { text: ['hello'] }), '

hihello

');\n equal(parse('p*{hi}', { text: ['1', '2'] }), 'hi1

hi2

');\n equal(parse('div>p+p{hi}', { text: ['hello'] }), '

hihello

');\n\n equal(parse('html[lang=${lang}]'), '');\n equal(parse('html.one.two'), '');\n equal(parse('html.one[two=three]'), '');\n equal(parse('div{[}+a{}'), '
[
');\n });\n\n it('unroll', () => {\n equal(parse('a>(b>c)+d'), '');\n equal(parse('(a>b)+(c>d)'), '');\n equal(parse('a>((b>c)(d>e))f'), '');\n equal(parse('a>((((b>c))))+d'), '');\n equal(parse('a>(((b>c))*4)+d'), '');\n equal(parse('(div>dl>(dt+dd)*2)'), '
');\n\n equal(parse('a*2>b*3'), '');\n equal(parse('a>(b+c)*2'), '');\n equal(parse('a>(b+c)*2+(d+e)*2'), '');\n\n // Should move `
` as sibling of `{foo}`\n equal(parse('p>{foo}>div'), '

foo

');\n equal(parse('p>{foo ${0}}>div'), '

foo ${0}

');\n });\n\n it('limit unroll', () => {\n\n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n equal(parse('a$*2>b$^*3/'), '');\n });\n});\n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n equal(parse('a$*2>b$@^*3/'), '');\n });\n\n it('href', () => {\n equal(parse('a', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a', { href: true, text: 'test here' }), 'test here');\n equal(parse('a', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a[href=]', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a[href=]', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a[href=]', { href: true, text: 'test here' }), 'test here');\n equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a.here', { href: true, text: 'www.domain.com' }), 'www.domain.com');\n equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=\"www.google.it\"]', { href: false, text: 'test' }), 'test');\n equal(parse('a[href=\"www.example.com\"]', { href: true, text: 'www.google.it' }), 'www.google.it');\n });\n\n it('wrap basic', () => {\n equal(parse('p', { text: 'test' }), '

test

');\n equal(parse('p', { text: ['test'] }), '

test

');\n equal(parse('p', { text: ['test1', 'test2'] }), '

test1\\ntest2

');\n equal(parse('p', { text: ['test1', '', 'test2'] }), '

test1\\n\\ntest2

');\n equal(parse('p*', { text: ['test1', 'test2'] }), 'test1

test2

');\n equal(parse('p*', { text: ['test1', '', 'test2'] }), 'test1

test2

');\n })\n});\n\n FIxed invalid parsing of repeater number with modifiers\n\n @@ -47,6 +47,6 @@ describe('Convert token abbreviations', () => {\n \n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n- equal(parse('a$*2>b$^*3/'), '');\n+ equal(parse('a$*2>b$@^*3/'), '');\n });\n });\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"FIxed invalid parsing of repeater number with modifiers"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676462,"cells":{"id":{"kind":"string","value":"10072112"},"text":{"kind":"string","value":" convert.ts\n import { equal } from 'assert';\nimport parser, { ParserOptions } from '../src';\nimport stringify from './assets/stringify-node';\n\nfunction parse(abbr: string, options?: ParserOptions) {\n return stringify(parser(abbr, options));\n}\n\ndescribe('Convert token abbreviations', () => {\n it('basic', () => {\n equal(parse('input[value=\"text$\"]*2'), '');\n\n equal(parse('ul>li.item$*3'), '
');\n equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '
    foo$bar$
');\n equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '
    item 1item 2
');\n equal(parse('ul>li.item$*'), '
');\n equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '
    foo.barhello.world
');\n\n equal(parse('p{hi}', { text: ['hello'] }), '

hihello

');\n equal(parse('p*{hi}', { text: ['1', '2'] }), 'hi1

hi2

');\n equal(parse('div>p+p{hi}', { text: ['hello'] }), '

hihello

');\n\n equal(parse('html[lang=${lang}]'), '');\n equal(parse('html.one.two'), '');\n equal(parse('html.one[two=three]'), '');\n equal(parse('div{[}+a{}'), '
[
');\n });\n\n it('unroll', () => {\n equal(parse('a>(b>c)+d'), '');\n equal(parse('(a>b)+(c>d)'), '');\n equal(parse('a>((b>c)(d>e))f'), '');\n equal(parse('a>((((b>c))))+d'), '');\n equal(parse('a>(((b>c))*4)+d'), '');\n equal(parse('(div>dl>(dt+dd)*2)'), '
');\n\n equal(parse('a*2>b*3'), '');\n equal(parse('a>(b+c)*2'), '');\n equal(parse('a>(b+c)*2+(d+e)*2'), '');\n\n // Should move `
` as sibling of `{foo}`\n equal(parse('p>{foo}>div'), '

foo

');\n equal(parse('p>{foo ${0}}>div'), '

foo ${0}

');\n });\n\n it('limit unroll', () => {\n\n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n equal(parse('a$*2>b$^*3/'), '');\n });\n});\n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n equal(parse('a$*2>b$@^*3/'), '');\n });\n\n it('href', () => {\n equal(parse('a', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a', { href: true, text: 'test here' }), 'test here');\n equal(parse('a', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a[href=]', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a[href=]', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a[href=]', { href: true, text: 'test here' }), 'test here');\n equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a.here', { href: true, text: 'www.domain.com' }), 'www.domain.com');\n equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=\"www.google.it\"]', { href: false, text: 'test' }), 'test');\n equal(parse('a[href=\"www.example.com\"]', { href: true, text: 'www.google.it' }), 'www.google.it');\n });\n\n it('wrap basic', () => {\n equal(parse('p', { text: 'test' }), '

test

');\n equal(parse('p', { text: ['test'] }), '

test

');\n equal(parse('p', { text: ['test1', 'test2'] }), '

test1\\ntest2

');\n equal(parse('p', { text: ['test1', '', 'test2'] }), '

test1\\n\\ntest2

');\n equal(parse('p*', { text: ['test1', 'test2'] }), 'test1

test2

');\n equal(parse('p*', { text: ['test1', '', 'test2'] }), 'test1

test2

');\n })\n});\n\n FIxed invalid parsing of repeater number with modifiers\n\n @@ -47,6 +47,6 @@ describe('Convert token abbreviations', () => {\n \n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n- equal(parse('a$*2>b$^*3/'), '');\n+ equal(parse('a$*2>b$@^*3/'), '');\n });\n });\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"FIxed invalid parsing of repeater number with modifiers"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676463,"cells":{"id":{"kind":"string","value":"10072113"},"text":{"kind":"string","value":" expand.ts\n import { strictEqual as equal } from 'assert';\nimport expand, { resolveConfig } from '../src';\n\ndescribe('Expand Abbreviation', () => {\n describe('Markup', () => {\n it('basic', () => {\n equal(expand('input[value=\"text$\"]*2'), '');\n equal(expand('ul>.item$*2'), '
    \\n\\t
  • \\n\\t
  • \\n
');\n\n // insert text into abbreviation\n equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '
    \\n\\t
  • foo
  • \\n\\t
  • bar
  • \\n
');\n\n // insert TextMate-style fields/tabstops in output\n equal(expand('ul>.item$*2', {\n options: {\n 'output.field': (index, placeholder) => `\\${${index}${placeholder ? ':' + placeholder : ''}}`\n }\n }), '
    \\n\\t
  • ${1}
  • \\n\\t
  • ${2}
  • \\n
');\n });\n\n it('attributes', () => {\n const snippets = {\n test: 'test[!foo bar. baz={}]'\n };\n const opt = { snippets };\n const reverse = {\n options: { 'output.reverseAttributes': true },\n snippets\n };\n\n equal(expand('a.test'), '');\n equal(expand('a.test', reverse), '');\n\n equal(expand('test', opt), '');\n equal(expand('test[foo]', opt), '');\n equal(expand('test[baz=a foo=1]', opt), '');\n\n equal(expand('map'), '');\n equal(expand('map[]'), '');\n equal(expand('map[name=\"valid\"]'), '');\n equal(expand('map[href=\"invalid\"]'), '');\n\n // Apply attributes in reverse order\n equal(expand('test', reverse), '');\n equal(expand('test[foo]', reverse), '');\n equal(expand('test[baz=a foo=1]', reverse), '');\n });\n\n it('numbering', () => {\n equal(expand('ul>li.item$@-*5'), '
    \\n\\t
  • \\n\\t
  • \\n\\t
  • \\n\\t
  • \\n\\t
  • \\n
');\n });\n\n it('syntax', () => {\n equal(expand('ul>.item$*2', { syntax: 'html' }), '
    \\n\\t
  • \\n\\t
  • \\n
');\n equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\\n\\tli.item1 \\n\\tli.item2 ');\n equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '\\n\\t
\\n
');\n });\n\n it('custom profile', () => {\n equal(expand('img'), '\"\"');\n equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '\"\"');\n });\n\n it('custom variables', () => {\n const variables = { charset: 'ru-RU' };\n\n equal(expand('[charset=${charset}]{${charset}}'), '
UTF-8
');\n equal(expand('[charset=${charset}]{${charset}}', { variables }), '
ru-RU
');\n });\n\n it('custom snippets', () => {\n const snippets = {\n link: 'link[foo=bar href]/',\n foo: '.foo[bar=baz]',\n repeat: 'div>ul>li{Hello World}*3'\n };\n\n equal(expand('foo', { snippets }), '
');\n\n // `link:css` depends on `link` snippet so changing it will result in\n // altered `link:css` result\n equal(expand('link:css'), '');\n equal(expand('link:css', { snippets }), '');\n\n // https://github.com/emmetio/emmet/issues/468\n equal(expand('repeat', { snippets }), '
\\n\\t
    \\n\\t\\t
  • Hello World
  • \\n\\t\\t
  • Hello World
  • \\n\\t\\t
  • Hello World
  • \\n\\t
\\n
');\n });\n\n it('formatter options', () => {\n equal(expand('ul>.item$*2'), '
    \\n\\t
  • \\n\\t
  • \\n
');\n equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }),\n '
    \\n\\t
  • \\n\\t\\n\\t
  • \\n\\t\\n
');\n\n equal(expand('div>p'), '
\\n\\t

\\n
');\n equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '
\\n\\t

\\n\\t\\t\\n\\t

\\n
');\n });\n\n it('JSX', () => {\n const config = { syntax: 'jsx' };\n equal(expand('div#foo.bar', config), '
');\n equal(expand('label[for=a]', config), '');\n equal(expand('Foo.Bar', config), '');\n equal(expand('div.{theme.style}', config), '
');\n });\n\n it('override attributes', () => {\n const config = { syntax: 'jsx' };\n equal(expand('.bar', config), '
');\n equal(expand('..bar', config), '
');\n equal(expand('..foo-bar', config), '
');\n\n equal(expand('.foo', { syntax: 'vue' }), '
');\n equal(expand('..foo', { syntax: 'vue' }), '
');\n });\n\n describe('Pug templates', () => {\n const config = resolveConfig({ syntax: 'pug' });\n it('basic', () => {\n equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n });\n });\n});\n equal(expand('p', { text: 'foo
foo
' }), '

foo

foo

');\n });\n\n it('wrap with abbreviation href', () => {\n equal(expand('a', { text: ['www.google.it'] }), 'www.google.it');\n equal(expand('a', { text: ['then www.google.it'] }), 'then www.google.it');\n equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), 'www.google.it');\n\n equal(expand('map[name=\"https://example.com\"]', { text: ['some text'] }),\n 'some text');\n equal(expand('map[href=\"https://example.com\"]', { text: ['some text'] }),\n 'some text');\n equal(expand('map[name=\"https://example.com\"]>b', { text: ['some text'] }),\n 'some text');\n\n equal(expand('a[href=\"https://example.com\"]>b', { text: ['some text false'], options: { 'markup.href': false } }),\n 'some text false');\n equal(expand('a[href=\"https://example.com\"]>b', { text: ['some text true'], options: { 'markup.href': true } }),\n 'some text true');\n equal(expand('a[href=\"https://example.com\"]>div', { text: ['

some text false

'], options: { 'markup.href': false } }),\n '\\n\\t
\\n\\t\\t

some text false

\\n\\t
\\n
');\n equal(expand('a[href=\"https://example.com\"]>div', { text: ['

some text true

'], options: { 'markup.href': true } }),\n '\\n\\t
\\n\\t\\t

some text true

\\n\\t
\\n
');\n });\n\n // it.only('debug', () => {\n // equal(expand('link:css'), '');\n // });\n });\n\n describe('Pug templates', () => {\n const config = resolveConfig({ syntax: 'pug' });\n it('basic', () => {\n equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(http-equiv=\"X-UA-Compatible\", content=\"IE=edge\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n });\n });\n});\n\n Fix #619 (#624)\n\n\n @@ -116,7 +116,7 @@ describe('Expand Abbreviation', () => {\n describe('Pug templates', () => {\n const config = resolveConfig({ syntax: 'pug' });\n it('basic', () => {\n- equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n+ equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(http-equiv=\"X-UA-Compatible\", content=\"IE=edge\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n });\n });\n });\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"Fix #619 (#624)"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676464,"cells":{"id":{"kind":"string","value":"10072114"},"text":{"kind":"string","value":" expand.ts\n import { strictEqual as equal } from 'assert';\nimport expand, { resolveConfig } from '../src';\n\ndescribe('Expand Abbreviation', () => {\n describe('Markup', () => {\n it('basic', () => {\n equal(expand('input[value=\"text$\"]*2'), '');\n equal(expand('ul>.item$*2'), '
    \\n\\t
  • \\n\\t
  • \\n
');\n\n // insert text into abbreviation\n equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '
    \\n\\t
  • foo
  • \\n\\t
  • bar
  • \\n
');\n\n // insert TextMate-style fields/tabstops in output\n equal(expand('ul>.item$*2', {\n options: {\n 'output.field': (index, placeholder) => `\\${${index}${placeholder ? ':' + placeholder : ''}}`\n }\n }), '
    \\n\\t
  • ${1}
  • \\n\\t
  • ${2}
  • \\n
');\n });\n\n it('attributes', () => {\n const snippets = {\n test: 'test[!foo bar. baz={}]'\n };\n const opt = { snippets };\n const reverse = {\n options: { 'output.reverseAttributes': true },\n snippets\n };\n\n equal(expand('a.test'), '');\n equal(expand('a.test', reverse), '');\n\n equal(expand('test', opt), '');\n equal(expand('test[foo]', opt), '');\n equal(expand('test[baz=a foo=1]', opt), '');\n\n equal(expand('map'), '');\n equal(expand('map[]'), '');\n equal(expand('map[name=\"valid\"]'), '');\n equal(expand('map[href=\"invalid\"]'), '');\n\n // Apply attributes in reverse order\n equal(expand('test', reverse), '');\n equal(expand('test[foo]', reverse), '');\n equal(expand('test[baz=a foo=1]', reverse), '');\n });\n\n it('numbering', () => {\n equal(expand('ul>li.item$@-*5'), '
    \\n\\t
  • \\n\\t
  • \\n\\t
  • \\n\\t
  • \\n\\t
  • \\n
');\n });\n\n it('syntax', () => {\n equal(expand('ul>.item$*2', { syntax: 'html' }), '
    \\n\\t
  • \\n\\t
  • \\n
');\n equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\\n\\tli.item1 \\n\\tli.item2 ');\n equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '\\n\\t
\\n
');\n });\n\n it('custom profile', () => {\n equal(expand('img'), '\"\"');\n equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '\"\"');\n });\n\n it('custom variables', () => {\n const variables = { charset: 'ru-RU' };\n\n equal(expand('[charset=${charset}]{${charset}}'), '
UTF-8
');\n equal(expand('[charset=${charset}]{${charset}}', { variables }), '
ru-RU
');\n });\n\n it('custom snippets', () => {\n const snippets = {\n link: 'link[foo=bar href]/',\n foo: '.foo[bar=baz]',\n repeat: 'div>ul>li{Hello World}*3'\n };\n\n equal(expand('foo', { snippets }), '
');\n\n // `link:css` depends on `link` snippet so changing it will result in\n // altered `link:css` result\n equal(expand('link:css'), '');\n equal(expand('link:css', { snippets }), '');\n\n // https://github.com/emmetio/emmet/issues/468\n equal(expand('repeat', { snippets }), '
\\n\\t
    \\n\\t\\t
  • Hello World
  • \\n\\t\\t
  • Hello World
  • \\n\\t\\t
  • Hello World
  • \\n\\t
\\n
');\n });\n\n it('formatter options', () => {\n equal(expand('ul>.item$*2'), '
    \\n\\t
  • \\n\\t
  • \\n
');\n equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }),\n '
    \\n\\t
  • \\n\\t\\n\\t
  • \\n\\t\\n
');\n\n equal(expand('div>p'), '
\\n\\t

\\n
');\n equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '
\\n\\t

\\n\\t\\t\\n\\t

\\n
');\n });\n\n it('JSX', () => {\n const config = { syntax: 'jsx' };\n equal(expand('div#foo.bar', config), '
');\n equal(expand('label[for=a]', config), '');\n equal(expand('Foo.Bar', config), '');\n equal(expand('div.{theme.style}', config), '
');\n });\n\n it('override attributes', () => {\n const config = { syntax: 'jsx' };\n equal(expand('.bar', config), '
');\n equal(expand('..bar', config), '
');\n equal(expand('..foo-bar', config), '
');\n\n equal(expand('.foo', { syntax: 'vue' }), '
');\n equal(expand('..foo', { syntax: 'vue' }), '
');\n });\n\n describe('Pug templates', () => {\n const config = resolveConfig({ syntax: 'pug' });\n it('basic', () => {\n equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n });\n });\n});\n equal(expand('p', { text: 'foo
foo
' }), '

foo

foo

');\n });\n\n it('wrap with abbreviation href', () => {\n equal(expand('a', { text: ['www.google.it'] }), 'www.google.it');\n equal(expand('a', { text: ['then www.google.it'] }), 'then www.google.it');\n equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), 'www.google.it');\n\n equal(expand('map[name=\"https://example.com\"]', { text: ['some text'] }),\n 'some text');\n equal(expand('map[href=\"https://example.com\"]', { text: ['some text'] }),\n 'some text');\n equal(expand('map[name=\"https://example.com\"]>b', { text: ['some text'] }),\n 'some text');\n\n equal(expand('a[href=\"https://example.com\"]>b', { text: ['some text false'], options: { 'markup.href': false } }),\n 'some text false');\n equal(expand('a[href=\"https://example.com\"]>b', { text: ['some text true'], options: { 'markup.href': true } }),\n 'some text true');\n equal(expand('a[href=\"https://example.com\"]>div', { text: ['

some text false

'], options: { 'markup.href': false } }),\n '\\n\\t
\\n\\t\\t

some text false

\\n\\t
\\n
');\n equal(expand('a[href=\"https://example.com\"]>div', { text: ['

some text true

'], options: { 'markup.href': true } }),\n '\\n\\t
\\n\\t\\t

some text true

\\n\\t
\\n
');\n });\n\n // it.only('debug', () => {\n // equal(expand('link:css'), '');\n // });\n });\n\n describe('Pug templates', () => {\n const config = resolveConfig({ syntax: 'pug' });\n it('basic', () => {\n equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(http-equiv=\"X-UA-Compatible\", content=\"IE=edge\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n });\n });\n});\n\n Fix #619 (#624)\n\n\n @@ -116,7 +116,7 @@ describe('Expand Abbreviation', () => {\n describe('Pug templates', () => {\n const config = resolveConfig({ syntax: 'pug' });\n it('basic', () => {\n- equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n+ equal(expand('!', config), 'doctype html\\nhtml(lang=\"en\")\\n\\thead\\n\\t\\tmeta(charset=\"UTF-8\")\\n\\t\\tmeta(http-equiv=\"X-UA-Compatible\", content=\"IE=edge\")\\n\\t\\tmeta(name=\"viewport\", content=\"width=device-width, initial-scale=1.0\")\\n\\t\\ttitle Document\\n\\tbody ');\n });\n });\n });\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"Fix #619 (#624)"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676465,"cells":{"id":{"kind":"string","value":"10072115"},"text":{"kind":"string","value":" parser.ts\n import { strictEqual as equal, throws } from 'assert';\nimport parser from '../src/parser';\nimport tokenizer from '../src/tokenizer';\nimport stringify from './assets/stringify';\nimport { ParserOptions } from '../src';\n\nconst parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options);\nconst str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options));\n\ndescribe('Parser', () => {\n it('basic abbreviations', () => {\n equal(str('p'), '

');\n equal(str('p{text}'), '

text

');\n equal(str('h$'), '');\n equal(str('.nav'), '');\n equal(str('div.width1\\\\/2'), '
');\n equal(str('#sample*3'), '');\n\n // https://github.com/emmetio/emmet/issues/562\n equal(str('li[repeat.for=\"todo of todoList\"]'), '
  • ', 'Dots in attribute names');\n\n equal(str('a>b'), '');\n equal(str('a+b'), '');\n equal(str('a+b>c+d'), '');\n equal(str('a>b>c+e'), '');\n equal(str('a>b>c^d'), '');\n equal(str('a>b>c^^^^d'), '');\n equal(str('a:b>c'), '');\n\n equal(str('ul.nav[title=\"foo\"]'), '');\n });\n\n it('groups', () => {\n equal(str('a>(b>c)+d'), '()');\n equal(str('(a>b)+(c>d)'), '()()');\n equal(str('a>((b>c)(d>e))f'), '(()())');\n equal(str('a>((((b>c))))+d'), '(((())))');\n equal(str('a>(((b>c))*4)+d'), '((())*4)');\n equal(str('(div>dl>(dt+dd)*2)'), '(
    (
    )*2
    )');\n equal(str('a>()'), '()');\n });\n\n it('attributes', () => {\n equal(str('[].foo'), '');\n equal(str('[a]'), '');\n equal(str('[a b c [d]]'), '');\n equal(str('[a=b]'), '');\n equal(str('[a=b c= d=e]'), '');\n equal(str('[a=b.c d=тест]'), '');\n equal(str('[[a]=b (c)=d]'), '');\n\n // Quoted attribute values\n equal(str('[a=\"b\"]'), '');\n equal(str('[a=\"b\" c=\\'d\\' e=\"\"]'), '');\n equal(str('[[a]=\"b\" (c)=\\'d\\']'), '');\n\n // Mixed quoted\n equal(str('[a=\"foo\\'bar\" b=\\'foo\"bar\\' c=\"foo\\\\\\\"bar\"]'), '');\n\n // Boolean & implied attributes\n equal(str('[a. b.]'), '');\n equal(str('[!a !b.]'), '');\n\n // Default values\n equal(str('[\"a.b\"]'), '');\n equal(str('[\\'a.b\\' \"c=d\" foo=bar \"./test.html\"]'), '');\n\n // Expressions as values\n equal(str('[foo={1 + 2} bar={fn(1, \"foo\")}]'), '');\n\n // Tabstops as unquoted values\n equal(str('[name=${1} value=${2:test}]'), '');\n });\n\n it('malformed attributes', () => {\n equal(str('[a'), '');\n equal(str('[a={foo]'), '');\n throws(() => str('[a=\"foo]'), /Unclosed quote/);\n throws(() => str('[a=b=c]'), /Unexpected \"Operator\" token/);\n });\n\n it('elements', () => {\n equal(str('div'), '
    ');\n equal(str('div.foo'), '
    ');\n equal(str('div#foo'), '
    ');\n equal(str('div#foo.bar'), '
    ');\n equal(str('div.foo#bar'), '
    ');\n equal(str('div.foo.bar.baz'), '
    ');\n equal(str('.foo'), '');\n equal(str('#foo'), '');\n equal(str('.foo_bar'), '');\n equal(str('#foo.bar'), '');\n\n // Attribute shorthands\n equal(str('.'), '');\n equal(str('#'), '');\n equal(str('#.'), '');\n equal(str('.#.'), '');\n equal(str('.a..'), '');\n\n // Elements with attributes\n equal(str('div[foo=bar]'), '
    ');\n equal(str('div.a[b=c]'), '
    ');\n equal(str('div[b=c].a'), '
    ');\n equal(str('div[a=b][c=\"d\"]'), '
    ');\n equal(str('[b=c]'), '');\n equal(str('.a[b=c]'), '');\n equal(str('[b=c].a#d'), '');\n equal(str('[b=c]a'), '', 'Do not consume node name after attribute set');\n\n // Element with text\n equal(str('div{foo}'), '
    foo
    ');\n equal(str('{foo}'), 'foo');\n\n // Mixed\n equal(str('div.foo{bar}'), '
    bar
    ');\n equal(str('.foo{bar}#baz'), 'bar');\n equal(str('.foo[b=c]{bar}'), 'bar');\n\n // Repeated element\n equal(str('div.foo*3'), '
    ');\n equal(str('.foo*'), '');\n equal(str('.a[b=c]*10'), '');\n equal(str('.a*10[b=c]'), '');\n equal(str('.a*10{text}'), 'text');\n\n // Self-closing element\n equal(str('div/'), '
    ');\n equal(str('.foo/'), '');\n equal(str('.foo[bar]/'), '');\n equal(str('.foo/*3'), '');\n equal(str('.foo*3/'), '');\n\n throws(() => parse('/'), /Unexpected character/);\n });\n\n it('JSX', () => {\n const opt = { jsx: true };\n equal(str('foo.bar', opt), '');\n equal(str('Foo.bar', opt), '');\n equal(str('Foo.Bar', opt), '');\n equal(str('Foo.', opt), '');\n equal(str('Foo.Bar.baz', opt), '');\n equal(str('Foo.Bar.Baz', opt), '');\n\n equal(str('.{theme.class}', opt), '');\n equal(str('#{id}', opt), '');\n equal(str('Foo.{theme.class}', opt), '');\n });\n\n it('errors', () => {\n throws(() => parse('str?'), /Unexpected character at 4/);\n throws(() => parse('foo,bar'), /Unexpected character at 4/);\n equal(str('foo\\\\,bar'), '');\n });\n});\n});\n\n Do not throw errors on missing closing brace\n\n @@ -153,4 +153,11 @@ describe('Parser', () => {\n throws(() => parse('foo,bar'), /Unexpected character at 4/);\n equal(str('foo\\\\,bar'), '');\n });\n+\n+ it('missing braces', () => {\n+ // Do not throw errors on missing closing braces\n+ equal(str('div[title=\"test\"'), '
    ');\n+ equal(str('div(foo'), '
    ()');\n+ equal(str('div{foo'), '
    foo
    ');\n+ });\n });\n"},"addition_count":{"kind":"number","value":7,"string":"7"},"commit_subject":{"kind":"string","value":"Do not throw errors on missing closing brace"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676466,"cells":{"id":{"kind":"string","value":"10072116"},"text":{"kind":"string","value":" parser.ts\n import { strictEqual as equal, throws } from 'assert';\nimport parser from '../src/parser';\nimport tokenizer from '../src/tokenizer';\nimport stringify from './assets/stringify';\nimport { ParserOptions } from '../src';\n\nconst parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options);\nconst str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options));\n\ndescribe('Parser', () => {\n it('basic abbreviations', () => {\n equal(str('p'), '

    ');\n equal(str('p{text}'), '

    text

    ');\n equal(str('h$'), '');\n equal(str('.nav'), '');\n equal(str('div.width1\\\\/2'), '
    ');\n equal(str('#sample*3'), '');\n\n // https://github.com/emmetio/emmet/issues/562\n equal(str('li[repeat.for=\"todo of todoList\"]'), '
  • ', 'Dots in attribute names');\n\n equal(str('a>b'), '');\n equal(str('a+b'), '');\n equal(str('a+b>c+d'), '');\n equal(str('a>b>c+e'), '');\n equal(str('a>b>c^d'), '');\n equal(str('a>b>c^^^^d'), '');\n equal(str('a:b>c'), '');\n\n equal(str('ul.nav[title=\"foo\"]'), '');\n });\n\n it('groups', () => {\n equal(str('a>(b>c)+d'), '()');\n equal(str('(a>b)+(c>d)'), '()()');\n equal(str('a>((b>c)(d>e))f'), '(()())');\n equal(str('a>((((b>c))))+d'), '(((())))');\n equal(str('a>(((b>c))*4)+d'), '((())*4)');\n equal(str('(div>dl>(dt+dd)*2)'), '(
    (
    )*2
    )');\n equal(str('a>()'), '()');\n });\n\n it('attributes', () => {\n equal(str('[].foo'), '');\n equal(str('[a]'), '');\n equal(str('[a b c [d]]'), '');\n equal(str('[a=b]'), '');\n equal(str('[a=b c= d=e]'), '');\n equal(str('[a=b.c d=тест]'), '');\n equal(str('[[a]=b (c)=d]'), '');\n\n // Quoted attribute values\n equal(str('[a=\"b\"]'), '');\n equal(str('[a=\"b\" c=\\'d\\' e=\"\"]'), '');\n equal(str('[[a]=\"b\" (c)=\\'d\\']'), '');\n\n // Mixed quoted\n equal(str('[a=\"foo\\'bar\" b=\\'foo\"bar\\' c=\"foo\\\\\\\"bar\"]'), '');\n\n // Boolean & implied attributes\n equal(str('[a. b.]'), '');\n equal(str('[!a !b.]'), '');\n\n // Default values\n equal(str('[\"a.b\"]'), '');\n equal(str('[\\'a.b\\' \"c=d\" foo=bar \"./test.html\"]'), '');\n\n // Expressions as values\n equal(str('[foo={1 + 2} bar={fn(1, \"foo\")}]'), '');\n\n // Tabstops as unquoted values\n equal(str('[name=${1} value=${2:test}]'), '');\n });\n\n it('malformed attributes', () => {\n equal(str('[a'), '');\n equal(str('[a={foo]'), '');\n throws(() => str('[a=\"foo]'), /Unclosed quote/);\n throws(() => str('[a=b=c]'), /Unexpected \"Operator\" token/);\n });\n\n it('elements', () => {\n equal(str('div'), '
    ');\n equal(str('div.foo'), '
    ');\n equal(str('div#foo'), '
    ');\n equal(str('div#foo.bar'), '
    ');\n equal(str('div.foo#bar'), '
    ');\n equal(str('div.foo.bar.baz'), '
    ');\n equal(str('.foo'), '');\n equal(str('#foo'), '');\n equal(str('.foo_bar'), '');\n equal(str('#foo.bar'), '');\n\n // Attribute shorthands\n equal(str('.'), '');\n equal(str('#'), '');\n equal(str('#.'), '');\n equal(str('.#.'), '');\n equal(str('.a..'), '');\n\n // Elements with attributes\n equal(str('div[foo=bar]'), '
    ');\n equal(str('div.a[b=c]'), '
    ');\n equal(str('div[b=c].a'), '
    ');\n equal(str('div[a=b][c=\"d\"]'), '
    ');\n equal(str('[b=c]'), '');\n equal(str('.a[b=c]'), '');\n equal(str('[b=c].a#d'), '');\n equal(str('[b=c]a'), '', 'Do not consume node name after attribute set');\n\n // Element with text\n equal(str('div{foo}'), '
    foo
    ');\n equal(str('{foo}'), 'foo');\n\n // Mixed\n equal(str('div.foo{bar}'), '
    bar
    ');\n equal(str('.foo{bar}#baz'), 'bar');\n equal(str('.foo[b=c]{bar}'), 'bar');\n\n // Repeated element\n equal(str('div.foo*3'), '
    ');\n equal(str('.foo*'), '');\n equal(str('.a[b=c]*10'), '');\n equal(str('.a*10[b=c]'), '');\n equal(str('.a*10{text}'), 'text');\n\n // Self-closing element\n equal(str('div/'), '
    ');\n equal(str('.foo/'), '');\n equal(str('.foo[bar]/'), '');\n equal(str('.foo/*3'), '');\n equal(str('.foo*3/'), '');\n\n throws(() => parse('/'), /Unexpected character/);\n });\n\n it('JSX', () => {\n const opt = { jsx: true };\n equal(str('foo.bar', opt), '');\n equal(str('Foo.bar', opt), '');\n equal(str('Foo.Bar', opt), '');\n equal(str('Foo.', opt), '');\n equal(str('Foo.Bar.baz', opt), '');\n equal(str('Foo.Bar.Baz', opt), '');\n\n equal(str('.{theme.class}', opt), '');\n equal(str('#{id}', opt), '');\n equal(str('Foo.{theme.class}', opt), '');\n });\n\n it('errors', () => {\n throws(() => parse('str?'), /Unexpected character at 4/);\n throws(() => parse('foo,bar'), /Unexpected character at 4/);\n equal(str('foo\\\\,bar'), '');\n });\n});\n});\n\n Do not throw errors on missing closing brace\n\n @@ -153,4 +153,11 @@ describe('Parser', () => {\n throws(() => parse('foo,bar'), /Unexpected character at 4/);\n equal(str('foo\\\\,bar'), '');\n });\n+\n+ it('missing braces', () => {\n+ // Do not throw errors on missing closing braces\n+ equal(str('div[title=\"test\"'), '
    ');\n+ equal(str('div(foo'), '
    ()');\n+ equal(str('div{foo'), '
    foo
    ');\n+ });\n });\n"},"addition_count":{"kind":"number","value":7,"string":"7"},"commit_subject":{"kind":"string","value":"Do not throw errors on missing closing brace"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676467,"cells":{"id":{"kind":"string","value":"10072117"},"text":{"kind":"string","value":" rating.ts\n ADDFILE\n Merge pull request #51 from mxth/rating\n\nRefactor rating component\n @@ -0,0 +1,173 @@\n+///\r\n+\r\n+'use strict';\r\n+\r\n+const ratingConfig = {\r\n+ max: 5,\r\n+ size: '',\r\n+ stateActive: 'active',\r\n+ stateHover: 'selected',\r\n+ stateHoverParent: 'selected',\r\n+ type: 'star'\r\n+};\r\n+\r\n+class SmRatingController {\r\n+ static $inject = ['$scope', '$element', '$attrs'];\r\n+\r\n+ hoverValue: number;\r\n+ readonly: boolean;\r\n+\r\n+ stateHoverParent: string;\r\n+\r\n+ ratingStates: RatingState[];\r\n+ icons: Icon[];\r\n+\r\n+ ngModel: ng.INgModelController;\r\n+\r\n+ constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) {\r\n+ const\r\n+ ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))),\r\n+ stateActive = this.evalAttribute('stateActive'),\r\n+ stateHover = this.evalAttribute('stateHover'),\r\n+ stateHoverParent = this.evalAttribute('stateHoverParent');\r\n+\r\n+ if (angular.isDefined($attrs.readonly)) {\r\n+ $scope.$watch($attrs.readonly, (readonly: boolean) => {\r\n+ this.readonly = readonly;\r\n+ });\r\n+ }\r\n+\r\n+ this.icons = ratingStates.map((state, index): Icon => {\r\n+ const\r\n+ iconElm = angular.element(''),\r\n+ value = index + 1;\r\n+\r\n+ iconElm.on('mouseenter', () => {\r\n+ $scope.$apply(() => {\r\n+ if (!this.readonly) {\r\n+ this.hoverValue = value;\r\n+ this.$element.addClass(stateHoverParent);\r\n+ this.updateStateHover();\r\n+ }\r\n+ if (angular.isDefined(this.$attrs.onHover)) {\r\n+ this.$scope.$eval(this.$attrs.onHover, { value: value });\r\n+ }\r\n+ });\r\n+ });\r\n+\r\n+ iconElm.on('click', () => {\r\n+ this.rate(value);\r\n+ });\r\n+\r\n+ return angular.extend({\r\n+ element: iconElm,\r\n+ index: index,\r\n+ stateActive: stateActive,\r\n+ stateHover: stateHover\r\n+ }, state);\r\n+ });\r\n+\r\n+ this.icons.forEach(icon => {\r\n+ $element.append(icon.element);\r\n+ });\r\n+\r\n+ $element\r\n+ .addClass('ui rating')\r\n+ .addClass($attrs.type || ratingConfig.type)\r\n+ .addClass($attrs.size || ratingConfig.size)\r\n+ .attr({\r\n+ 'aria-valuemax': this.icons.length,\r\n+ 'aria-valuemin': 0,\r\n+ role: 'slider',\r\n+ tabindex: 0\r\n+ })\r\n+ .on('mouseleave', () => {\r\n+ this.hoverValue = -1;\r\n+ if (angular.isDefined($attrs.onLeave)) {\r\n+ $scope.$evalAsync($attrs.onLeave);\r\n+ }\r\n+ $element.removeClass(stateHoverParent);\r\n+ this.updateStateHover();\r\n+ })\r\n+ .on('keydown', (evt: any) => {\r\n+ if (/(37|38|39|40)/.test(evt.which)) {\r\n+ evt.preventDefault();\r\n+ evt.stopPropagation();\r\n+ this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1));\r\n+ }\r\n+ });\r\n+ }\r\n+\r\n+ rate(value: number) {\r\n+ if (!this.readonly && value >= 0 && value <= this.icons.length) {\r\n+ this.ngModel.$setViewValue(value);\r\n+ this.ngModel.$render();\r\n+ }\r\n+ }\r\n+\r\n+ init(ngModel: ng.INgModelController) {\r\n+ this.ngModel = ngModel;\r\n+\r\n+ ngModel.$render = () => {\r\n+ const value = ngModel.$viewValue;\r\n+ this.$element.attr('aria-valuenow', value);\r\n+\r\n+ this.icons.forEach((icon: Icon, index) => {\r\n+ icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive);\r\n+ });\r\n+ };\r\n+\r\n+ ngModel.$formatters.push((value) => {\r\n+ if (angular.isNumber(value) && value % 1 !== 0) {\r\n+ value = Math.round(value);\r\n+ }\r\n+ return value;\r\n+ });\r\n+ }\r\n+\r\n+ updateStateHover() {\r\n+ this.icons.forEach((icon: Icon, index) => {\r\n+ icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover);\r\n+ });\r\n+ }\r\n+\r\n+ evalAttribute(attr: string) {\r\n+ return angular.isDefined(this.$attrs[attr]) ?\r\n+ this.$scope.$eval(this.$attrs[attr]) :\r\n+ ratingConfig[attr];\r\n+ }\r\n+}\r\n+\r\n+class SmRatingDirective implements ng.IDirective {\r\n+ static instance(): ng.IDirective {\r\n+ return new SmRatingDirective;\r\n+ }\r\n+\r\n+ restrict = 'E';\r\n+ require = ['smRating', 'ngModel'];\r\n+ controller = SmRatingController;\r\n+ link = (\r\n+ scope: ng.IScope,\r\n+ element: ng.IAugmentedJQuery,\r\n+ attrs,\r\n+ ctrls: [SmRatingController, ng.INgModelController]\r\n+ ) => {\r\n+ const [smRating, ngModel] = ctrls;\r\n+ smRating.init(ngModel);\r\n+ };\r\n+}\r\n+\r\n+interface Icon extends RatingState {\r\n+ index: number;\r\n+ element: ng.IAugmentedJQuery;\r\n+}\r\n+\r\n+interface RatingState {\r\n+ stateActive: string;\r\n+ stateHover: string;\r\n+}\r\n+\r\n+export const smRatingModule = angular\r\n+ .module('semantic.ui.modules.rating', [])\r\n+ .directive('smRating', SmRatingDirective.instance)\r\n+ .constant('ratingConfig', ratingConfig);\r\n"},"addition_count":{"kind":"number","value":173,"string":"173"},"commit_subject":{"kind":"string","value":"Merge pull request #51 from mxth/rating"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676468,"cells":{"id":{"kind":"string","value":"10072118"},"text":{"kind":"string","value":" rating.ts\n ADDFILE\n Merge pull request #51 from mxth/rating\n\nRefactor rating component\n @@ -0,0 +1,173 @@\n+///\r\n+\r\n+'use strict';\r\n+\r\n+const ratingConfig = {\r\n+ max: 5,\r\n+ size: '',\r\n+ stateActive: 'active',\r\n+ stateHover: 'selected',\r\n+ stateHoverParent: 'selected',\r\n+ type: 'star'\r\n+};\r\n+\r\n+class SmRatingController {\r\n+ static $inject = ['$scope', '$element', '$attrs'];\r\n+\r\n+ hoverValue: number;\r\n+ readonly: boolean;\r\n+\r\n+ stateHoverParent: string;\r\n+\r\n+ ratingStates: RatingState[];\r\n+ icons: Icon[];\r\n+\r\n+ ngModel: ng.INgModelController;\r\n+\r\n+ constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) {\r\n+ const\r\n+ ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))),\r\n+ stateActive = this.evalAttribute('stateActive'),\r\n+ stateHover = this.evalAttribute('stateHover'),\r\n+ stateHoverParent = this.evalAttribute('stateHoverParent');\r\n+\r\n+ if (angular.isDefined($attrs.readonly)) {\r\n+ $scope.$watch($attrs.readonly, (readonly: boolean) => {\r\n+ this.readonly = readonly;\r\n+ });\r\n+ }\r\n+\r\n+ this.icons = ratingStates.map((state, index): Icon => {\r\n+ const\r\n+ iconElm = angular.element(''),\r\n+ value = index + 1;\r\n+\r\n+ iconElm.on('mouseenter', () => {\r\n+ $scope.$apply(() => {\r\n+ if (!this.readonly) {\r\n+ this.hoverValue = value;\r\n+ this.$element.addClass(stateHoverParent);\r\n+ this.updateStateHover();\r\n+ }\r\n+ if (angular.isDefined(this.$attrs.onHover)) {\r\n+ this.$scope.$eval(this.$attrs.onHover, { value: value });\r\n+ }\r\n+ });\r\n+ });\r\n+\r\n+ iconElm.on('click', () => {\r\n+ this.rate(value);\r\n+ });\r\n+\r\n+ return angular.extend({\r\n+ element: iconElm,\r\n+ index: index,\r\n+ stateActive: stateActive,\r\n+ stateHover: stateHover\r\n+ }, state);\r\n+ });\r\n+\r\n+ this.icons.forEach(icon => {\r\n+ $element.append(icon.element);\r\n+ });\r\n+\r\n+ $element\r\n+ .addClass('ui rating')\r\n+ .addClass($attrs.type || ratingConfig.type)\r\n+ .addClass($attrs.size || ratingConfig.size)\r\n+ .attr({\r\n+ 'aria-valuemax': this.icons.length,\r\n+ 'aria-valuemin': 0,\r\n+ role: 'slider',\r\n+ tabindex: 0\r\n+ })\r\n+ .on('mouseleave', () => {\r\n+ this.hoverValue = -1;\r\n+ if (angular.isDefined($attrs.onLeave)) {\r\n+ $scope.$evalAsync($attrs.onLeave);\r\n+ }\r\n+ $element.removeClass(stateHoverParent);\r\n+ this.updateStateHover();\r\n+ })\r\n+ .on('keydown', (evt: any) => {\r\n+ if (/(37|38|39|40)/.test(evt.which)) {\r\n+ evt.preventDefault();\r\n+ evt.stopPropagation();\r\n+ this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1));\r\n+ }\r\n+ });\r\n+ }\r\n+\r\n+ rate(value: number) {\r\n+ if (!this.readonly && value >= 0 && value <= this.icons.length) {\r\n+ this.ngModel.$setViewValue(value);\r\n+ this.ngModel.$render();\r\n+ }\r\n+ }\r\n+\r\n+ init(ngModel: ng.INgModelController) {\r\n+ this.ngModel = ngModel;\r\n+\r\n+ ngModel.$render = () => {\r\n+ const value = ngModel.$viewValue;\r\n+ this.$element.attr('aria-valuenow', value);\r\n+\r\n+ this.icons.forEach((icon: Icon, index) => {\r\n+ icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive);\r\n+ });\r\n+ };\r\n+\r\n+ ngModel.$formatters.push((value) => {\r\n+ if (angular.isNumber(value) && value % 1 !== 0) {\r\n+ value = Math.round(value);\r\n+ }\r\n+ return value;\r\n+ });\r\n+ }\r\n+\r\n+ updateStateHover() {\r\n+ this.icons.forEach((icon: Icon, index) => {\r\n+ icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover);\r\n+ });\r\n+ }\r\n+\r\n+ evalAttribute(attr: string) {\r\n+ return angular.isDefined(this.$attrs[attr]) ?\r\n+ this.$scope.$eval(this.$attrs[attr]) :\r\n+ ratingConfig[attr];\r\n+ }\r\n+}\r\n+\r\n+class SmRatingDirective implements ng.IDirective {\r\n+ static instance(): ng.IDirective {\r\n+ return new SmRatingDirective;\r\n+ }\r\n+\r\n+ restrict = 'E';\r\n+ require = ['smRating', 'ngModel'];\r\n+ controller = SmRatingController;\r\n+ link = (\r\n+ scope: ng.IScope,\r\n+ element: ng.IAugmentedJQuery,\r\n+ attrs,\r\n+ ctrls: [SmRatingController, ng.INgModelController]\r\n+ ) => {\r\n+ const [smRating, ngModel] = ctrls;\r\n+ smRating.init(ngModel);\r\n+ };\r\n+}\r\n+\r\n+interface Icon extends RatingState {\r\n+ index: number;\r\n+ element: ng.IAugmentedJQuery;\r\n+}\r\n+\r\n+interface RatingState {\r\n+ stateActive: string;\r\n+ stateHover: string;\r\n+}\r\n+\r\n+export const smRatingModule = angular\r\n+ .module('semantic.ui.modules.rating', [])\r\n+ .directive('smRating', SmRatingDirective.instance)\r\n+ .constant('ratingConfig', ratingConfig);\r\n"},"addition_count":{"kind":"number","value":173,"string":"173"},"commit_subject":{"kind":"string","value":"Merge pull request #51 from mxth/rating"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676469,"cells":{"id":{"kind":"string","value":"10072119"},"text":{"kind":"string","value":" rating.ts\n ADDFILE\n Merge pull request #51 from mxth/rating\n\nRefactor rating component\n @@ -0,0 +1,173 @@\n+///\r\n+\r\n+'use strict';\r\n+\r\n+const ratingConfig = {\r\n+ max: 5,\r\n+ size: '',\r\n+ stateActive: 'active',\r\n+ stateHover: 'selected',\r\n+ stateHoverParent: 'selected',\r\n+ type: 'star'\r\n+};\r\n+\r\n+class SmRatingController {\r\n+ static $inject = ['$scope', '$element', '$attrs'];\r\n+\r\n+ hoverValue: number;\r\n+ readonly: boolean;\r\n+\r\n+ stateHoverParent: string;\r\n+\r\n+ ratingStates: RatingState[];\r\n+ icons: Icon[];\r\n+\r\n+ ngModel: ng.INgModelController;\r\n+\r\n+ constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) {\r\n+ const\r\n+ ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))),\r\n+ stateActive = this.evalAttribute('stateActive'),\r\n+ stateHover = this.evalAttribute('stateHover'),\r\n+ stateHoverParent = this.evalAttribute('stateHoverParent');\r\n+\r\n+ if (angular.isDefined($attrs.readonly)) {\r\n+ $scope.$watch($attrs.readonly, (readonly: boolean) => {\r\n+ this.readonly = readonly;\r\n+ });\r\n+ }\r\n+\r\n+ this.icons = ratingStates.map((state, index): Icon => {\r\n+ const\r\n+ iconElm = angular.element(''),\r\n+ value = index + 1;\r\n+\r\n+ iconElm.on('mouseenter', () => {\r\n+ $scope.$apply(() => {\r\n+ if (!this.readonly) {\r\n+ this.hoverValue = value;\r\n+ this.$element.addClass(stateHoverParent);\r\n+ this.updateStateHover();\r\n+ }\r\n+ if (angular.isDefined(this.$attrs.onHover)) {\r\n+ this.$scope.$eval(this.$attrs.onHover, { value: value });\r\n+ }\r\n+ });\r\n+ });\r\n+\r\n+ iconElm.on('click', () => {\r\n+ this.rate(value);\r\n+ });\r\n+\r\n+ return angular.extend({\r\n+ element: iconElm,\r\n+ index: index,\r\n+ stateActive: stateActive,\r\n+ stateHover: stateHover\r\n+ }, state);\r\n+ });\r\n+\r\n+ this.icons.forEach(icon => {\r\n+ $element.append(icon.element);\r\n+ });\r\n+\r\n+ $element\r\n+ .addClass('ui rating')\r\n+ .addClass($attrs.type || ratingConfig.type)\r\n+ .addClass($attrs.size || ratingConfig.size)\r\n+ .attr({\r\n+ 'aria-valuemax': this.icons.length,\r\n+ 'aria-valuemin': 0,\r\n+ role: 'slider',\r\n+ tabindex: 0\r\n+ })\r\n+ .on('mouseleave', () => {\r\n+ this.hoverValue = -1;\r\n+ if (angular.isDefined($attrs.onLeave)) {\r\n+ $scope.$evalAsync($attrs.onLeave);\r\n+ }\r\n+ $element.removeClass(stateHoverParent);\r\n+ this.updateStateHover();\r\n+ })\r\n+ .on('keydown', (evt: any) => {\r\n+ if (/(37|38|39|40)/.test(evt.which)) {\r\n+ evt.preventDefault();\r\n+ evt.stopPropagation();\r\n+ this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1));\r\n+ }\r\n+ });\r\n+ }\r\n+\r\n+ rate(value: number) {\r\n+ if (!this.readonly && value >= 0 && value <= this.icons.length) {\r\n+ this.ngModel.$setViewValue(value);\r\n+ this.ngModel.$render();\r\n+ }\r\n+ }\r\n+\r\n+ init(ngModel: ng.INgModelController) {\r\n+ this.ngModel = ngModel;\r\n+\r\n+ ngModel.$render = () => {\r\n+ const value = ngModel.$viewValue;\r\n+ this.$element.attr('aria-valuenow', value);\r\n+\r\n+ this.icons.forEach((icon: Icon, index) => {\r\n+ icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive);\r\n+ });\r\n+ };\r\n+\r\n+ ngModel.$formatters.push((value) => {\r\n+ if (angular.isNumber(value) && value % 1 !== 0) {\r\n+ value = Math.round(value);\r\n+ }\r\n+ return value;\r\n+ });\r\n+ }\r\n+\r\n+ updateStateHover() {\r\n+ this.icons.forEach((icon: Icon, index) => {\r\n+ icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover);\r\n+ });\r\n+ }\r\n+\r\n+ evalAttribute(attr: string) {\r\n+ return angular.isDefined(this.$attrs[attr]) ?\r\n+ this.$scope.$eval(this.$attrs[attr]) :\r\n+ ratingConfig[attr];\r\n+ }\r\n+}\r\n+\r\n+class SmRatingDirective implements ng.IDirective {\r\n+ static instance(): ng.IDirective {\r\n+ return new SmRatingDirective;\r\n+ }\r\n+\r\n+ restrict = 'E';\r\n+ require = ['smRating', 'ngModel'];\r\n+ controller = SmRatingController;\r\n+ link = (\r\n+ scope: ng.IScope,\r\n+ element: ng.IAugmentedJQuery,\r\n+ attrs,\r\n+ ctrls: [SmRatingController, ng.INgModelController]\r\n+ ) => {\r\n+ const [smRating, ngModel] = ctrls;\r\n+ smRating.init(ngModel);\r\n+ };\r\n+}\r\n+\r\n+interface Icon extends RatingState {\r\n+ index: number;\r\n+ element: ng.IAugmentedJQuery;\r\n+}\r\n+\r\n+interface RatingState {\r\n+ stateActive: string;\r\n+ stateHover: string;\r\n+}\r\n+\r\n+export const smRatingModule = angular\r\n+ .module('semantic.ui.modules.rating', [])\r\n+ .directive('smRating', SmRatingDirective.instance)\r\n+ .constant('ratingConfig', ratingConfig);\r\n"},"addition_count":{"kind":"number","value":173,"string":"173"},"commit_subject":{"kind":"string","value":"Merge pull request #51 from mxth/rating"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676470,"cells":{"id":{"kind":"string","value":"10072120"},"text":{"kind":"string","value":" style.css\n html {\n background: #efefef;\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-size: 13px;\n}\n\nbody {\n padding: 0 10px;\n margin: 10px auto 0;\n}\n\n.header {\n background: #ededed;\n background: -webkit-gradient(linear, left top, left bottom,\n color-stop(0%,#576a76),\n color-stop(100%,#4d5256));\n background: -moz-linear-gradient(top, #576076 0%, #414e58 100%);\n background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: -o-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: linear-gradient(top, #576a76 0%, #414e58 100%);\n border-bottom: 1px solid #fff;\n -moz-border-radius-topleft: 5px;\n -webkit-border-top-left-radius: 5px;\n border-top-left-radius: 5px;\n -moz-border-radius-topright: 5px;\n -webkit-border-top-right-radius:5px;\n border-top-right-radius: 5px;\n\n overflow:hidden;\n padding: 10px 5%;\n text-shadow:0 1px 0 #000;\n}\n\n}\n\n.reset{\n font-size:10px;\n line-height:38px;\n}\n\n.header ul li {\n display: inline;\n}\n\n.header ul li a {\n color: #eee;\n text-decoration: none;\n margin-right: 10px;\n display: inline-block;\n padding: 4px 8px;\n -moz-border-radius: 10px;\n -webkit-border-radius:10px;\n border-radius: 10px;\n\n}\n\n.header ul li a:hover {\n background: rgba(255,255,255,0.1);\n}\n\n.header ul li a:active {\n -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);\n box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n}\n\n.header ul li.current a {\n background: rgba(255,255,255,0.1);\n -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);\n box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n color: #fff;\n}\n\n.header p.environment {\n clear: both;\n padding: 10px 0 0 0;\n color: #BBB;\n font-style: italic;\n float: right;\n}\n\n#main {\n padding: 10px 5%;\n background: #f9f9f9;\n border:1px solid #ccc;\n border-top:none;\n -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2);\n -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2);\n box-shadow: 0 3px 10px rgba(0,0,0,0.2);\n overflow: hidden;\n}\n\n#main .logo {\n float: right;\n margin: 10px;\n}\n\n#main span.hl {\n background: #efefef;\n padding: 2px;\n}\n\n#main h1 {\n margin: 10px 0;\n font-size: 190%;\n font-weight: bold;\n color: #0080FF;\n}\n\n#main table {\n width: 100%;\n margin:0 0 10px;\n}\n\n#main table tr td, #main table tr th {\n border-bottom: 1px solid #ccc;\n padding: 6px;\n}\n\n#main table tr th {\n background: #efefef;\n color: #888;\n font-size: 80%;\n text-transform:uppercase;\n}\n\n#main table tr td.no-data {\n text-align: center;\n padding: 40px 0;\n color: #999;\n font-style: italic;\n font-size: 130%;\n}\n\n#main a {\n color: #111;\n}\n\n#main p {\n margin: 5px 0;\n}\n\n#main p.intro {\n margin-bottom: 15px;\n font-size: 85%;\n color: #999;\n margin-top: 0;\n line-height: 1.3;\n}\n\n#main h1.wi {\n margin-bottom: 5px;\n}\n\n#main p.sub {\n font-size: 95%;\n color: #999;\n}\n\n.experiment {\n background:#fff;\n border: 1px solid #eee;\n border-bottom:none;\n margin:30px 0;\n}\n\n.experiment_with_goal {\n margin: -32px 0 30px 0;\n}\n\n.experiment .experiment-header {\n background: #f4f4f4;\n background: -webkit-gradient(linear, left top, left bottom,\n color-stop(0%,#f4f4f4),\n color-stop(100%,#e0e0e0));\n background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%);\n background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n border-top:1px solid #fff;\n overflow:hidden;\n padding:0 10px;\n}\n\n.experiment h2 {\n color:#888;\n margin: 12px 0 12px 0;\n font-size: 1em;\n font-weight:bold;\n float:left;\n text-shadow:0 1px 0 rgba(255,255,255,0.8);\n}\n\n.experiment h2 .goal {\n font-style: italic;\n}\n\n.experiment h2 .version {\n font-style:italic;\n font-size:0.8em;\n color:#bbb;\n font-weight:normal;\n}\n\n.experiment table em{\n font-style:italic;\n font-size:0.9em;\n color:#bbb;\n}\n\n.experiment table .totals td {\n background: #eee;\n font-weight: bold;\n}\n\n#footer {\n padding: 10px 5%;\n color: #999;\n font-size: 85%;\n line-height: 1.5;\n padding-top: 10px;\n}\n\n#footer p a {\n color: #999;\n}\n\n.inline-controls {\n float:right;\n}\n\n.inline-controls small {\n color: #888;\n font-size: 11px;\n}\n\n.inline-controls form {\n display: inline-block;\n font-size: 10px;\n line-height: 38px;\n}\n\n.inline-controls input {\n margin-left: 10px;\n}\n\n.worse, .better {\n color: #773F3F;\n font-size: 10px;\n font-weight:bold;\n}\n\n.better {\n color: #408C48;\n}\n\n.experiment a.button, .experiment button, .experiment input[type=\"submit\"] {\n padding: 4px 10px;\n overflow: hidden;\n background: #d8dae0;\n -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5);\n -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5);\n box-shadow: 0 1px 0 rgba(0,0,0,0.5);\n border:none;\n -moz-border-radius: 30px;\n -webkit-border-radius:30px;\n border-radius: 30px;\n color:#2e3035;\n cursor: pointer;\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n text-decoration: none;\n text-shadow:0 1px 0 rgba(255,255,255,0.8);\n -moz-user-select: none;\n -webkit-user-select:none;\n user-select: none;\n white-space: nowrap;\n}\na.button:hover, button:hover, input[type=\"submit\"]:hover,\na.button:focus, button:focus, input[type=\"submit\"]:focus{\n background:#bbbfc7;\n}\na.button:active, button:active, input[type=\"submit\"]:active{\n -moz-box-shadow: inset 0 0 4px #484d57;\n -webkit-box-shadow:inset 0 0 4px #484d57;\n box-shadow: inset 0 0 4px #484d57;\n position:relative;\n top:1px;\n}\n\na.button.red, button.red, input[type=\"submit\"].red,\na.button.green, button.green, input[type=\"submit\"].green {\n color:#fff;\n text-shadow:0 1px 0 rgba(0,0,0,0.4);\n}\n\na.button.red, button.red, input[type=\"submit\"].red {\n background:#a56d6d;\n}\na.button.red:hover, button.red:hover, input[type=\"submit\"].red:hover,\na.button.red:focus, button.red:focus, input[type=\"submit\"].red:focus {\n background:#895C5C;\n}\na.button.green, button.green, input[type=\"submit\"].green {\n background:#8daa92;\n}\na.button.green:hover, button.green:hover, input[type=\"submit\"].green:hover,\na.button.green:focus, button.green:focus, input[type=\"submit\"].green:focus {\n background:#768E7A;\n}\n\n.dashboard-controls input, .dashboard-controls select {\n padding: 10px;\n}\n\n.dashboard-controls-bottom {\n margin-top: 10px;\n}\n\n.pagination {\n text-align: center;\n font-size: 15px;\n}\n\n.pagination a, .paginaton span {\n display: inline-block;\n padding: 5px;\n}\n\n.divider {\n display: inline-block;\n margin-left: 10px;\n}\n\n no more massive clickable area on the reset button\n @@ -35,6 +35,7 @@ h2{\n }\n \n .reset{\n+ display:inline-block;\n font-size:10px;\n line-height:38px;\n }\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"no more massive clickable area on the reset button"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".css"},"lang":{"kind":"string","value":"css"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676471,"cells":{"id":{"kind":"string","value":"10072121"},"text":{"kind":"string","value":" style.css\n html {\n background: #efefef;\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-size: 13px;\n}\n\nbody {\n padding: 0 10px;\n margin: 10px auto 0;\n}\n\n.header {\n background: #ededed;\n background: -webkit-gradient(linear, left top, left bottom,\n color-stop(0%,#576a76),\n color-stop(100%,#4d5256));\n background: -moz-linear-gradient(top, #576076 0%, #414e58 100%);\n background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: -o-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: linear-gradient(top, #576a76 0%, #414e58 100%);\n border-bottom: 1px solid #fff;\n -moz-border-radius-topleft: 5px;\n -webkit-border-top-left-radius: 5px;\n border-top-left-radius: 5px;\n -moz-border-radius-topright: 5px;\n -webkit-border-top-right-radius:5px;\n border-top-right-radius: 5px;\n\n overflow:hidden;\n padding: 10px 5%;\n text-shadow:0 1px 0 #000;\n}\n\n}\n\n.reset{\n font-size:10px;\n line-height:38px;\n}\n\n.header ul li {\n display: inline;\n}\n\n.header ul li a {\n color: #eee;\n text-decoration: none;\n margin-right: 10px;\n display: inline-block;\n padding: 4px 8px;\n -moz-border-radius: 10px;\n -webkit-border-radius:10px;\n border-radius: 10px;\n\n}\n\n.header ul li a:hover {\n background: rgba(255,255,255,0.1);\n}\n\n.header ul li a:active {\n -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);\n box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n}\n\n.header ul li.current a {\n background: rgba(255,255,255,0.1);\n -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);\n box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n color: #fff;\n}\n\n.header p.environment {\n clear: both;\n padding: 10px 0 0 0;\n color: #BBB;\n font-style: italic;\n float: right;\n}\n\n#main {\n padding: 10px 5%;\n background: #f9f9f9;\n border:1px solid #ccc;\n border-top:none;\n -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2);\n -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2);\n box-shadow: 0 3px 10px rgba(0,0,0,0.2);\n overflow: hidden;\n}\n\n#main .logo {\n float: right;\n margin: 10px;\n}\n\n#main span.hl {\n background: #efefef;\n padding: 2px;\n}\n\n#main h1 {\n margin: 10px 0;\n font-size: 190%;\n font-weight: bold;\n color: #0080FF;\n}\n\n#main table {\n width: 100%;\n margin:0 0 10px;\n}\n\n#main table tr td, #main table tr th {\n border-bottom: 1px solid #ccc;\n padding: 6px;\n}\n\n#main table tr th {\n background: #efefef;\n color: #888;\n font-size: 80%;\n text-transform:uppercase;\n}\n\n#main table tr td.no-data {\n text-align: center;\n padding: 40px 0;\n color: #999;\n font-style: italic;\n font-size: 130%;\n}\n\n#main a {\n color: #111;\n}\n\n#main p {\n margin: 5px 0;\n}\n\n#main p.intro {\n margin-bottom: 15px;\n font-size: 85%;\n color: #999;\n margin-top: 0;\n line-height: 1.3;\n}\n\n#main h1.wi {\n margin-bottom: 5px;\n}\n\n#main p.sub {\n font-size: 95%;\n color: #999;\n}\n\n.experiment {\n background:#fff;\n border: 1px solid #eee;\n border-bottom:none;\n margin:30px 0;\n}\n\n.experiment_with_goal {\n margin: -32px 0 30px 0;\n}\n\n.experiment .experiment-header {\n background: #f4f4f4;\n background: -webkit-gradient(linear, left top, left bottom,\n color-stop(0%,#f4f4f4),\n color-stop(100%,#e0e0e0));\n background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%);\n background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n border-top:1px solid #fff;\n overflow:hidden;\n padding:0 10px;\n}\n\n.experiment h2 {\n color:#888;\n margin: 12px 0 12px 0;\n font-size: 1em;\n font-weight:bold;\n float:left;\n text-shadow:0 1px 0 rgba(255,255,255,0.8);\n}\n\n.experiment h2 .goal {\n font-style: italic;\n}\n\n.experiment h2 .version {\n font-style:italic;\n font-size:0.8em;\n color:#bbb;\n font-weight:normal;\n}\n\n.experiment table em{\n font-style:italic;\n font-size:0.9em;\n color:#bbb;\n}\n\n.experiment table .totals td {\n background: #eee;\n font-weight: bold;\n}\n\n#footer {\n padding: 10px 5%;\n color: #999;\n font-size: 85%;\n line-height: 1.5;\n padding-top: 10px;\n}\n\n#footer p a {\n color: #999;\n}\n\n.inline-controls {\n float:right;\n}\n\n.inline-controls small {\n color: #888;\n font-size: 11px;\n}\n\n.inline-controls form {\n display: inline-block;\n font-size: 10px;\n line-height: 38px;\n}\n\n.inline-controls input {\n margin-left: 10px;\n}\n\n.worse, .better {\n color: #773F3F;\n font-size: 10px;\n font-weight:bold;\n}\n\n.better {\n color: #408C48;\n}\n\n.experiment a.button, .experiment button, .experiment input[type=\"submit\"] {\n padding: 4px 10px;\n overflow: hidden;\n background: #d8dae0;\n -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5);\n -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5);\n box-shadow: 0 1px 0 rgba(0,0,0,0.5);\n border:none;\n -moz-border-radius: 30px;\n -webkit-border-radius:30px;\n border-radius: 30px;\n color:#2e3035;\n cursor: pointer;\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n text-decoration: none;\n text-shadow:0 1px 0 rgba(255,255,255,0.8);\n -moz-user-select: none;\n -webkit-user-select:none;\n user-select: none;\n white-space: nowrap;\n}\na.button:hover, button:hover, input[type=\"submit\"]:hover,\na.button:focus, button:focus, input[type=\"submit\"]:focus{\n background:#bbbfc7;\n}\na.button:active, button:active, input[type=\"submit\"]:active{\n -moz-box-shadow: inset 0 0 4px #484d57;\n -webkit-box-shadow:inset 0 0 4px #484d57;\n box-shadow: inset 0 0 4px #484d57;\n position:relative;\n top:1px;\n}\n\na.button.red, button.red, input[type=\"submit\"].red,\na.button.green, button.green, input[type=\"submit\"].green {\n color:#fff;\n text-shadow:0 1px 0 rgba(0,0,0,0.4);\n}\n\na.button.red, button.red, input[type=\"submit\"].red {\n background:#a56d6d;\n}\na.button.red:hover, button.red:hover, input[type=\"submit\"].red:hover,\na.button.red:focus, button.red:focus, input[type=\"submit\"].red:focus {\n background:#895C5C;\n}\na.button.green, button.green, input[type=\"submit\"].green {\n background:#8daa92;\n}\na.button.green:hover, button.green:hover, input[type=\"submit\"].green:hover,\na.button.green:focus, button.green:focus, input[type=\"submit\"].green:focus {\n background:#768E7A;\n}\n\n.dashboard-controls input, .dashboard-controls select {\n padding: 10px;\n}\n\n.dashboard-controls-bottom {\n margin-top: 10px;\n}\n\n.pagination {\n text-align: center;\n font-size: 15px;\n}\n\n.pagination a, .paginaton span {\n display: inline-block;\n padding: 5px;\n}\n\n.divider {\n display: inline-block;\n margin-left: 10px;\n}\n\n no more massive clickable area on the reset button\n @@ -35,6 +35,7 @@ h2{\n }\n \n .reset{\n+ display:inline-block;\n font-size:10px;\n line-height:38px;\n }\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"no more massive clickable area on the reset button"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".css"},"lang":{"kind":"string","value":"css"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676472,"cells":{"id":{"kind":"string","value":"10072122"},"text":{"kind":"string","value":" style.css\n html {\n background: #efefef;\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-size: 13px;\n}\n\nbody {\n padding: 0 10px;\n margin: 10px auto 0;\n}\n\n.header {\n background: #ededed;\n background: -webkit-gradient(linear, left top, left bottom,\n color-stop(0%,#576a76),\n color-stop(100%,#4d5256));\n background: -moz-linear-gradient(top, #576076 0%, #414e58 100%);\n background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: -o-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%);\n background: linear-gradient(top, #576a76 0%, #414e58 100%);\n border-bottom: 1px solid #fff;\n -moz-border-radius-topleft: 5px;\n -webkit-border-top-left-radius: 5px;\n border-top-left-radius: 5px;\n -moz-border-radius-topright: 5px;\n -webkit-border-top-right-radius:5px;\n border-top-right-radius: 5px;\n\n overflow:hidden;\n padding: 10px 5%;\n text-shadow:0 1px 0 #000;\n}\n\n}\n\n.reset{\n font-size:10px;\n line-height:38px;\n}\n\n.header ul li {\n display: inline;\n}\n\n.header ul li a {\n color: #eee;\n text-decoration: none;\n margin-right: 10px;\n display: inline-block;\n padding: 4px 8px;\n -moz-border-radius: 10px;\n -webkit-border-radius:10px;\n border-radius: 10px;\n\n}\n\n.header ul li a:hover {\n background: rgba(255,255,255,0.1);\n}\n\n.header ul li a:active {\n -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);\n box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n}\n\n.header ul li.current a {\n background: rgba(255,255,255,0.1);\n -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2);\n box-shadow: inset 0 1px 0 rgba(0,0,0,0.2);\n color: #fff;\n}\n\n.header p.environment {\n clear: both;\n padding: 10px 0 0 0;\n color: #BBB;\n font-style: italic;\n float: right;\n}\n\n#main {\n padding: 10px 5%;\n background: #f9f9f9;\n border:1px solid #ccc;\n border-top:none;\n -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2);\n -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2);\n box-shadow: 0 3px 10px rgba(0,0,0,0.2);\n overflow: hidden;\n}\n\n#main .logo {\n float: right;\n margin: 10px;\n}\n\n#main span.hl {\n background: #efefef;\n padding: 2px;\n}\n\n#main h1 {\n margin: 10px 0;\n font-size: 190%;\n font-weight: bold;\n color: #0080FF;\n}\n\n#main table {\n width: 100%;\n margin:0 0 10px;\n}\n\n#main table tr td, #main table tr th {\n border-bottom: 1px solid #ccc;\n padding: 6px;\n}\n\n#main table tr th {\n background: #efefef;\n color: #888;\n font-size: 80%;\n text-transform:uppercase;\n}\n\n#main table tr td.no-data {\n text-align: center;\n padding: 40px 0;\n color: #999;\n font-style: italic;\n font-size: 130%;\n}\n\n#main a {\n color: #111;\n}\n\n#main p {\n margin: 5px 0;\n}\n\n#main p.intro {\n margin-bottom: 15px;\n font-size: 85%;\n color: #999;\n margin-top: 0;\n line-height: 1.3;\n}\n\n#main h1.wi {\n margin-bottom: 5px;\n}\n\n#main p.sub {\n font-size: 95%;\n color: #999;\n}\n\n.experiment {\n background:#fff;\n border: 1px solid #eee;\n border-bottom:none;\n margin:30px 0;\n}\n\n.experiment_with_goal {\n margin: -32px 0 30px 0;\n}\n\n.experiment .experiment-header {\n background: #f4f4f4;\n background: -webkit-gradient(linear, left top, left bottom,\n color-stop(0%,#f4f4f4),\n color-stop(100%,#e0e0e0));\n background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%);\n background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%);\n border-top:1px solid #fff;\n overflow:hidden;\n padding:0 10px;\n}\n\n.experiment h2 {\n color:#888;\n margin: 12px 0 12px 0;\n font-size: 1em;\n font-weight:bold;\n float:left;\n text-shadow:0 1px 0 rgba(255,255,255,0.8);\n}\n\n.experiment h2 .goal {\n font-style: italic;\n}\n\n.experiment h2 .version {\n font-style:italic;\n font-size:0.8em;\n color:#bbb;\n font-weight:normal;\n}\n\n.experiment table em{\n font-style:italic;\n font-size:0.9em;\n color:#bbb;\n}\n\n.experiment table .totals td {\n background: #eee;\n font-weight: bold;\n}\n\n#footer {\n padding: 10px 5%;\n color: #999;\n font-size: 85%;\n line-height: 1.5;\n padding-top: 10px;\n}\n\n#footer p a {\n color: #999;\n}\n\n.inline-controls {\n float:right;\n}\n\n.inline-controls small {\n color: #888;\n font-size: 11px;\n}\n\n.inline-controls form {\n display: inline-block;\n font-size: 10px;\n line-height: 38px;\n}\n\n.inline-controls input {\n margin-left: 10px;\n}\n\n.worse, .better {\n color: #773F3F;\n font-size: 10px;\n font-weight:bold;\n}\n\n.better {\n color: #408C48;\n}\n\n.experiment a.button, .experiment button, .experiment input[type=\"submit\"] {\n padding: 4px 10px;\n overflow: hidden;\n background: #d8dae0;\n -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5);\n -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5);\n box-shadow: 0 1px 0 rgba(0,0,0,0.5);\n border:none;\n -moz-border-radius: 30px;\n -webkit-border-radius:30px;\n border-radius: 30px;\n color:#2e3035;\n cursor: pointer;\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n text-decoration: none;\n text-shadow:0 1px 0 rgba(255,255,255,0.8);\n -moz-user-select: none;\n -webkit-user-select:none;\n user-select: none;\n white-space: nowrap;\n}\na.button:hover, button:hover, input[type=\"submit\"]:hover,\na.button:focus, button:focus, input[type=\"submit\"]:focus{\n background:#bbbfc7;\n}\na.button:active, button:active, input[type=\"submit\"]:active{\n -moz-box-shadow: inset 0 0 4px #484d57;\n -webkit-box-shadow:inset 0 0 4px #484d57;\n box-shadow: inset 0 0 4px #484d57;\n position:relative;\n top:1px;\n}\n\na.button.red, button.red, input[type=\"submit\"].red,\na.button.green, button.green, input[type=\"submit\"].green {\n color:#fff;\n text-shadow:0 1px 0 rgba(0,0,0,0.4);\n}\n\na.button.red, button.red, input[type=\"submit\"].red {\n background:#a56d6d;\n}\na.button.red:hover, button.red:hover, input[type=\"submit\"].red:hover,\na.button.red:focus, button.red:focus, input[type=\"submit\"].red:focus {\n background:#895C5C;\n}\na.button.green, button.green, input[type=\"submit\"].green {\n background:#8daa92;\n}\na.button.green:hover, button.green:hover, input[type=\"submit\"].green:hover,\na.button.green:focus, button.green:focus, input[type=\"submit\"].green:focus {\n background:#768E7A;\n}\n\n.dashboard-controls input, .dashboard-controls select {\n padding: 10px;\n}\n\n.dashboard-controls-bottom {\n margin-top: 10px;\n}\n\n.pagination {\n text-align: center;\n font-size: 15px;\n}\n\n.pagination a, .paginaton span {\n display: inline-block;\n padding: 5px;\n}\n\n.divider {\n display: inline-block;\n margin-left: 10px;\n}\n\n no more massive clickable area on the reset button\n @@ -35,6 +35,7 @@ h2{\n }\n \n .reset{\n+ display:inline-block;\n font-size:10px;\n line-height:38px;\n }\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"no more massive clickable area on the reset button"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".css"},"lang":{"kind":"string","value":"css"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676473,"cells":{"id":{"kind":"string","value":"10072123"},"text":{"kind":"string","value":" .jscsrc\n {\n \"requireCurlyBraces\": [\n \"if\",\n \"else\",\n \"for\",\n \"while\",\n \"do\",\n \"try\",\n \"catch\"\n ],\n \"requireSpaceAfterKeywords\": [\n \"if\",\n \"else\",\n \"for\",\n \"while\",\n \"do\",\n \"switch\",\n \"case\",\n \"return\",\n \"try\",\n \"catch\",\n \"typeof\"\n ],\n \"requireSpaceBeforeBinaryOperators\": [\n \"=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\", \"<<=\", \">>=\", \">>>=\",\n \"&=\", \"|=\", \"^=\", \"+=\",\n\n \"+\", \"-\", \"*\", \"/\", \"%\", \"<<\", \">>\", \">>>\", \"&\",\n \"|\", \"^\", \"&&\", \"||\", \"===\", \"==\", \">=\",\n \"<=\", \"<\", \">\", \"!=\", \"!==\"\n ],\n \"requireSpaceBeforeBlockStatements\": true,\n \"requireParenthesesAroundIIFE\": true,\n \"requireSpacesInConditionalExpression\": true,\n \"disallowSpacesInNamedFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpacesInFunctionDeclaration\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"requireBlocksOnNewline\": 1,\n \"disallowEmptyBlocks\": true,\n \"disallowSpacesInsideArrayBrackets\": true,\n \"disallowSpacesInsideParentheses\": true,\n \"disallowSpaceAfterObjectKeys\": true,\n \"requireCommaBeforeLineBreak\": true,\n \"disallowSpaceAfterPrefixUnaryOperators\": true,\n \"disallowSpaceBeforePostfixUnaryOperators\": true,\n \"disallowSpaceBeforeBinaryOperators\": [\n \",\"\n ],\n \"requireSpaceBeforeBinaryOperators\": true,\n \"requireSpaceAfterBinaryOperators\": true,\n \"disallowKeywords\": [ \"with\" ],\n \"disallowMultipleLineBreaks\": true,\n \"validateLineBreaks\": \"LF\",\n \"validateQuoteMarks\": true,\n \"validateIndentation\": 2,\n \"disallowMixedSpacesAndTabs\": true,\n \"disallowTrailingWhitespace\": true,\n \"disallowTrailingComma\": true,\n \"disallowKeywordsOnNewLine\": [ \"else\" ],\n \"requireLineFeedAtFileEnd\": true,\n \"requireCapitalizedConstructors\": true,\n \"requireDotNotation\": true,\n \"disallowYodaConditions\": true,\n \"requireSpacesInFunctionExpression\": {\n \"beforeOpeningCurlyBrace\": true\n },\n \"disallowSpacesInFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpaceAfterObjectKeys\": true,\n \"requireSpaceBeforeObjectValues\": true\n}\n\n chore(.jsscrc) Updated jssc to use rules as for angularjs\n\n @@ -1,75 +1,40 @@\n {\n- \"requireCurlyBraces\": [\n- \"if\",\n- \"else\",\n- \"for\",\n- \"while\",\n- \"do\",\n- \"try\",\n- \"catch\"\n- ],\n- \"requireSpaceAfterKeywords\": [\n- \"if\",\n- \"else\",\n- \"for\",\n- \"while\",\n- \"do\",\n- \"switch\",\n- \"case\",\n- \"return\",\n- \"try\",\n- \"catch\",\n- \"typeof\"\n- ],\n- \"requireSpaceBeforeBinaryOperators\": [\n- \"=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\", \"<<=\", \">>=\", \">>>=\",\n- \"&=\", \"|=\", \"^=\", \"+=\",\n-\n- \"+\", \"-\", \"*\", \"/\", \"%\", \"<<\", \">>\", \">>>\", \"&\",\n- \"|\", \"^\", \"&&\", \"||\", \"===\", \"==\", \">=\",\n- \"<=\", \"<\", \">\", \"!=\", \"!==\"\n- ],\n- \"requireSpaceBeforeBlockStatements\": true,\n- \"requireParenthesesAroundIIFE\": true,\n- \"requireSpacesInConditionalExpression\": true,\n- \"disallowSpacesInNamedFunctionExpression\": {\n+ \"disallowKeywords\": [\"with\"],\n+ \"disallowMixedSpacesAndTabs\": true,\n+ \"disallowMultipleLineStrings\": true,\n+ \"disallowNewlineBeforeBlockStatements\": true,\n+ \"disallowSpaceAfterObjectKeys\": true,\n+ \"disallowSpaceAfterPrefixUnaryOperators\": [\"++\", \"--\", \"+\", \"-\", \"~\", \"!\"],\n+ \"disallowSpaceBeforeBinaryOperators\": [\",\"],\n+ \"disallowSpaceBeforePostfixUnaryOperators\": [\"++\", \"--\"],\n+ \"disallowSpacesInAnonymousFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpacesInFunctionDeclaration\": {\n \"beforeOpeningRoundBrace\": true\n },\n- \"requireBlocksOnNewline\": 1,\n- \"disallowEmptyBlocks\": true,\n+ \"disallowSpacesInNamedFunctionExpression\": {\n+ \"beforeOpeningRoundBrace\": true\n+ },\n \"disallowSpacesInsideArrayBrackets\": true,\n \"disallowSpacesInsideParentheses\": true,\n- \"disallowSpaceAfterObjectKeys\": true,\n- \"requireCommaBeforeLineBreak\": true,\n- \"disallowSpaceAfterPrefixUnaryOperators\": true,\n- \"disallowSpaceBeforePostfixUnaryOperators\": true,\n- \"disallowSpaceBeforeBinaryOperators\": [\n- \",\"\n- ],\n- \"requireSpaceBeforeBinaryOperators\": true,\n- \"requireSpaceAfterBinaryOperators\": true,\n- \"disallowKeywords\": [ \"with\" ],\n- \"disallowMultipleLineBreaks\": true,\n- \"validateLineBreaks\": \"LF\",\n- \"validateQuoteMarks\": true,\n- \"validateIndentation\": 2,\n- \"disallowMixedSpacesAndTabs\": true,\n- \"disallowTrailingWhitespace\": true,\n \"disallowTrailingComma\": true,\n- \"disallowKeywordsOnNewLine\": [ \"else\" ],\n+ \"disallowTrailingWhitespace\": true,\n+ \"requireCommaBeforeLineBreak\": true,\n \"requireLineFeedAtFileEnd\": true,\n- \"requireCapitalizedConstructors\": true,\n- \"requireDotNotation\": true,\n- \"disallowYodaConditions\": true,\n- \"requireSpacesInFunctionExpression\": {\n- \"beforeOpeningCurlyBrace\": true\n+ \"requireSpaceAfterBinaryOperators\": [\"?\", \":\", \"+\", \"-\", \"/\", \"*\", \"%\", \"==\", \"===\", \"!=\", \"!==\", \">\", \">=\", \"<\", \"<=\", \"&&\", \"||\"],\n+ \"requireSpaceBeforeBinaryOperators\": [\"?\", \":\", \"+\", \"-\", \"/\", \"*\", \"%\", \"==\", \"===\", \"!=\", \"!==\", \">\", \">=\", \"<\", \"<=\", \"&&\", \"||\"],\n+ \"requireSpaceAfterKeywords\": [\"if\", \"else\", \"for\", \"while\", \"do\", \"switch\", \"return\", \"try\", \"catch\"],\n+ \"requireSpaceBeforeBlockStatements\": true,\n+ \"requireSpacesInConditionalExpression\": {\n+ \"afterTest\": true,\n+ \"beforeConsequent\": true,\n+ \"afterConsequent\": true,\n+ \"beforeAlternate\": true\n },\n- \"disallowSpacesInFunctionExpression\": {\n- \"beforeOpeningRoundBrace\": true\n+ \"requireSpacesInFunction\": {\n+ \"beforeOpeningCurlyBrace\": true\n },\n- \"disallowSpaceAfterObjectKeys\": true,\n- \"requireSpaceBeforeObjectValues\": true\n-}\n\\ No newline at end of file\n+ \"validateLineBreaks\": \"LF\",\n+ \"validateParameterSeparator\": \", \"\n+}\n"},"addition_count":{"kind":"number","value":28,"string":"28"},"commit_subject":{"kind":"string","value":"chore(.jsscrc) Updated jssc to use rules as for angularjs"},"deletion_count":{"kind":"number","value":63,"string":"63"},"file_extension":{"kind":"string","value":""},"lang":{"kind":"string","value":"jscsrc"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676474,"cells":{"id":{"kind":"string","value":"10072124"},"text":{"kind":"string","value":" .jscsrc\n {\n \"requireCurlyBraces\": [\n \"if\",\n \"else\",\n \"for\",\n \"while\",\n \"do\",\n \"try\",\n \"catch\"\n ],\n \"requireSpaceAfterKeywords\": [\n \"if\",\n \"else\",\n \"for\",\n \"while\",\n \"do\",\n \"switch\",\n \"case\",\n \"return\",\n \"try\",\n \"catch\",\n \"typeof\"\n ],\n \"requireSpaceBeforeBinaryOperators\": [\n \"=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\", \"<<=\", \">>=\", \">>>=\",\n \"&=\", \"|=\", \"^=\", \"+=\",\n\n \"+\", \"-\", \"*\", \"/\", \"%\", \"<<\", \">>\", \">>>\", \"&\",\n \"|\", \"^\", \"&&\", \"||\", \"===\", \"==\", \">=\",\n \"<=\", \"<\", \">\", \"!=\", \"!==\"\n ],\n \"requireSpaceBeforeBlockStatements\": true,\n \"requireParenthesesAroundIIFE\": true,\n \"requireSpacesInConditionalExpression\": true,\n \"disallowSpacesInNamedFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpacesInFunctionDeclaration\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"requireBlocksOnNewline\": 1,\n \"disallowEmptyBlocks\": true,\n \"disallowSpacesInsideArrayBrackets\": true,\n \"disallowSpacesInsideParentheses\": true,\n \"disallowSpaceAfterObjectKeys\": true,\n \"requireCommaBeforeLineBreak\": true,\n \"disallowSpaceAfterPrefixUnaryOperators\": true,\n \"disallowSpaceBeforePostfixUnaryOperators\": true,\n \"disallowSpaceBeforeBinaryOperators\": [\n \",\"\n ],\n \"requireSpaceBeforeBinaryOperators\": true,\n \"requireSpaceAfterBinaryOperators\": true,\n \"disallowKeywords\": [ \"with\" ],\n \"disallowMultipleLineBreaks\": true,\n \"validateLineBreaks\": \"LF\",\n \"validateQuoteMarks\": true,\n \"validateIndentation\": 2,\n \"disallowMixedSpacesAndTabs\": true,\n \"disallowTrailingWhitespace\": true,\n \"disallowTrailingComma\": true,\n \"disallowKeywordsOnNewLine\": [ \"else\" ],\n \"requireLineFeedAtFileEnd\": true,\n \"requireCapitalizedConstructors\": true,\n \"requireDotNotation\": true,\n \"disallowYodaConditions\": true,\n \"requireSpacesInFunctionExpression\": {\n \"beforeOpeningCurlyBrace\": true\n },\n \"disallowSpacesInFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpaceAfterObjectKeys\": true,\n \"requireSpaceBeforeObjectValues\": true\n}\n\n chore(.jsscrc) Updated jssc to use rules as for angularjs\n\n @@ -1,75 +1,40 @@\n {\n- \"requireCurlyBraces\": [\n- \"if\",\n- \"else\",\n- \"for\",\n- \"while\",\n- \"do\",\n- \"try\",\n- \"catch\"\n- ],\n- \"requireSpaceAfterKeywords\": [\n- \"if\",\n- \"else\",\n- \"for\",\n- \"while\",\n- \"do\",\n- \"switch\",\n- \"case\",\n- \"return\",\n- \"try\",\n- \"catch\",\n- \"typeof\"\n- ],\n- \"requireSpaceBeforeBinaryOperators\": [\n- \"=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\", \"<<=\", \">>=\", \">>>=\",\n- \"&=\", \"|=\", \"^=\", \"+=\",\n-\n- \"+\", \"-\", \"*\", \"/\", \"%\", \"<<\", \">>\", \">>>\", \"&\",\n- \"|\", \"^\", \"&&\", \"||\", \"===\", \"==\", \">=\",\n- \"<=\", \"<\", \">\", \"!=\", \"!==\"\n- ],\n- \"requireSpaceBeforeBlockStatements\": true,\n- \"requireParenthesesAroundIIFE\": true,\n- \"requireSpacesInConditionalExpression\": true,\n- \"disallowSpacesInNamedFunctionExpression\": {\n+ \"disallowKeywords\": [\"with\"],\n+ \"disallowMixedSpacesAndTabs\": true,\n+ \"disallowMultipleLineStrings\": true,\n+ \"disallowNewlineBeforeBlockStatements\": true,\n+ \"disallowSpaceAfterObjectKeys\": true,\n+ \"disallowSpaceAfterPrefixUnaryOperators\": [\"++\", \"--\", \"+\", \"-\", \"~\", \"!\"],\n+ \"disallowSpaceBeforeBinaryOperators\": [\",\"],\n+ \"disallowSpaceBeforePostfixUnaryOperators\": [\"++\", \"--\"],\n+ \"disallowSpacesInAnonymousFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpacesInFunctionDeclaration\": {\n \"beforeOpeningRoundBrace\": true\n },\n- \"requireBlocksOnNewline\": 1,\n- \"disallowEmptyBlocks\": true,\n+ \"disallowSpacesInNamedFunctionExpression\": {\n+ \"beforeOpeningRoundBrace\": true\n+ },\n \"disallowSpacesInsideArrayBrackets\": true,\n \"disallowSpacesInsideParentheses\": true,\n- \"disallowSpaceAfterObjectKeys\": true,\n- \"requireCommaBeforeLineBreak\": true,\n- \"disallowSpaceAfterPrefixUnaryOperators\": true,\n- \"disallowSpaceBeforePostfixUnaryOperators\": true,\n- \"disallowSpaceBeforeBinaryOperators\": [\n- \",\"\n- ],\n- \"requireSpaceBeforeBinaryOperators\": true,\n- \"requireSpaceAfterBinaryOperators\": true,\n- \"disallowKeywords\": [ \"with\" ],\n- \"disallowMultipleLineBreaks\": true,\n- \"validateLineBreaks\": \"LF\",\n- \"validateQuoteMarks\": true,\n- \"validateIndentation\": 2,\n- \"disallowMixedSpacesAndTabs\": true,\n- \"disallowTrailingWhitespace\": true,\n \"disallowTrailingComma\": true,\n- \"disallowKeywordsOnNewLine\": [ \"else\" ],\n+ \"disallowTrailingWhitespace\": true,\n+ \"requireCommaBeforeLineBreak\": true,\n \"requireLineFeedAtFileEnd\": true,\n- \"requireCapitalizedConstructors\": true,\n- \"requireDotNotation\": true,\n- \"disallowYodaConditions\": true,\n- \"requireSpacesInFunctionExpression\": {\n- \"beforeOpeningCurlyBrace\": true\n+ \"requireSpaceAfterBinaryOperators\": [\"?\", \":\", \"+\", \"-\", \"/\", \"*\", \"%\", \"==\", \"===\", \"!=\", \"!==\", \">\", \">=\", \"<\", \"<=\", \"&&\", \"||\"],\n+ \"requireSpaceBeforeBinaryOperators\": [\"?\", \":\", \"+\", \"-\", \"/\", \"*\", \"%\", \"==\", \"===\", \"!=\", \"!==\", \">\", \">=\", \"<\", \"<=\", \"&&\", \"||\"],\n+ \"requireSpaceAfterKeywords\": [\"if\", \"else\", \"for\", \"while\", \"do\", \"switch\", \"return\", \"try\", \"catch\"],\n+ \"requireSpaceBeforeBlockStatements\": true,\n+ \"requireSpacesInConditionalExpression\": {\n+ \"afterTest\": true,\n+ \"beforeConsequent\": true,\n+ \"afterConsequent\": true,\n+ \"beforeAlternate\": true\n },\n- \"disallowSpacesInFunctionExpression\": {\n- \"beforeOpeningRoundBrace\": true\n+ \"requireSpacesInFunction\": {\n+ \"beforeOpeningCurlyBrace\": true\n },\n- \"disallowSpaceAfterObjectKeys\": true,\n- \"requireSpaceBeforeObjectValues\": true\n-}\n\\ No newline at end of file\n+ \"validateLineBreaks\": \"LF\",\n+ \"validateParameterSeparator\": \", \"\n+}\n"},"addition_count":{"kind":"number","value":28,"string":"28"},"commit_subject":{"kind":"string","value":"chore(.jsscrc) Updated jssc to use rules as for angularjs"},"deletion_count":{"kind":"number","value":63,"string":"63"},"file_extension":{"kind":"string","value":""},"lang":{"kind":"string","value":"jscsrc"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676475,"cells":{"id":{"kind":"string","value":"10072125"},"text":{"kind":"string","value":" .jscsrc\n {\n \"requireCurlyBraces\": [\n \"if\",\n \"else\",\n \"for\",\n \"while\",\n \"do\",\n \"try\",\n \"catch\"\n ],\n \"requireSpaceAfterKeywords\": [\n \"if\",\n \"else\",\n \"for\",\n \"while\",\n \"do\",\n \"switch\",\n \"case\",\n \"return\",\n \"try\",\n \"catch\",\n \"typeof\"\n ],\n \"requireSpaceBeforeBinaryOperators\": [\n \"=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\", \"<<=\", \">>=\", \">>>=\",\n \"&=\", \"|=\", \"^=\", \"+=\",\n\n \"+\", \"-\", \"*\", \"/\", \"%\", \"<<\", \">>\", \">>>\", \"&\",\n \"|\", \"^\", \"&&\", \"||\", \"===\", \"==\", \">=\",\n \"<=\", \"<\", \">\", \"!=\", \"!==\"\n ],\n \"requireSpaceBeforeBlockStatements\": true,\n \"requireParenthesesAroundIIFE\": true,\n \"requireSpacesInConditionalExpression\": true,\n \"disallowSpacesInNamedFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpacesInFunctionDeclaration\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"requireBlocksOnNewline\": 1,\n \"disallowEmptyBlocks\": true,\n \"disallowSpacesInsideArrayBrackets\": true,\n \"disallowSpacesInsideParentheses\": true,\n \"disallowSpaceAfterObjectKeys\": true,\n \"requireCommaBeforeLineBreak\": true,\n \"disallowSpaceAfterPrefixUnaryOperators\": true,\n \"disallowSpaceBeforePostfixUnaryOperators\": true,\n \"disallowSpaceBeforeBinaryOperators\": [\n \",\"\n ],\n \"requireSpaceBeforeBinaryOperators\": true,\n \"requireSpaceAfterBinaryOperators\": true,\n \"disallowKeywords\": [ \"with\" ],\n \"disallowMultipleLineBreaks\": true,\n \"validateLineBreaks\": \"LF\",\n \"validateQuoteMarks\": true,\n \"validateIndentation\": 2,\n \"disallowMixedSpacesAndTabs\": true,\n \"disallowTrailingWhitespace\": true,\n \"disallowTrailingComma\": true,\n \"disallowKeywordsOnNewLine\": [ \"else\" ],\n \"requireLineFeedAtFileEnd\": true,\n \"requireCapitalizedConstructors\": true,\n \"requireDotNotation\": true,\n \"disallowYodaConditions\": true,\n \"requireSpacesInFunctionExpression\": {\n \"beforeOpeningCurlyBrace\": true\n },\n \"disallowSpacesInFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpaceAfterObjectKeys\": true,\n \"requireSpaceBeforeObjectValues\": true\n}\n\n chore(.jsscrc) Updated jssc to use rules as for angularjs\n\n @@ -1,75 +1,40 @@\n {\n- \"requireCurlyBraces\": [\n- \"if\",\n- \"else\",\n- \"for\",\n- \"while\",\n- \"do\",\n- \"try\",\n- \"catch\"\n- ],\n- \"requireSpaceAfterKeywords\": [\n- \"if\",\n- \"else\",\n- \"for\",\n- \"while\",\n- \"do\",\n- \"switch\",\n- \"case\",\n- \"return\",\n- \"try\",\n- \"catch\",\n- \"typeof\"\n- ],\n- \"requireSpaceBeforeBinaryOperators\": [\n- \"=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\", \"<<=\", \">>=\", \">>>=\",\n- \"&=\", \"|=\", \"^=\", \"+=\",\n-\n- \"+\", \"-\", \"*\", \"/\", \"%\", \"<<\", \">>\", \">>>\", \"&\",\n- \"|\", \"^\", \"&&\", \"||\", \"===\", \"==\", \">=\",\n- \"<=\", \"<\", \">\", \"!=\", \"!==\"\n- ],\n- \"requireSpaceBeforeBlockStatements\": true,\n- \"requireParenthesesAroundIIFE\": true,\n- \"requireSpacesInConditionalExpression\": true,\n- \"disallowSpacesInNamedFunctionExpression\": {\n+ \"disallowKeywords\": [\"with\"],\n+ \"disallowMixedSpacesAndTabs\": true,\n+ \"disallowMultipleLineStrings\": true,\n+ \"disallowNewlineBeforeBlockStatements\": true,\n+ \"disallowSpaceAfterObjectKeys\": true,\n+ \"disallowSpaceAfterPrefixUnaryOperators\": [\"++\", \"--\", \"+\", \"-\", \"~\", \"!\"],\n+ \"disallowSpaceBeforeBinaryOperators\": [\",\"],\n+ \"disallowSpaceBeforePostfixUnaryOperators\": [\"++\", \"--\"],\n+ \"disallowSpacesInAnonymousFunctionExpression\": {\n \"beforeOpeningRoundBrace\": true\n },\n \"disallowSpacesInFunctionDeclaration\": {\n \"beforeOpeningRoundBrace\": true\n },\n- \"requireBlocksOnNewline\": 1,\n- \"disallowEmptyBlocks\": true,\n+ \"disallowSpacesInNamedFunctionExpression\": {\n+ \"beforeOpeningRoundBrace\": true\n+ },\n \"disallowSpacesInsideArrayBrackets\": true,\n \"disallowSpacesInsideParentheses\": true,\n- \"disallowSpaceAfterObjectKeys\": true,\n- \"requireCommaBeforeLineBreak\": true,\n- \"disallowSpaceAfterPrefixUnaryOperators\": true,\n- \"disallowSpaceBeforePostfixUnaryOperators\": true,\n- \"disallowSpaceBeforeBinaryOperators\": [\n- \",\"\n- ],\n- \"requireSpaceBeforeBinaryOperators\": true,\n- \"requireSpaceAfterBinaryOperators\": true,\n- \"disallowKeywords\": [ \"with\" ],\n- \"disallowMultipleLineBreaks\": true,\n- \"validateLineBreaks\": \"LF\",\n- \"validateQuoteMarks\": true,\n- \"validateIndentation\": 2,\n- \"disallowMixedSpacesAndTabs\": true,\n- \"disallowTrailingWhitespace\": true,\n \"disallowTrailingComma\": true,\n- \"disallowKeywordsOnNewLine\": [ \"else\" ],\n+ \"disallowTrailingWhitespace\": true,\n+ \"requireCommaBeforeLineBreak\": true,\n \"requireLineFeedAtFileEnd\": true,\n- \"requireCapitalizedConstructors\": true,\n- \"requireDotNotation\": true,\n- \"disallowYodaConditions\": true,\n- \"requireSpacesInFunctionExpression\": {\n- \"beforeOpeningCurlyBrace\": true\n+ \"requireSpaceAfterBinaryOperators\": [\"?\", \":\", \"+\", \"-\", \"/\", \"*\", \"%\", \"==\", \"===\", \"!=\", \"!==\", \">\", \">=\", \"<\", \"<=\", \"&&\", \"||\"],\n+ \"requireSpaceBeforeBinaryOperators\": [\"?\", \":\", \"+\", \"-\", \"/\", \"*\", \"%\", \"==\", \"===\", \"!=\", \"!==\", \">\", \">=\", \"<\", \"<=\", \"&&\", \"||\"],\n+ \"requireSpaceAfterKeywords\": [\"if\", \"else\", \"for\", \"while\", \"do\", \"switch\", \"return\", \"try\", \"catch\"],\n+ \"requireSpaceBeforeBlockStatements\": true,\n+ \"requireSpacesInConditionalExpression\": {\n+ \"afterTest\": true,\n+ \"beforeConsequent\": true,\n+ \"afterConsequent\": true,\n+ \"beforeAlternate\": true\n },\n- \"disallowSpacesInFunctionExpression\": {\n- \"beforeOpeningRoundBrace\": true\n+ \"requireSpacesInFunction\": {\n+ \"beforeOpeningCurlyBrace\": true\n },\n- \"disallowSpaceAfterObjectKeys\": true,\n- \"requireSpaceBeforeObjectValues\": true\n-}\n\\ No newline at end of file\n+ \"validateLineBreaks\": \"LF\",\n+ \"validateParameterSeparator\": \", \"\n+}\n"},"addition_count":{"kind":"number","value":28,"string":"28"},"commit_subject":{"kind":"string","value":"chore(.jsscrc) Updated jssc to use rules as for angularjs"},"deletion_count":{"kind":"number","value":63,"string":"63"},"file_extension":{"kind":"string","value":""},"lang":{"kind":"string","value":"jscsrc"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676476,"cells":{"id":{"kind":"string","value":"10072126"},"text":{"kind":"string","value":" buildout.cfg\n [buildout]\nparts = django\nfind-links = http://bitbucket.org/ubernostrum/django-registration/downloads/django-registration-0.8-alpha-1.tar.gz\nunzip = true\neggs = pkginfo\n django-registration==0.8-alpha-1\n\n[django]\nrecipe = djangorecipe\nversion = 1.1.1\nsettings = settings\neggs = ${buildout:eggs}\ntest = djangopypi\nproject = chishop\nwsgi = true\n\n Use development settings by default\n\n @@ -8,7 +8,7 @@ eggs = pkginfo\n [django]\n recipe = djangorecipe\n version = 1.1.1\n-settings = settings\n+settings = development\n eggs = ${buildout:eggs}\n test = djangopypi\n project = chishop\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"Use development settings by default"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".cfg"},"lang":{"kind":"string","value":"cfg"},"license":{"kind":"string","value":"bsd-3-clause"},"repo_name":{"kind":"string","value":"ask/chishop"}}},{"rowIdx":10676477,"cells":{"id":{"kind":"string","value":"10072127"},"text":{"kind":"string","value":" extract-abbreviation.ts\n ADDFILE\n Unit tests and docs for abbreviation extractor\n\n @@ -0,0 +1,126 @@\n+import { deepStrictEqual, strictEqual, ok } from 'assert';\n+import extractAbbreviation, { ExtractOptions, ExtractedAbbreviation } from '../src/extract-abbreviation';\n+import isAtHTMLTag from '../src/extract-abbreviation/is-html';\n+import scanner from '../src/extract-abbreviation/reader';\n+import { consumeQuoted } from '../src/extract-abbreviation/quotes';\n+\n+function extract(abbr: string, options?: Partial) {\n+ let caretPos: number | undefined = abbr.indexOf('|');\n+ if (caretPos !== -1) {\n+ abbr = abbr.slice(0, caretPos) + abbr.slice(caretPos + 1);\n+ } else {\n+ caretPos = void 0;\n+ }\n+\n+ return extractAbbreviation(abbr, caretPos, options);\n+}\n+\n+function result(abbreviation: string, location: number, start = location): ExtractedAbbreviation {\n+ return {\n+ abbreviation,\n+ location,\n+ start: start != null ? start : location,\n+ end: location + abbreviation.length\n+ };\n+}\n+\n+describe('Extract abbreviation', () => {\n+ it('basic', () => {\n+ deepStrictEqual(extract('.bar'), result('.bar', 0));\n+ deepStrictEqual(extract('.foo .bar'), result('.bar', 5));\n+ deepStrictEqual(extract('.foo @bar'), result('@bar', 5));\n+ deepStrictEqual(extract('.foo img/'), result('img/', 5));\n+ deepStrictEqual(extract('текстdiv'), result('div', 5));\n+ deepStrictEqual(extract('foo div[foo=\"текст\" bar=текст2]'), result('div[foo=\"текст\" bar=текст2]', 4));\n+ });\n+\n+ it('abbreviation with operators', () => {\n+ deepStrictEqual(extract('a foo+bar.baz'), result('foo+bar.baz', 2));\n+ deepStrictEqual(extract('a foo>bar+baz*3'), result('foo>bar+baz*3', 2));\n+ });\n+\n+ it('abbreviation with attributes', () => {\n+ deepStrictEqual(extract('a foo[bar|]'), result('foo[bar]', 2));\n+ deepStrictEqual(extract('a foo[bar=\"baz\" a b]'), result('foo[bar=\"baz\" a b]', 2));\n+ deepStrictEqual(extract('foo bar[a|] baz'), result('bar[a]', 4));\n+ });\n+\n+ it('tag test', () => {\n+ deepStrictEqual(extract('bar[a b=\"c\"]>baz'), result('bar[a b=\"c\"]>baz', 5));\n+ deepStrictEqual(extract('foo>bar'), result('foo>bar', 0));\n+ deepStrictEqual(extract('bar'), result('bar', 5));\n+ deepStrictEqual(extract('bar[a=\"d\" b=\"c\"]>baz'), result('bar[a=\"d\" b=\"c\"]>baz', 5));\n+ });\n+\n+ it('stylesheet abbreviation', () => {\n+ deepStrictEqual(extract('foo{bar|}'), result('foo{bar}', 0));\n+ deepStrictEqual(extract('foo{bar|}', { type: 'stylesheet' }), result('bar', 4));\n+ });\n+\n+ it('prefixed extract', () => {\n+ deepStrictEqual(extract('bar[a b=\"c\"]>baz'), result('bar[a b=\"c\"]>baz', 5));\n+ deepStrictEqual(extract('bar[a b=\"c\"]>baz', { prefix: '<' }), result('foo>bar[a b=\"c\"]>baz', 1, 0));\n+ deepStrictEqual(extract('bar[a b=\"<\"]>baz', { prefix: '<' }), result('foo>bar[a b=\"<\"]>baz', 1, 0));\n+ deepStrictEqual(extract('bar{<}>baz', { prefix: '<' }), result('foo>bar{<}>baz', 1, 0));\n+\n+ // Multiple prefix characters\n+ deepStrictEqual(extract('foo>>>bar[a b=\"c\"]>baz', { prefix: '>>>' }), result('bar[a b=\"c\"]>baz', 6, 3));\n+\n+ // Absent prefix\n+ strictEqual(extract('bar[a b=\"c\"]>baz', { prefix: '&&' }), void 0);\n+ });\n+\n+ it('HTML test', () => {\n+ const html = (str: string) => isAtHTMLTag(scanner(str));\n+\n+ // simple tag\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+\n+ // tag with attributes\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html(''));\n+\n+ // invalid tags\n+ ok(!html('div>'));\n+ ok(!html(''));\n+ ok(!html('
    '));\n+ ok(!html('
    '));\n+ ok(!html('[a=b c=d]>'));\n+ ok(!html('div[a=b c=d]>'));\n+ });\n+\n+ it('consume quotes', () => {\n+ let s = scanner(' \"foo\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 1);\n+\n+ s = scanner('\"foo\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 0);\n+\n+ s = scanner('\"\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 0);\n+\n+ s = scanner('\"a\\\\\\\"b\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 0);\n+\n+ // don’t eat anything\n+ s = scanner('foo');\n+ ok(!consumeQuoted(s));\n+ strictEqual(s.pos, 3);\n+ });\n+});\n"},"addition_count":{"kind":"number","value":126,"string":"126"},"commit_subject":{"kind":"string","value":"Unit tests and docs for abbreviation extractor"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676478,"cells":{"id":{"kind":"string","value":"10072128"},"text":{"kind":"string","value":" extract-abbreviation.ts\n ADDFILE\n Unit tests and docs for abbreviation extractor\n\n @@ -0,0 +1,126 @@\n+import { deepStrictEqual, strictEqual, ok } from 'assert';\n+import extractAbbreviation, { ExtractOptions, ExtractedAbbreviation } from '../src/extract-abbreviation';\n+import isAtHTMLTag from '../src/extract-abbreviation/is-html';\n+import scanner from '../src/extract-abbreviation/reader';\n+import { consumeQuoted } from '../src/extract-abbreviation/quotes';\n+\n+function extract(abbr: string, options?: Partial) {\n+ let caretPos: number | undefined = abbr.indexOf('|');\n+ if (caretPos !== -1) {\n+ abbr = abbr.slice(0, caretPos) + abbr.slice(caretPos + 1);\n+ } else {\n+ caretPos = void 0;\n+ }\n+\n+ return extractAbbreviation(abbr, caretPos, options);\n+}\n+\n+function result(abbreviation: string, location: number, start = location): ExtractedAbbreviation {\n+ return {\n+ abbreviation,\n+ location,\n+ start: start != null ? start : location,\n+ end: location + abbreviation.length\n+ };\n+}\n+\n+describe('Extract abbreviation', () => {\n+ it('basic', () => {\n+ deepStrictEqual(extract('.bar'), result('.bar', 0));\n+ deepStrictEqual(extract('.foo .bar'), result('.bar', 5));\n+ deepStrictEqual(extract('.foo @bar'), result('@bar', 5));\n+ deepStrictEqual(extract('.foo img/'), result('img/', 5));\n+ deepStrictEqual(extract('текстdiv'), result('div', 5));\n+ deepStrictEqual(extract('foo div[foo=\"текст\" bar=текст2]'), result('div[foo=\"текст\" bar=текст2]', 4));\n+ });\n+\n+ it('abbreviation with operators', () => {\n+ deepStrictEqual(extract('a foo+bar.baz'), result('foo+bar.baz', 2));\n+ deepStrictEqual(extract('a foo>bar+baz*3'), result('foo>bar+baz*3', 2));\n+ });\n+\n+ it('abbreviation with attributes', () => {\n+ deepStrictEqual(extract('a foo[bar|]'), result('foo[bar]', 2));\n+ deepStrictEqual(extract('a foo[bar=\"baz\" a b]'), result('foo[bar=\"baz\" a b]', 2));\n+ deepStrictEqual(extract('foo bar[a|] baz'), result('bar[a]', 4));\n+ });\n+\n+ it('tag test', () => {\n+ deepStrictEqual(extract('bar[a b=\"c\"]>baz'), result('bar[a b=\"c\"]>baz', 5));\n+ deepStrictEqual(extract('foo>bar'), result('foo>bar', 0));\n+ deepStrictEqual(extract('bar'), result('bar', 5));\n+ deepStrictEqual(extract('bar[a=\"d\" b=\"c\"]>baz'), result('bar[a=\"d\" b=\"c\"]>baz', 5));\n+ });\n+\n+ it('stylesheet abbreviation', () => {\n+ deepStrictEqual(extract('foo{bar|}'), result('foo{bar}', 0));\n+ deepStrictEqual(extract('foo{bar|}', { type: 'stylesheet' }), result('bar', 4));\n+ });\n+\n+ it('prefixed extract', () => {\n+ deepStrictEqual(extract('bar[a b=\"c\"]>baz'), result('bar[a b=\"c\"]>baz', 5));\n+ deepStrictEqual(extract('bar[a b=\"c\"]>baz', { prefix: '<' }), result('foo>bar[a b=\"c\"]>baz', 1, 0));\n+ deepStrictEqual(extract('bar[a b=\"<\"]>baz', { prefix: '<' }), result('foo>bar[a b=\"<\"]>baz', 1, 0));\n+ deepStrictEqual(extract('bar{<}>baz', { prefix: '<' }), result('foo>bar{<}>baz', 1, 0));\n+\n+ // Multiple prefix characters\n+ deepStrictEqual(extract('foo>>>bar[a b=\"c\"]>baz', { prefix: '>>>' }), result('bar[a b=\"c\"]>baz', 6, 3));\n+\n+ // Absent prefix\n+ strictEqual(extract('bar[a b=\"c\"]>baz', { prefix: '&&' }), void 0);\n+ });\n+\n+ it('HTML test', () => {\n+ const html = (str: string) => isAtHTMLTag(scanner(str));\n+\n+ // simple tag\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+\n+ // tag with attributes\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html('
    '));\n+ ok(html(''));\n+\n+ // invalid tags\n+ ok(!html('div>'));\n+ ok(!html(''));\n+ ok(!html('
    '));\n+ ok(!html('
    '));\n+ ok(!html('[a=b c=d]>'));\n+ ok(!html('div[a=b c=d]>'));\n+ });\n+\n+ it('consume quotes', () => {\n+ let s = scanner(' \"foo\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 1);\n+\n+ s = scanner('\"foo\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 0);\n+\n+ s = scanner('\"\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 0);\n+\n+ s = scanner('\"a\\\\\\\"b\"');\n+ ok(consumeQuoted(s));\n+ strictEqual(s.pos, 0);\n+\n+ // don’t eat anything\n+ s = scanner('foo');\n+ ok(!consumeQuoted(s));\n+ strictEqual(s.pos, 3);\n+ });\n+});\n"},"addition_count":{"kind":"number","value":126,"string":"126"},"commit_subject":{"kind":"string","value":"Unit tests and docs for abbreviation extractor"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676479,"cells":{"id":{"kind":"string","value":"10072129"},"text":{"kind":"string","value":" split.gemspec\n # -*- encoding: utf-8 -*-\n# frozen_string_literal: true\n\n$:.push File.expand_path(\"../lib\", __FILE__)\nrequire \"split/version\"\n\nGem::Specification.new do |s|\n s.name = \"split\"\n s.version = Split::VERSION\n s.platform = Gem::Platform::RUBY\n s.authors = [\"Andrew Nesbitt\"]\n s.licenses = [\"MIT\"]\n s.email = [\"andrewnez@gmail.com\"]\n s.homepage = \"https://github.com/splitrb/split\"\n s.summary = \"Rack based split testing framework\"\n\n s.metadata = {\n \"homepage_uri\" => \"https://github.com/splitrb/split\",\n \"changelog_uri\" => \"https://github.com/splitrb/split/blob/main/CHANGELOG.md\",\n \"source_code_uri\" => \"https://github.com/splitrb/split\",\n \"bug_tracker_uri\" => \"https://github.com/splitrb/split/issues\",\n \"wiki_uri\" => \"https://github.com/splitrb/split/wiki\",\n \"mailing_list_uri\" => \"https://groups.google.com/d/forum/split-ruby\"\n }\n s.add_dependency 'sinatra', '>= 1.2.6'\n s.add_dependency 'simple-random'\n\n s.add_development_dependency 'rake'\n s.add_development_dependency 'bundler', '~> 1.6'\n s.add_development_dependency 'rspec', '~> 3.0'\n s.add_development_dependency 'rack-test'\n s.add_development_dependency 'coveralls'\nend\n s.add_dependency \"rubystats\", \">= 0.3.0\"\n\n s.add_development_dependency \"bundler\", \">= 1.17\"\n s.add_development_dependency \"simplecov\", \"~> 0.15\"\n s.add_development_dependency \"rack-test\", \"~> 2.0\"\n s.add_development_dependency \"rake\", \"~> 13\"\n s.add_development_dependency \"rspec\", \"~> 3.7\"\n s.add_development_dependency \"pry\", \"~> 0.10\"\n s.add_development_dependency \"rails\", \">= 5.0\"\nend\n\n Add debugger gem\n\n @@ -25,9 +25,10 @@ Gem::Specification.new do |s|\n s.add_dependency 'sinatra', '>= 1.2.6'\n s.add_dependency 'simple-random'\n \n- s.add_development_dependency 'rake'\n s.add_development_dependency 'bundler', '~> 1.6'\n- s.add_development_dependency 'rspec', '~> 3.0'\n- s.add_development_dependency 'rack-test'\n s.add_development_dependency 'coveralls'\n+ s.add_development_dependency 'debugger'\n+ s.add_development_dependency 'rack-test'\n+ s.add_development_dependency 'rake'\n+ s.add_development_dependency 'rspec', '~> 3.0'\n end\n"},"addition_count":{"kind":"number","value":4,"string":"4"},"commit_subject":{"kind":"string","value":"Add debugger gem"},"deletion_count":{"kind":"number","value":3,"string":"3"},"file_extension":{"kind":"string","value":".gemspec"},"lang":{"kind":"string","value":"gemspec"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676480,"cells":{"id":{"kind":"string","value":"10072130"},"text":{"kind":"string","value":" split.gemspec\n # -*- encoding: utf-8 -*-\n# frozen_string_literal: true\n\n$:.push File.expand_path(\"../lib\", __FILE__)\nrequire \"split/version\"\n\nGem::Specification.new do |s|\n s.name = \"split\"\n s.version = Split::VERSION\n s.platform = Gem::Platform::RUBY\n s.authors = [\"Andrew Nesbitt\"]\n s.licenses = [\"MIT\"]\n s.email = [\"andrewnez@gmail.com\"]\n s.homepage = \"https://github.com/splitrb/split\"\n s.summary = \"Rack based split testing framework\"\n\n s.metadata = {\n \"homepage_uri\" => \"https://github.com/splitrb/split\",\n \"changelog_uri\" => \"https://github.com/splitrb/split/blob/main/CHANGELOG.md\",\n \"source_code_uri\" => \"https://github.com/splitrb/split\",\n \"bug_tracker_uri\" => \"https://github.com/splitrb/split/issues\",\n \"wiki_uri\" => \"https://github.com/splitrb/split/wiki\",\n \"mailing_list_uri\" => \"https://groups.google.com/d/forum/split-ruby\"\n }\n s.add_dependency 'sinatra', '>= 1.2.6'\n s.add_dependency 'simple-random'\n\n s.add_development_dependency 'rake'\n s.add_development_dependency 'bundler', '~> 1.6'\n s.add_development_dependency 'rspec', '~> 3.0'\n s.add_development_dependency 'rack-test'\n s.add_development_dependency 'coveralls'\nend\n s.add_dependency \"rubystats\", \">= 0.3.0\"\n\n s.add_development_dependency \"bundler\", \">= 1.17\"\n s.add_development_dependency \"simplecov\", \"~> 0.15\"\n s.add_development_dependency \"rack-test\", \"~> 2.0\"\n s.add_development_dependency \"rake\", \"~> 13\"\n s.add_development_dependency \"rspec\", \"~> 3.7\"\n s.add_development_dependency \"pry\", \"~> 0.10\"\n s.add_development_dependency \"rails\", \">= 5.0\"\nend\n\n Add debugger gem\n\n @@ -25,9 +25,10 @@ Gem::Specification.new do |s|\n s.add_dependency 'sinatra', '>= 1.2.6'\n s.add_dependency 'simple-random'\n \n- s.add_development_dependency 'rake'\n s.add_development_dependency 'bundler', '~> 1.6'\n- s.add_development_dependency 'rspec', '~> 3.0'\n- s.add_development_dependency 'rack-test'\n s.add_development_dependency 'coveralls'\n+ s.add_development_dependency 'debugger'\n+ s.add_development_dependency 'rack-test'\n+ s.add_development_dependency 'rake'\n+ s.add_development_dependency 'rspec', '~> 3.0'\n end\n"},"addition_count":{"kind":"number","value":4,"string":"4"},"commit_subject":{"kind":"string","value":"Add debugger gem"},"deletion_count":{"kind":"number","value":3,"string":"3"},"file_extension":{"kind":"string","value":".gemspec"},"lang":{"kind":"string","value":"gemspec"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676481,"cells":{"id":{"kind":"string","value":"10072131"},"text":{"kind":"string","value":" split.gemspec\n # -*- encoding: utf-8 -*-\n# frozen_string_literal: true\n\n$:.push File.expand_path(\"../lib\", __FILE__)\nrequire \"split/version\"\n\nGem::Specification.new do |s|\n s.name = \"split\"\n s.version = Split::VERSION\n s.platform = Gem::Platform::RUBY\n s.authors = [\"Andrew Nesbitt\"]\n s.licenses = [\"MIT\"]\n s.email = [\"andrewnez@gmail.com\"]\n s.homepage = \"https://github.com/splitrb/split\"\n s.summary = \"Rack based split testing framework\"\n\n s.metadata = {\n \"homepage_uri\" => \"https://github.com/splitrb/split\",\n \"changelog_uri\" => \"https://github.com/splitrb/split/blob/main/CHANGELOG.md\",\n \"source_code_uri\" => \"https://github.com/splitrb/split\",\n \"bug_tracker_uri\" => \"https://github.com/splitrb/split/issues\",\n \"wiki_uri\" => \"https://github.com/splitrb/split/wiki\",\n \"mailing_list_uri\" => \"https://groups.google.com/d/forum/split-ruby\"\n }\n s.add_dependency 'sinatra', '>= 1.2.6'\n s.add_dependency 'simple-random'\n\n s.add_development_dependency 'rake'\n s.add_development_dependency 'bundler', '~> 1.6'\n s.add_development_dependency 'rspec', '~> 3.0'\n s.add_development_dependency 'rack-test'\n s.add_development_dependency 'coveralls'\nend\n s.add_dependency \"rubystats\", \">= 0.3.0\"\n\n s.add_development_dependency \"bundler\", \">= 1.17\"\n s.add_development_dependency \"simplecov\", \"~> 0.15\"\n s.add_development_dependency \"rack-test\", \"~> 2.0\"\n s.add_development_dependency \"rake\", \"~> 13\"\n s.add_development_dependency \"rspec\", \"~> 3.7\"\n s.add_development_dependency \"pry\", \"~> 0.10\"\n s.add_development_dependency \"rails\", \">= 5.0\"\nend\n\n Add debugger gem\n\n @@ -25,9 +25,10 @@ Gem::Specification.new do |s|\n s.add_dependency 'sinatra', '>= 1.2.6'\n s.add_dependency 'simple-random'\n \n- s.add_development_dependency 'rake'\n s.add_development_dependency 'bundler', '~> 1.6'\n- s.add_development_dependency 'rspec', '~> 3.0'\n- s.add_development_dependency 'rack-test'\n s.add_development_dependency 'coveralls'\n+ s.add_development_dependency 'debugger'\n+ s.add_development_dependency 'rack-test'\n+ s.add_development_dependency 'rake'\n+ s.add_development_dependency 'rspec', '~> 3.0'\n end\n"},"addition_count":{"kind":"number","value":4,"string":"4"},"commit_subject":{"kind":"string","value":"Add debugger gem"},"deletion_count":{"kind":"number","value":3,"string":"3"},"file_extension":{"kind":"string","value":".gemspec"},"lang":{"kind":"string","value":"gemspec"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676482,"cells":{"id":{"kind":"string","value":"10072132"},"text":{"kind":"string","value":" transducers.js\n \n// basic protocol helpers\n\nvar symbolExists = typeof Symbol !== 'undefined';\n\nvar protocols = {\n iterator: symbolExists ? Symbol.iterator : '@@iterator'\n};\n\nfunction throwProtocolError(name, coll) {\n throw new Error(\"don't know how to \" + name + \" collection: \" +\n coll);\n}\n\nfunction fulfillsProtocol(obj, name) {\n if(name === 'iterator') {\n // Accept ill-formed iterators that don't conform to the\n // protocol by accepting just next()\n return obj[protocols.iterator] || obj.next;\n }\n\n return obj[protocols[name]];\n}\n\nfunction getProtocolProperty(obj, name) {\n return obj[protocols[name]];\n}\n\nfunction iterator(coll) {\n var iter = getProtocolProperty(coll, 'iterator');\n if(iter) {\n return iter.call(coll);\n }\n else if(coll.next) {\n // Basic duck typing to accept an ill-formed iterator that doesn't\n // conform to the iterator protocol (all iterators should have the\n // @@iterator method and return themselves, but some engines don't\n // have that on generators like older v8)\n return coll;\n }\n else if(isArray(coll)) {\n return new ArrayIterator(coll);\n }\n else if(isObject(coll)) {\n return new ObjectIterator(coll);\n }\n}\n\nfunction ArrayIterator(arr) {\n this.arr = arr;\n this.index = 0;\n}\n\nArrayIterator.prototype.next = function() {\n if(this.index < this.arr.length) {\n return {\n value: this.arr[this.index++],\n done: false\n };\n }\n return {\n done: true\n }\n};\n\nfunction ObjectIterator(obj) {\n this.obj = obj;\n this.keys = Object.keys(obj);\n this.index = 0;\n}\n\nObjectIterator.prototype.next = function() {\n if(this.index < this.keys.length) {\n var k = this.keys[this.index++];\n return {\n value: [k, this.obj[k]],\n done: false\n };\n }\n return {\n done: true\n }\n};\n\n// helpers\n\nvar toString = Object.prototype.toString;\nvar isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) {\n return toString.call(obj) == '[object Array]';\n};\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nfunction isObject(x) {\n return x instanceof Object &&\n Object.getPrototypeOf(x) === Object.getPrototypeOf({});\n}\n\nfunction isNumber(x) {\n return typeof x === 'number';\n}\n\nfunction Reduced(value) {\n this.val = val;\n}\n\nfunction reduce(coll, f, init) {\n if(isArray(coll)) {\n var result = init;\n var index = -1;\n var len = coll.length;\n while(++index < len) {\n result = f(result, coll[index]);\n if(result instanceof Reduced) {\n return result.val;\n }\n }\n return result;\n }\n else if(fulfillsProtocol(coll, 'iterator')) {\n var result = init;\n var iter = iterator(coll);\n var val = iter.next();\n while(!val.done) {\n result = f(result, val.value);\n if(result instanceof Reduced) {\n return result.val;\n }\n val = iter.next();\n }\n return result;\n }\n else if(isObject(coll)) {\n return reduce(Object.keys(coll), function(result, k) {\n return f(result, [k, coll[k]]);\n }, init);\n }\n throwProtocolError('reduce', coll);\n}\n\nfunction transduce(xform, reducer, init, coll) {\n reducer = xform(reducer);\n if(!coll) {\n coll = init;\n init = reducer.init();\n }\n var res = reduce(coll, function(res, input) {\n return reducer.step(res, input);\n }, init);\n return reducer.result(res);\n}\n\nfunction compose() {\n while(++index < len) {\n result = xform['@@transducer/step'](result, coll[index]);\n if(isReduced(result)) {\n result = deref(result);\n break;\n }\n }\n return xform['@@transducer/result'](result);\n }\n else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {\n var result = init;\n var iter = iterator(coll);\n var val = iter.next();\n while(!val.done) {\n result = xform['@@transducer/step'](result, val.value);\n if(isReduced(result)) {\n result = deref(result);\n break;\n }\n val = iter.next();\n }\n return xform['@@transducer/result'](result);\n }\n throwProtocolError('iterate', coll);\n}\n\nfunction transduce(coll, xform, reducer, init) {\n xform = xform(reducer);\n if(init === undefined) {\n init = xform['@@transducer/init']();\n }\n return reduce(coll, xform, init);\n}\n\nfunction compose() {\n var funcs = Array.prototype.slice.call(arguments);\n return function(r) {\n var value = r;\n for(var i=funcs.length-1; i>=0; i--) {\n value = funcs[i](value);\n }\n return value;\n }\n }\n}\n\nfunction arrayMap(f, arr, ctx) {\n var index = -1;\n var length = arr.length;\n var result = Array(length);\n throw new Error('init value unavailable');\n };\n t['@@transducer/result'] = function(v) {\n return v;\n };\n return result;\n}\n\nfunction arrayFilter(f, arr, ctx) {\n var len = arr.length;\n var result = [];\n f = bound(f, ctx, 2);\n if(!ctx) {\n return f;\n }\n else {\n switch(count) {\n case 1:\n return function(x) {\n return f.call(ctx, x);\n }\n case 2:\n return function(x, y) {\n return f.call(ctx, x, y);\n }\n default:\n return f.bind(ctx);\n }\n }\n}\n\nfunction arrayMap(arr, f, ctx) {\n var index = -1;\n var length = arr.length;\n var result = Array(length);\n f = bound(f, ctx, 2);\n\n while (++index < length) {\n result[index] = f(arr[index], index);\n }\n return result;\n\n if(coll) {\n if(isArray(coll)) {\n return arrayMap(f, coll, ctx);\n }\n return seq(coll, map(f));\n }\n for(var i=0; i= this.n) {\n // Finish reducing on the same step as the final value. TODO:\n // double-check that this doesn't break any semantics\n result = ensureReduced(result);\n }\n }\n this.i++;\n return result;\n};\n\nfunction take(coll, n) {\n if(isNumber(coll)) { n = coll; coll = null }\n\n if(coll) {\n return seq(coll, take(n));\n }\n\n return function(xform) {\n return new Take(n, xform);\n }\n}\n\nfunction Drop(n, xform) {\n this.n = n;\n this.i = 0;\n this.xform = xform;\n}\n\nDrop.prototype['@@transducer/init'] = function() {\n return this.xform['@@transducer/init']();\n};\n\nDrop.prototype['@@transducer/result'] = function(v) {\n return this.xform['@@transducer/result'](v);\n};\n\nDrop.prototype['@@transducer/step'] = function(result, input) {\n if(this.i++ < this.n) {\n return result;\n }\n return this.xform['@@transducer/step'](result, input);\n};\n\nfunction drop(coll, n) {\n if(isNumber(coll)) { n = coll; coll = null }\n\n if(coll) {\n return seq(coll, drop(n));\n }\n\n return function(xform) {\n return new Drop(n, xform);\n }\n}\n\nfunction DropWhile(f, xform) {\n this.xform = xform;\n this.f = f;\n this.dropping = true;\n}\n\nDropWhile.prototype['@@transducer/init'] = function() {\n return this.xform['@@transducer/init']();\n};\n\nCat.prototype.step = function(result, input) {\n var xform = this.xform;\n\n return reduce(input, function(res, input) {\n return xform.step(res, input)\n }, result);\n};\n\nfunction cat(xform) {\n\n if(coll) {\n return seq(coll, dropWhile(f));\n }\n\n return function(xform) {\n return new DropWhile(f, xform);\n }\n}\n\nfunction Partition(n, xform) {\n this.n = n;\n this.i = 0;\n this.xform = xform;\n this.part = new Array(n);\n}\n\nPartition.prototype['@@transducer/init'] = function() {\n return this.xform['@@transducer/init']();\n};\n\nPartition.prototype['@@transducer/result'] = function(v) {\n if (this.i > 0) {\n return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i)));\n }\n return this.xform['@@transducer/result'](v);\n};\n\nPartition.prototype['@@transducer/step'] = function(result, input) {\n this.part[this.i] = input;\n this.i += 1;\n if (this.i === this.n) {\n var out = this.part.slice(0, this.n);\n this.part = new Array(this.n);\n this.i = 0;\n return this.xform['@@transducer/step'](result, out);\n }\n return result;\n};\n\nfunction partition(coll, n) {\n if (isNumber(coll)) {\n n = coll; coll = null;\n }\n\n if (coll) {\n return seq(coll, partition(n));\n }\n\n return function(xform) {\n return new Partition(n, xform);\n };\n}\n\nvar NOTHING = {};\n\nfunction PartitionBy(f, xform) {\n // TODO: take an \"opts\" object that allows the user to specify\n // equality\n this.f = f;\n this.xform = xform;\n this.part = [];\n this.last = NOTHING;\n\nfunction array(coll, xform) {\n if(!xform) {\n return reduce(coll, push, []);\n }\n return transduce(xform, arrayReducer, [], coll);\n}\n\nfunction obj(coll, xform) {\n if(!xform) {\n return reduce(coll, merge, {});\n }\n return transduce(xform, objReducer, {}, coll);\n}\nPartitionBy.prototype['@@transducer/step'] = function(result, input) {\n var current = this.f(input);\n if (current === this.last || this.last === NOTHING) {\n this.part.push(input);\n } else {\n result = this.xform['@@transducer/step'](result, this.part);\n this.part = [input];\n }\n this.last = current;\n return result;\n};\n\nfunction partitionBy(coll, f, ctx) {\n if (isFunction(coll)) { ctx = f; f = coll; coll = null; }\n f = bound(f, ctx);\n\n if (coll) {\n return seq(coll, partitionBy(f));\n }\n\n return function(xform) {\n return new PartitionBy(f, xform);\n };\n}\n\nfunction Interpose(sep, xform) {\n this.sep = sep;\n this.xform = xform;\n this.started = false;\n}\n\nInterpose.prototype['@@transducer/init'] = function() {\n return this.xform['@@transducer/init']();\n};\n\nInterpose.prototype['@@transducer/result'] = function(v) {\n return this.xform['@@transducer/result'](v);\n};\n\nInterpose.prototype['@@transducer/step'] = function(result, input) {\n if (this.started) {\n var withSep = this.xform['@@transducer/step'](result, this.sep);\n if (isReduced(withSep)) {\n return withSep;\n } else {\n return this.xform['@@transducer/step'](withSep, input);\n }\n } else {\n this.started = true;\n return this.xform['@@transducer/step'](result, input);\n }\n};\n\n/**\n * Returns a new collection containing elements of the given\n * collection, separated by the specified separator. Returns a\n * transducer if a collection is not provided.\n */\nfunction interpose(coll, separator) {\n if (arguments.length === 1) {\n separator = coll;\n return function(xform) {\n return new Interpose(separator, xform);\n };\n }\n return seq(coll, interpose(separator));\n}\n\nfunction Repeat(n, xform) {\n this.xform = xform;\n this.n = n;\n}\n\nRepeat.prototype['@@transducer/init'] = function() {\n return this.xform['@@transducer/init']();\n};\n\nRepeat.prototype['@@transducer/result'] = function(v) {\n return this.xform['@@transducer/result'](v);\n};\n\nRepeat.prototype['@@transducer/step'] = function(result, input) {\n var n = this.n;\n var r = result;\n for (var i = 0; i < n; i++) {\n r = this.xform['@@transducer/step'](r, input);\n if (isReduced(r)) {\n break;\n }\n }\n return r;\n};\n\n/**\n * Returns a new collection containing elements of the given\n * collection, each repeated n times. Returns a transducer if a\n * collection is not provided.\n */\nfunction repeat(coll, n) {\n if (arguments.length === 1) {\n n = coll;\n return function(xform) {\n return new Repeat(n, xform);\n };\n }\n return seq(coll, repeat(n));\n}\n\nfunction TakeNth(n, xform) {\n this.xform = xform;\n this.n = n;\n this.i = -1;\n}\n\nTakeNth.prototype['@@transducer/init'] = function() {\n return this.xform['@@transducer/init']();\n};\n\nTakeNth.prototype['@@transducer/result'] = function(v) {\n return this.xform['@@transducer/result'](v);\n};\n\nTakeNth.prototype['@@transducer/step'] = function(result, input) {\n this.i += 1;\n if (this.i % this.n === 0) {\n return this.xform['@@transducer/step'](result, input);\n }\n return result;\n};\n\n/**\n * Returns a new collection of every nth element of the given\n * collection. Returns a transducer if a collection is not provided.\n */\nfunction takeNth(coll, nth) {\n if (arguments.length === 1) {\n nth = coll;\n return function(xform) {\n return new TakeNth(nth, xform);\n };\n }\n return seq(coll, takeNth(nth));\n}\n\n// pure transducers (cannot take collections)\n\nfunction Cat(xform) {\n this.xform = xform;\n}\n\nCat.prototype['@@transducer/init'] = function() {\n return this.xform['@@transducer/init']();\n};\n\nCat.prototype['@@transducer/result'] = function(v) {\n return this.xform['@@transducer/result'](v);\n};\n\nCat.prototype['@@transducer/step'] = function(result, input) {\n var xform = this.xform;\n var newxform = {};\n newxform['@@transducer/init'] = function() {\n return xform['@@transducer/init']();\n };\n newxform['@@transducer/result'] = function(v) {\n return v;\n };\n newxform['@@transducer/step'] = function(result, input) {\n var val = xform['@@transducer/step'](result, input);\n return isReduced(val) ? deref(val) : val;\n };\n\n return reduce(input, newxform, result);\n};\n\nfunction cat(xform) {\n return new Cat(xform);\n}\n\nfunction mapcat(f, ctx) {\n f = bound(f, ctx);\n return compose(map(f), cat);\n}\n\n// collection helpers\n\nfunction push(arr, x) {\n arr.push(x);\n return arr;\n}\n\nfunction merge(obj, x) {\n if(isArray(x) && x.length === 2) {\n obj[x[0]] = x[1];\n }\n else {\n var keys = Object.keys(x);\n var len = keys.length;\n for(var i=0; i switch coll and f order in APIs, benchmark tweaks\n\n @@ -106,50 +106,42 @@ function Reduced(val) {\n this.val = val;\n }\n \n-function reduce(coll, f, init) {\n+function reduce(coll, xform, init) {\n if(isArray(coll)) {\n var result = init;\n var index = -1;\n var len = coll.length;\n while(++index < len) {\n- result = f(result, coll[index]);\n+ result = xform.step(result, coll[index]);\n if(result instanceof Reduced) {\n return result.val;\n }\n }\n- return result;\n+ return xform.result(result);\n }\n- else if(fulfillsProtocol(coll, 'iterator')) {\n+ else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) {\n var result = init;\n var iter = iterator(coll);\n var val = iter.next();\n while(!val.done) {\n- result = f(result, val.value);\n+ result = xform.step(result, val.value);\n if(result instanceof Reduced) {\n return result.val;\n }\n val = iter.next();\n }\n- return result;\n+ return xform.result(result);\n }\n- else if(isObject(coll)) {\n- return reduce(Object.keys(coll), function(result, k) {\n- return f(result, [k, coll[k]]);\n- }, init);\n- }\n- throwProtocolError('reduce', coll);\n+ throwProtocolError('iterate', coll);\n }\n \n function transduce(xform, reducer, init, coll) {\n- reducer = xform(reducer);\n+ xform = xform(reducer);\n if(!coll) {\n coll = init;\n- init = reducer.init();\n+ init = xform.init();\n }\n- var res = reduce(coll, function(res, input) {\n- return reducer.step(res, input);\n- }, init);\n- return reducer.result(res);\n+ return reduce(coll, xform, init);\n }\n \n function compose() {\n@@ -199,7 +191,7 @@ function bound(f, ctx, count) {\n }\n }\n \n-function arrayMap(f, arr, ctx) {\n+function arrayMap(arr, f, ctx) {\n var index = -1;\n var length = arr.length;\n var result = Array(length);\n@@ -211,7 +203,7 @@ function arrayMap(f, arr, ctx) {\n return result;\n }\n \n-function arrayFilter(f, arr, ctx) {\n+function arrayFilter(arr, f, ctx) {\n var len = arr.length;\n var result = [];\n f = bound(f, ctx, 2);\n@@ -247,7 +239,7 @@ function map(coll, f, ctx) {\n \n if(coll) {\n if(isArray(coll)) {\n- return arrayMap(f, coll, ctx);\n+ return arrayMap(coll, f, ctx);\n }\n return seq(coll, map(f));\n }\n@@ -283,7 +275,7 @@ function filter(coll, f, ctx) {\n \n if(coll) {\n if(isArray(coll)) {\n- return arrayFilter(f, coll, ctx);\n+ return arrayFilter(coll, f, ctx);\n }\n return seq(coll, filter(f));\n }\n@@ -486,10 +478,20 @@ Cat.prototype.result = function(v) {\n \n Cat.prototype.step = function(result, input) {\n var xform = this.xform;\n+ var newxform = {\n+ init: function() {\n+ return xform.init();\n+ },\n+ result: function(v) {\n+ return v;\n+ },\n+ step: function(result, input) {\n+ var val = xform.step(result, input);\n+ return (val instanceof Reduced) ? new Reduced(val) : val;\n+ }\n+ }\n \n- return reduce(input, function(res, input) {\n- return xform.step(res, input)\n- }, result);\n+ return reduce(input, newxform, result);\n };\n \n function cat(xform) {\n@@ -559,14 +561,14 @@ function getReducer(coll) {\n \n function array(coll, xform) {\n if(!xform) {\n- return reduce(coll, push, []);\n+ return reduce(coll, arrayReducer, []);\n }\n return transduce(xform, arrayReducer, [], coll);\n }\n \n function obj(coll, xform) {\n if(!xform) {\n- return reduce(coll, merge, {});\n+ return reduce(coll, objReducer, {});\n }\n return transduce(xform, objReducer, {}, coll);\n }\n"},"addition_count":{"kind":"number","value":29,"string":"29"},"commit_subject":{"kind":"string","value":"switch coll and f order in APIs, benchmark tweaks"},"deletion_count":{"kind":"number","value":27,"string":"27"},"file_extension":{"kind":"string","value":".js"},"lang":{"kind":"string","value":"js"},"license":{"kind":"string","value":"bsd-2-clause"},"repo_name":{"kind":"string","value":"jlongster/transducers.js"}}},{"rowIdx":10676483,"cells":{"id":{"kind":"string","value":"10072133"},"text":{"kind":"string","value":" index.ngdoc\n ADDFILE\n chore(dgeni): Added content and assets for index page\n\n @@ -0,0 +1,5 @@\n+@ngdoc overview\n+@name Semantic-UI-Angular API Reference\n+@description\n+\n+Welcome to the Semantic-UI-Angular API docs page!\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":5,"string":"5"},"commit_subject":{"kind":"string","value":"chore(dgeni): Added content and assets for index page"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ngdoc"},"lang":{"kind":"string","value":"ngdoc"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676484,"cells":{"id":{"kind":"string","value":"10072134"},"text":{"kind":"string","value":" index.ngdoc\n ADDFILE\n chore(dgeni): Added content and assets for index page\n\n @@ -0,0 +1,5 @@\n+@ngdoc overview\n+@name Semantic-UI-Angular API Reference\n+@description\n+\n+Welcome to the Semantic-UI-Angular API docs page!\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":5,"string":"5"},"commit_subject":{"kind":"string","value":"chore(dgeni): Added content and assets for index page"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ngdoc"},"lang":{"kind":"string","value":"ngdoc"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676485,"cells":{"id":{"kind":"string","value":"10072135"},"text":{"kind":"string","value":" index.ngdoc\n ADDFILE\n chore(dgeni): Added content and assets for index page\n\n @@ -0,0 +1,5 @@\n+@ngdoc overview\n+@name Semantic-UI-Angular API Reference\n+@description\n+\n+Welcome to the Semantic-UI-Angular API docs page!\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":5,"string":"5"},"commit_subject":{"kind":"string","value":"chore(dgeni): Added content and assets for index page"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ngdoc"},"lang":{"kind":"string","value":"ngdoc"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"Semantic-Org/Semantic-UI-Angular"}}},{"rowIdx":10676486,"cells":{"id":{"kind":"string","value":"10072136"},"text":{"kind":"string","value":" dual_adapter_spec.rb\n # frozen_string_literal: true\n\nrequire \"spec_helper\"\n\ndescribe Split::Persistence::DualAdapter do\n let(:context) { \"some context\" }\n\n let(:logged_in_adapter_instance) { double }\n let(:logged_in_adapter) do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } }\n end\n let(:logged_out_adapter_instance) { double }\n let(:logged_out_adapter) do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } }\n end\n\n context 'when logged in' do\n subject do\n described_class.with_config(\n logged_in: lambda { |context| true },\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n end\n\n it '#[]=' do\n expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n subject['my_key'] = 'my_value'\n end\n\n it '#[]' do\n expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n expect(subject['my_key']).to eq('my_value')\n end\n\n it '#delete' do\n expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(subject.delete('my_key')).to eq('my_value')\n end\n\n it '#keys' do\n expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n expect(subject.keys).to eq(['my_value', 'my_value2'])\n end\n end\n\n context 'when logged out' do\n subject do\n described_class.with_config(\n logged_in: lambda { |context| false },\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n end\n\n it '#[]=' do\n expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n subject['my_key'] = 'my_value'\n end\n\n it '#[]' do\n expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n expect(subject['my_key']).to eq('my_value')\n end\n\n it '#delete' do\n expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(subject.delete('my_key')).to eq('my_value')\n end\n\n it '#keys' do\n expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n expect(subject.keys).to eq(['my_value', 'my_value2'])\n end\n end\n\n describe \"when errors in config\" do\n before { described_class.config.clear }\n let(:some_proc) { -> { } }\n\n it \"when no logged in adapter\" do\n expect {\n described_class.with_config(\n logged_in: some_proc,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_in_adapter/)\n end\n\n it \"when no logged out adapter\" do\n expect {\n described_class.with_config(\n logged_in: some_proc,\n logged_in_adapter: logged_in_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_out_adapter/)\n end\n\n it \"when no logged in detector\" do\n expect {\n described_class.with_config(\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_in$/)\n end\n end\nend\n\n Add a flag to use the new behavior of the DualAdapter\n\n @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } }\n end\n \n- context 'when logged in' do\n- subject do\n- described_class.with_config(\n- logged_in: lambda { |context| true },\n- logged_in_adapter: logged_in_adapter,\n- logged_out_adapter: logged_out_adapter\n- ).new(context)\n- end\n-\n- it '#[]=' do\n- expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n- subject['my_key'] = 'my_value'\n- end\n-\n- it '#[]' do\n- expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n- expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n- expect(subject['my_key']).to eq('my_value')\n- end\n-\n- it '#delete' do\n- expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(subject.delete('my_key')).to eq('my_value')\n+ context 'when fallback_to_logged_out_adapter is false' do\n+ context 'when logged in' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| true },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: false\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[]=)\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:delete)\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:keys)\n+ expect(subject.keys).to eq(['my_value'])\n+ end\n end\n \n- it '#keys' do\n- expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n- expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n- expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ context 'when logged out' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| false },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: false\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:delete)\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:keys)\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n end\n \n- context 'when logged out' do\n- subject do\n- described_class.with_config(\n- logged_in: lambda { |context| false },\n- logged_in_adapter: logged_in_adapter,\n- logged_out_adapter: logged_out_adapter\n- ).new(context)\n- end\n-\n- it '#[]=' do\n- expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n- expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n- subject['my_key'] = 'my_value'\n- end\n-\n- it '#[]' do\n- expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n- expect(subject['my_key']).to eq('my_value')\n- end\n-\n- it '#delete' do\n- expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(subject.delete('my_key')).to eq('my_value')\n+ context 'when fallback_to_logged_out_adapter is true' do\n+ context 'when logged in' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| true },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: true\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n \n- it '#keys' do\n- expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n- expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n- expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ context 'when logged out' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| false },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: true\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n end\n \n"},"addition_count":{"kind":"number","value":136,"string":"136"},"commit_subject":{"kind":"string","value":"Add a flag to use the new behavior of the DualAdapter"},"deletion_count":{"kind":"number","value":60,"string":"60"},"file_extension":{"kind":"string","value":".rb"},"lang":{"kind":"string","value":"rb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676487,"cells":{"id":{"kind":"string","value":"10072137"},"text":{"kind":"string","value":" dual_adapter_spec.rb\n # frozen_string_literal: true\n\nrequire \"spec_helper\"\n\ndescribe Split::Persistence::DualAdapter do\n let(:context) { \"some context\" }\n\n let(:logged_in_adapter_instance) { double }\n let(:logged_in_adapter) do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } }\n end\n let(:logged_out_adapter_instance) { double }\n let(:logged_out_adapter) do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } }\n end\n\n context 'when logged in' do\n subject do\n described_class.with_config(\n logged_in: lambda { |context| true },\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n end\n\n it '#[]=' do\n expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n subject['my_key'] = 'my_value'\n end\n\n it '#[]' do\n expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n expect(subject['my_key']).to eq('my_value')\n end\n\n it '#delete' do\n expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(subject.delete('my_key')).to eq('my_value')\n end\n\n it '#keys' do\n expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n expect(subject.keys).to eq(['my_value', 'my_value2'])\n end\n end\n\n context 'when logged out' do\n subject do\n described_class.with_config(\n logged_in: lambda { |context| false },\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n end\n\n it '#[]=' do\n expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n subject['my_key'] = 'my_value'\n end\n\n it '#[]' do\n expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n expect(subject['my_key']).to eq('my_value')\n end\n\n it '#delete' do\n expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(subject.delete('my_key')).to eq('my_value')\n end\n\n it '#keys' do\n expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n expect(subject.keys).to eq(['my_value', 'my_value2'])\n end\n end\n\n describe \"when errors in config\" do\n before { described_class.config.clear }\n let(:some_proc) { -> { } }\n\n it \"when no logged in adapter\" do\n expect {\n described_class.with_config(\n logged_in: some_proc,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_in_adapter/)\n end\n\n it \"when no logged out adapter\" do\n expect {\n described_class.with_config(\n logged_in: some_proc,\n logged_in_adapter: logged_in_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_out_adapter/)\n end\n\n it \"when no logged in detector\" do\n expect {\n described_class.with_config(\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_in$/)\n end\n end\nend\n\n Add a flag to use the new behavior of the DualAdapter\n\n @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } }\n end\n \n- context 'when logged in' do\n- subject do\n- described_class.with_config(\n- logged_in: lambda { |context| true },\n- logged_in_adapter: logged_in_adapter,\n- logged_out_adapter: logged_out_adapter\n- ).new(context)\n- end\n-\n- it '#[]=' do\n- expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n- subject['my_key'] = 'my_value'\n- end\n-\n- it '#[]' do\n- expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n- expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n- expect(subject['my_key']).to eq('my_value')\n- end\n-\n- it '#delete' do\n- expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(subject.delete('my_key')).to eq('my_value')\n+ context 'when fallback_to_logged_out_adapter is false' do\n+ context 'when logged in' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| true },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: false\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[]=)\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:delete)\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:keys)\n+ expect(subject.keys).to eq(['my_value'])\n+ end\n end\n \n- it '#keys' do\n- expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n- expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n- expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ context 'when logged out' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| false },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: false\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:delete)\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:keys)\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n end\n \n- context 'when logged out' do\n- subject do\n- described_class.with_config(\n- logged_in: lambda { |context| false },\n- logged_in_adapter: logged_in_adapter,\n- logged_out_adapter: logged_out_adapter\n- ).new(context)\n- end\n-\n- it '#[]=' do\n- expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n- expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n- subject['my_key'] = 'my_value'\n- end\n-\n- it '#[]' do\n- expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n- expect(subject['my_key']).to eq('my_value')\n- end\n-\n- it '#delete' do\n- expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(subject.delete('my_key')).to eq('my_value')\n+ context 'when fallback_to_logged_out_adapter is true' do\n+ context 'when logged in' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| true },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: true\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n \n- it '#keys' do\n- expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n- expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n- expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ context 'when logged out' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| false },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: true\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n end\n \n"},"addition_count":{"kind":"number","value":136,"string":"136"},"commit_subject":{"kind":"string","value":"Add a flag to use the new behavior of the DualAdapter"},"deletion_count":{"kind":"number","value":60,"string":"60"},"file_extension":{"kind":"string","value":".rb"},"lang":{"kind":"string","value":"rb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676488,"cells":{"id":{"kind":"string","value":"10072138"},"text":{"kind":"string","value":" dual_adapter_spec.rb\n # frozen_string_literal: true\n\nrequire \"spec_helper\"\n\ndescribe Split::Persistence::DualAdapter do\n let(:context) { \"some context\" }\n\n let(:logged_in_adapter_instance) { double }\n let(:logged_in_adapter) do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } }\n end\n let(:logged_out_adapter_instance) { double }\n let(:logged_out_adapter) do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } }\n end\n\n context 'when logged in' do\n subject do\n described_class.with_config(\n logged_in: lambda { |context| true },\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n end\n\n it '#[]=' do\n expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n subject['my_key'] = 'my_value'\n end\n\n it '#[]' do\n expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n expect(subject['my_key']).to eq('my_value')\n end\n\n it '#delete' do\n expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(subject.delete('my_key')).to eq('my_value')\n end\n\n it '#keys' do\n expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n expect(subject.keys).to eq(['my_value', 'my_value2'])\n end\n end\n\n context 'when logged out' do\n subject do\n described_class.with_config(\n logged_in: lambda { |context| false },\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n end\n\n it '#[]=' do\n expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n subject['my_key'] = 'my_value'\n end\n\n it '#[]' do\n expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n expect(subject['my_key']).to eq('my_value')\n end\n\n it '#delete' do\n expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n expect(subject.delete('my_key')).to eq('my_value')\n end\n\n it '#keys' do\n expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n expect(subject.keys).to eq(['my_value', 'my_value2'])\n end\n end\n\n describe \"when errors in config\" do\n before { described_class.config.clear }\n let(:some_proc) { -> { } }\n\n it \"when no logged in adapter\" do\n expect {\n described_class.with_config(\n logged_in: some_proc,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_in_adapter/)\n end\n\n it \"when no logged out adapter\" do\n expect {\n described_class.with_config(\n logged_in: some_proc,\n logged_in_adapter: logged_in_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_out_adapter/)\n end\n\n it \"when no logged in detector\" do\n expect {\n described_class.with_config(\n logged_in_adapter: logged_in_adapter,\n logged_out_adapter: logged_out_adapter\n ).new(context)\n }.to raise_error(StandardError, /:logged_in$/)\n end\n end\nend\n\n Add a flag to use the new behavior of the DualAdapter\n\n @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do\n Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } }\n end\n \n- context 'when logged in' do\n- subject do\n- described_class.with_config(\n- logged_in: lambda { |context| true },\n- logged_in_adapter: logged_in_adapter,\n- logged_out_adapter: logged_out_adapter\n- ).new(context)\n- end\n-\n- it '#[]=' do\n- expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n- subject['my_key'] = 'my_value'\n- end\n-\n- it '#[]' do\n- expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n- expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n- expect(subject['my_key']).to eq('my_value')\n- end\n-\n- it '#delete' do\n- expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(subject.delete('my_key')).to eq('my_value')\n+ context 'when fallback_to_logged_out_adapter is false' do\n+ context 'when logged in' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| true },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: false\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[]=)\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:delete)\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:keys)\n+ expect(subject.keys).to eq(['my_value'])\n+ end\n end\n \n- it '#keys' do\n- expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n- expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n- expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ context 'when logged out' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| false },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: false\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:delete)\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:keys)\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n end\n \n- context 'when logged out' do\n- subject do\n- described_class.with_config(\n- logged_in: lambda { |context| false },\n- logged_in_adapter: logged_in_adapter,\n- logged_out_adapter: logged_out_adapter\n- ).new(context)\n- end\n-\n- it '#[]=' do\n- expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n- expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n- subject['my_key'] = 'my_value'\n- end\n-\n- it '#[]' do\n- expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n- expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n- expect(subject['my_key']).to eq('my_value')\n- end\n-\n- it '#delete' do\n- expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n- expect(subject.delete('my_key')).to eq('my_value')\n+ context 'when fallback_to_logged_out_adapter is true' do\n+ context 'when logged in' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| true },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: true\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect_any_instance_of(logged_out_adapter).not_to receive(:[])\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n \n- it '#keys' do\n- expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n- expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n- expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ context 'when logged out' do\n+ subject do\n+ described_class.with_config(\n+ logged_in: lambda { |context| false },\n+ logged_in_adapter: logged_in_adapter,\n+ logged_out_adapter: logged_out_adapter,\n+ fallback_to_logged_out_adapter: true\n+ ).new(context)\n+ end\n+\n+ it '#[]=' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[]=)\n+ expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value')\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil }\n+ subject['my_key'] = 'my_value'\n+ end\n+\n+ it '#[]' do\n+ expect_any_instance_of(logged_in_adapter).not_to receive(:[])\n+ expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' }\n+ expect(subject['my_key']).to eq('my_value')\n+ end\n+\n+ it '#delete' do\n+ expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' }\n+ expect(subject.delete('my_key')).to eq('my_value')\n+ end\n+\n+ it '#keys' do\n+ expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] }\n+ expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] }\n+ expect(subject.keys).to eq(['my_value', 'my_value2'])\n+ end\n end\n end\n \n"},"addition_count":{"kind":"number","value":136,"string":"136"},"commit_subject":{"kind":"string","value":"Add a flag to use the new behavior of the DualAdapter"},"deletion_count":{"kind":"number","value":60,"string":"60"},"file_extension":{"kind":"string","value":".rb"},"lang":{"kind":"string","value":"rb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676489,"cells":{"id":{"kind":"string","value":"10072139"},"text":{"kind":"string","value":" experiment_spec.rb\n # frozen_string_literal: true\n\nrequire \"spec_helper\"\nrequire \"time\"\n\ndescribe Split::Experiment do\n def new_experiment(goals = [])\n Split::Experiment.new(\"link_color\", alternatives: [\"blue\", \"red\", \"green\"], goals: goals)\n end\n\n def alternative(color)\n Split::Alternative.new(color, \"link_color\")\n end\n\n let(:experiment) { new_experiment }\n\n let(:blue) { alternative(\"blue\") }\n let(:green) { alternative(\"green\") }\n\n context \"with an experiment\" do\n let(:experiment) { Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"]) }\n\n it \"should have a name\" do\n expect(experiment.name).to eq(\"basket_text\")\n end\n\n it \"should have alternatives\" do\n expect(experiment.alternatives.length).to be 2\n end\n\n it \"should have alternatives with correct names\" do\n expect(experiment.alternatives.collect { |a| a.name }).to eq([\"Basket\", \"Cart\"])\n end\n\n it \"should be resettable by default\" do\n expect(experiment.resettable).to be_truthy\n end\n\n it \"should save to redis\" do\n experiment.save\n expect(Split.redis.exists?(\"basket_text\")).to be true\n end\n\n it \"should save the start time to redis\" do\n experiment_start_time = Time.at(1372167761)\n expect(Time).to receive(:now).and_return(experiment_start_time)\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to eq(experiment_start_time)\n end\n\n it \"should not save the start time to redis when start_manually is enabled\" do\n expect(Split.configuration).to receive(:start_manually).and_return(true)\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to be_nil\n end\n\n it \"should save the selected algorithm to redis\" do\n experiment_algorithm = Split::Algorithms::Whiplash\n experiment.algorithm = experiment_algorithm\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").algorithm).to eq(experiment_algorithm)\n end\n\n it \"should handle having a start time stored as a string\" do\n experiment_start_time = Time.parse(\"Sat Mar 03 14:01:03\")\n expect(Time).to receive(:now).twice.and_return(experiment_start_time)\n experiment.save\n Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to eq(experiment_start_time)\n end\n\n it \"should handle not having a start time\" do\n experiment_start_time = Time.parse(\"Sat Mar 03 14:01:03\")\n expect(Time).to receive(:now).and_return(experiment_start_time)\n experiment.save\n\n Split.redis.hdel(:experiment_start_times, experiment.name)\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to be_nil\n end\n\n it \"should not create duplicates when saving multiple times\" do\n experiment.save\n experiment.save\n expect(Split.redis.exists?(\"basket_text\")).to be true\n expect(Split.redis.lrange(\"basket_text\", 0, -1)).to eq(['{\"Basket\":1}', '{\"Cart\":1}'])\n end\n\n describe \"new record?\" do\n it \"should know if it hasn't been saved yet\" do\n expect(experiment.new_record?).to be_truthy\n end\n\n it \"should know if it has been saved yet\" do\n experiment.save\n expect(experiment.new_record?).to be_falsey\n end\n end\n\n describe \"control\" do\n it \"should be the first alternative\" do\n experiment.save\n expect(experiment.control.name).to eq(\"Basket\")\n end\n end\n end\n\n describe \"initialization\" do\n it \"should set the algorithm when passed as an option to the initializer\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash)\n expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n\n it \"should be possible to make an experiment not resettable\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], resettable: false)\n expect(experiment.resettable).to be_falsey\n end\n experiment.next_alternative.name.should eql('green')\n end\n end\nend\n\n end\n\n describe \"persistent configuration\" do\n it \"should persist resettable in redis\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], resettable: false)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.resettable).to be_falsey\n end\n\n describe \"#metadata\" do\n let(:experiment) { Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }\n let(:meta) { { a: \"b\" } }\n\n before do\n experiment.save\n end\n\n it \"should delete the key when metadata is removed\" do\n experiment.metadata = nil\n experiment.save\n\n expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey\n end\n\n context \"simple hash\" do\n let(:meta) { { \"basket\" => \"a\", \"cart\" => \"b\" } }\n\n it \"should persist metadata in redis\" do\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.metadata).to eq(meta)\n end\n end\n\n context \"nested hash\" do\n let(:meta) { { \"basket\" => { \"one\" => \"two\" }, \"cart\" => \"b\" } }\n it \"should persist metadata in redis\" do\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.metadata).to eq(meta)\n end\n end\n end\n\n it \"should persist algorithm in redis\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n\n it \"should persist a new experiment in redis, that does not exist in the configuration file\" do\n experiment = Split::Experiment.new(\"foobar\", alternatives: [\"tra\", \"la\"], algorithm: Split::Algorithms::Whiplash)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"foobar\")\n expect(e).to eq(experiment)\n expect(e.alternatives.collect { |a| a.name }).to eq([\"tra\", \"la\"])\n end\n end\n\n describe \"deleting\" do\n it \"should delete itself\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [ \"Basket\", \"Cart\"])\n experiment.save\n\n experiment.delete\n expect(Split.redis.exists?(\"link_color\")).to be false\n expect(Split::ExperimentCatalog.find(\"link_color\")).to be_nil\n end\n\n it \"should increment the version\" do\n expect(experiment.version).to eq(0)\n experiment.delete\n expect(experiment.version).to eq(1)\n end\n\n it \"should call the on_experiment_delete hook\" do\n expect(Split.configuration.on_experiment_delete).to receive(:call)\n experiment.delete\n end\n\n it \"should call the on_before_experiment_delete hook\" do\n expect(Split.configuration.on_before_experiment_delete).to receive(:call)\n experiment.delete\n end\n\n it \"should reset the start time if the experiment should be manually started\" do\n Split.configuration.start_manually = true\n experiment.start\n experiment.delete\n expect(experiment.start_time).to be_nil\n end\n\n it \"should default cohorting back to false\" do\n experiment.disable_cohorting\n expect(experiment.cohorting_disabled?).to eq(true)\n experiment.delete\n expect(experiment.cohorting_disabled?).to eq(false)\n end\n end\n\n describe \"winner\" do\n it \"should have no winner initially\" do\n expect(experiment.winner).to be_nil\n end\n end\n\n describe \"winner=\" do\n it \"should allow you to specify a winner\" do\n experiment.save\n experiment.winner = \"red\"\n expect(experiment.winner.name).to eq(\"red\")\n end\n\n it \"should call the on_experiment_winner_choose hook\" do\n expect(Split.configuration.on_experiment_winner_choose).to receive(:call)\n experiment.winner = \"green\"\n end\n\n context \"when has_winner state is memoized\" do\n before { expect(experiment).to_not have_winner }\n\n it \"should keep has_winner state consistent\" do\n experiment.winner = \"red\"\n expect(experiment).to have_winner\n end\n end\n end\n\n describe \"reset_winner\" do\n before { experiment.winner = \"green\" }\n\n it \"should reset the winner\" do\n experiment.reset_winner\n expect(experiment.winner).to be_nil\n end\n\n context \"when has_winner state is memoized\" do\n before { expect(experiment).to have_winner }\n\n it \"should keep has_winner state consistent\" do\n experiment.reset_winner\n expect(experiment).to_not have_winner\n end\n end\n end\n\n describe \"has_winner?\" do\n context \"with winner\" do\n before { experiment.winner = \"red\" }\n\n it \"returns true\" do\n expect(experiment).to have_winner\n end\n end\n\n context \"without winner\" do\n it \"returns false\" do\n expect(experiment).to_not have_winner\n end\n end\n\n it \"memoizes has_winner state\" do\n expect(experiment).to receive(:winner).once\n expect(experiment).to_not have_winner\n expect(experiment).to_not have_winner\n end\n end\n\n describe \"reset\" do\n let(:reset_manually) { false }\n\n before do\n allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)\n experiment.save\n green.increment_participation\n green.increment_participation\n end\n\n it \"should reset all alternatives\" do\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n experiment.reset\n\n expect(green.participant_count).to eq(0)\n expect(green.completed_count).to eq(0)\n end\n\n it \"should reset the winner\" do\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n experiment.reset\n\n expect(experiment.winner).to be_nil\n end\n\n it \"should increment the version\" do\n expect(experiment.version).to eq(0)\n experiment.reset\n expect(experiment.version).to eq(1)\n end\n\n it \"should call the on_experiment_reset hook\" do\n expect(Split.configuration.on_experiment_reset).to receive(:call)\n experiment.reset\n end\n\n it \"should call the on_before_experiment_reset hook\" do\n expect(Split.configuration.on_before_experiment_reset).to receive(:call)\n experiment.reset\n end\n end\n\n describe \"algorithm\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"red\", \"green\") }\n\n it \"should use the default algorithm if none is specified\" do\n expect(experiment.algorithm).to eq(Split.configuration.algorithm)\n end\n\n it \"should use the user specified algorithm for this experiment if specified\" do\n experiment.algorithm = Split::Algorithms::Whiplash\n expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n end\n\n describe \"#next_alternative\" do\n context \"with multiple alternatives\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"red\", \"green\") }\n\n context \"with winner\" do\n it \"should always return the winner\" do\n green = Split::Alternative.new(\"green\", \"link_color\")\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n end\n end\n\n context \"without winner\" do\n it \"should use the specified algorithm\" do\n experiment.algorithm = Split::Algorithms::Whiplash\n expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new(\"green\", \"link_color\"))\n expect(experiment.next_alternative.name).to eq(\"green\")\n end\n end\n end\n\n context \"with single alternative\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\") }\n\n it \"should always return the only alternative\" do\n expect(experiment.next_alternative.name).to eq(\"blue\")\n expect(experiment.next_alternative.name).to eq(\"blue\")\n end\n end\n end\n\n describe \"#cohorting_disabled?\" do\n it \"returns false when nothing has been configured\" do\n expect(experiment.cohorting_disabled?).to eq false\n end\n\n it \"returns true when enable_cohorting is performed\" do\n experiment.enable_cohorting\n expect(experiment.cohorting_disabled?).to eq false\n end\n\n it \"returns false when nothing has been configured\" do\n experiment.disable_cohorting\n expect(experiment.cohorting_disabled?).to eq true\n end\n end\n\n describe \"changing an existing experiment\" do\n def same_but_different_alternative\n Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"yellow\", \"orange\")\n end\n\n it \"should reset an experiment if it is loaded with different alternatives\" do\n experiment.save\n blue.participant_count = 5\n same_experiment = same_but_different_alternative\n expect(same_experiment.alternatives.map(&:name)).to eq([\"blue\", \"yellow\", \"orange\"])\n expect(blue.participant_count).to eq(0)\n end\n\n it \"should only reset once\" do\n experiment.save\n expect(experiment.version).to eq(0)\n same_experiment = same_but_different_alternative\n expect(same_experiment.version).to eq(1)\n same_experiment_again = same_but_different_alternative\n expect(same_experiment_again.version).to eq(1)\n end\n\n context \"when metadata is changed\" do\n it \"should increase version\" do\n experiment.save\n experiment.metadata = { \"foo\" => \"bar\" }\n\n expect { experiment.save }.to change { experiment.version }.by(1)\n end\n\n it \"does not increase version\" do\n experiment.metadata = nil\n experiment.save\n expect { experiment.save }.to change { experiment.version }.by(0)\n end\n end\n\n context \"when experiment configuration is changed\" do\n let(:reset_manually) { false }\n\n before do\n experiment.save\n allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)\n green.increment_participation\n green.increment_participation\n experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),\n goals: %w(purchase))\n experiment.save\n end\n\n it \"resets all alternatives\" do\n expect(green.participant_count).to eq(0)\n expect(green.completed_count).to eq(0)\n end\n\n context \"when reset_manually is set\" do\n let(:reset_manually) { true }\n\n it \"does not reset alternatives\" do\n expect(green.participant_count).to eq(2)\n expect(green.completed_count).to eq(0)\n end\n end\n end\n end\n\n describe \"alternatives passed as non-strings\" do\n it \"should throw an exception if an alternative is passed that is not a string\" do\n expect { Split::ExperimentCatalog.find_or_create(\"link_color\", :blue, :red) }.to raise_error(ArgumentError)\n expect { Split::ExperimentCatalog.find_or_create(\"link_enabled\", true, false) }.to raise_error(ArgumentError)\n end\n end\n\n describe \"specifying weights\" do\n let(:experiment_with_weight) {\n Split::ExperimentCatalog.find_or_create(\"link_color\", { \"blue\" => 1 }, { \"red\" => 2 })\n }\n\n it \"should work for a new experiment\" do\n expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])\n end\n\n it \"should work for an existing experiment\" do\n experiment.save\n expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])\n end\n end\n\n describe \"specifying goals\" do\n let(:experiment) {\n new_experiment([\"purchase\"])\n }\n\n context \"saving experiment\" do\n let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ \"link_color\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\") }\n\n before { experiment.save }\n\n it \"can find existing experiment\" do\n expect(Split::ExperimentCatalog.find(\"link_color\").name).to eq(\"link_color\")\n end\n\n it \"should reset an experiment if it is loaded with different goals\" do\n same_but_different_goals\n expect(Split::ExperimentCatalog.find(\"link_color\").goals).to eq([\"purchase\", \"refund\"])\n end\n end\n\n it \"should have goals\" do\n expect(experiment.goals).to eq([\"purchase\"])\n end\n\n context \"find or create experiment\" do\n it \"should have correct goals\" do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n expect(experiment.goals).to eq([\"purchase\", \"refund\"])\n experiment = Split::ExperimentCatalog.find_or_create(\"link_color3\", \"blue\", \"red\", \"green\")\n expect(experiment.goals).to eq([])\n end\n end\n end\n\n describe \"beta probability calculation\" do\n it \"should return a hash with the probability of each alternative being the best\" do\n experiment = Split::ExperimentCatalog.find_or_create(\"mathematicians\", \"bernoulli\", \"poisson\", \"lagrange\")\n experiment.calc_winning_alternatives\n expect(experiment.alternative_probabilities).not_to be_nil\n end\n\n it \"should return between 46% and 54% probability for an experiment with 2 alternatives and no data\" do\n experiment = Split::ExperimentCatalog.find_or_create(\"scientists\", \"einstein\", \"bohr\")\n experiment.calc_winning_alternatives\n expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)\n end\n\n it \"should calculate the probability of being the winning alternative separately for each goal\", skip: true do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n goal1 = experiment.goals[0]\n goal2 = experiment.goals[1]\n experiment.alternatives.each do |alternative|\n alternative.participant_count = 50\n alternative.set_completed_count(10, goal1)\n alternative.set_completed_count(15+rand(30), goal2)\n end\n experiment.calc_winning_alternatives\n alt = experiment.alternatives[0]\n p_goal1 = alt.p_winner(goal1)\n p_goal2 = alt.p_winner(goal2)\n expect(p_goal1).not_to be_within(0.04).of(p_goal2)\n end\n\n it \"should return nil and not re-calculate probabilities if they have already been calculated today\" do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n expect(experiment.calc_winning_alternatives).not_to be nil\n expect(experiment.calc_winning_alternatives).to be nil\n end\n end\nend\n\n If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives\n @@ -122,5 +122,17 @@ describe Split::Experiment do\n experiment.next_alternative.name.should eql('green')\n end\n end\n-end\n \n+ describe 'changing an existing experiment' do\n+ it \"should reset an experiment if it is loaded with different alternatives\" do\n+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green')\n+ blue = Split::Alternative.find('blue', 'link_color')\n+ blue.participant_count = 5\n+ blue.save\n+ same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange')\n+ same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange'])\n+ new_blue = Split::Alternative.find('blue', 'link_color')\n+ new_blue.participant_count.should eql(0)\n+ end\n+ end\n+end\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":13,"string":"13"},"commit_subject":{"kind":"string","value":"If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".rb"},"lang":{"kind":"string","value":"rb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676490,"cells":{"id":{"kind":"string","value":"10072140"},"text":{"kind":"string","value":" experiment_spec.rb\n # frozen_string_literal: true\n\nrequire \"spec_helper\"\nrequire \"time\"\n\ndescribe Split::Experiment do\n def new_experiment(goals = [])\n Split::Experiment.new(\"link_color\", alternatives: [\"blue\", \"red\", \"green\"], goals: goals)\n end\n\n def alternative(color)\n Split::Alternative.new(color, \"link_color\")\n end\n\n let(:experiment) { new_experiment }\n\n let(:blue) { alternative(\"blue\") }\n let(:green) { alternative(\"green\") }\n\n context \"with an experiment\" do\n let(:experiment) { Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"]) }\n\n it \"should have a name\" do\n expect(experiment.name).to eq(\"basket_text\")\n end\n\n it \"should have alternatives\" do\n expect(experiment.alternatives.length).to be 2\n end\n\n it \"should have alternatives with correct names\" do\n expect(experiment.alternatives.collect { |a| a.name }).to eq([\"Basket\", \"Cart\"])\n end\n\n it \"should be resettable by default\" do\n expect(experiment.resettable).to be_truthy\n end\n\n it \"should save to redis\" do\n experiment.save\n expect(Split.redis.exists?(\"basket_text\")).to be true\n end\n\n it \"should save the start time to redis\" do\n experiment_start_time = Time.at(1372167761)\n expect(Time).to receive(:now).and_return(experiment_start_time)\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to eq(experiment_start_time)\n end\n\n it \"should not save the start time to redis when start_manually is enabled\" do\n expect(Split.configuration).to receive(:start_manually).and_return(true)\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to be_nil\n end\n\n it \"should save the selected algorithm to redis\" do\n experiment_algorithm = Split::Algorithms::Whiplash\n experiment.algorithm = experiment_algorithm\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").algorithm).to eq(experiment_algorithm)\n end\n\n it \"should handle having a start time stored as a string\" do\n experiment_start_time = Time.parse(\"Sat Mar 03 14:01:03\")\n expect(Time).to receive(:now).twice.and_return(experiment_start_time)\n experiment.save\n Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to eq(experiment_start_time)\n end\n\n it \"should handle not having a start time\" do\n experiment_start_time = Time.parse(\"Sat Mar 03 14:01:03\")\n expect(Time).to receive(:now).and_return(experiment_start_time)\n experiment.save\n\n Split.redis.hdel(:experiment_start_times, experiment.name)\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to be_nil\n end\n\n it \"should not create duplicates when saving multiple times\" do\n experiment.save\n experiment.save\n expect(Split.redis.exists?(\"basket_text\")).to be true\n expect(Split.redis.lrange(\"basket_text\", 0, -1)).to eq(['{\"Basket\":1}', '{\"Cart\":1}'])\n end\n\n describe \"new record?\" do\n it \"should know if it hasn't been saved yet\" do\n expect(experiment.new_record?).to be_truthy\n end\n\n it \"should know if it has been saved yet\" do\n experiment.save\n expect(experiment.new_record?).to be_falsey\n end\n end\n\n describe \"control\" do\n it \"should be the first alternative\" do\n experiment.save\n expect(experiment.control.name).to eq(\"Basket\")\n end\n end\n end\n\n describe \"initialization\" do\n it \"should set the algorithm when passed as an option to the initializer\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash)\n expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n\n it \"should be possible to make an experiment not resettable\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], resettable: false)\n expect(experiment.resettable).to be_falsey\n end\n experiment.next_alternative.name.should eql('green')\n end\n end\nend\n\n end\n\n describe \"persistent configuration\" do\n it \"should persist resettable in redis\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], resettable: false)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.resettable).to be_falsey\n end\n\n describe \"#metadata\" do\n let(:experiment) { Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }\n let(:meta) { { a: \"b\" } }\n\n before do\n experiment.save\n end\n\n it \"should delete the key when metadata is removed\" do\n experiment.metadata = nil\n experiment.save\n\n expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey\n end\n\n context \"simple hash\" do\n let(:meta) { { \"basket\" => \"a\", \"cart\" => \"b\" } }\n\n it \"should persist metadata in redis\" do\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.metadata).to eq(meta)\n end\n end\n\n context \"nested hash\" do\n let(:meta) { { \"basket\" => { \"one\" => \"two\" }, \"cart\" => \"b\" } }\n it \"should persist metadata in redis\" do\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.metadata).to eq(meta)\n end\n end\n end\n\n it \"should persist algorithm in redis\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n\n it \"should persist a new experiment in redis, that does not exist in the configuration file\" do\n experiment = Split::Experiment.new(\"foobar\", alternatives: [\"tra\", \"la\"], algorithm: Split::Algorithms::Whiplash)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"foobar\")\n expect(e).to eq(experiment)\n expect(e.alternatives.collect { |a| a.name }).to eq([\"tra\", \"la\"])\n end\n end\n\n describe \"deleting\" do\n it \"should delete itself\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [ \"Basket\", \"Cart\"])\n experiment.save\n\n experiment.delete\n expect(Split.redis.exists?(\"link_color\")).to be false\n expect(Split::ExperimentCatalog.find(\"link_color\")).to be_nil\n end\n\n it \"should increment the version\" do\n expect(experiment.version).to eq(0)\n experiment.delete\n expect(experiment.version).to eq(1)\n end\n\n it \"should call the on_experiment_delete hook\" do\n expect(Split.configuration.on_experiment_delete).to receive(:call)\n experiment.delete\n end\n\n it \"should call the on_before_experiment_delete hook\" do\n expect(Split.configuration.on_before_experiment_delete).to receive(:call)\n experiment.delete\n end\n\n it \"should reset the start time if the experiment should be manually started\" do\n Split.configuration.start_manually = true\n experiment.start\n experiment.delete\n expect(experiment.start_time).to be_nil\n end\n\n it \"should default cohorting back to false\" do\n experiment.disable_cohorting\n expect(experiment.cohorting_disabled?).to eq(true)\n experiment.delete\n expect(experiment.cohorting_disabled?).to eq(false)\n end\n end\n\n describe \"winner\" do\n it \"should have no winner initially\" do\n expect(experiment.winner).to be_nil\n end\n end\n\n describe \"winner=\" do\n it \"should allow you to specify a winner\" do\n experiment.save\n experiment.winner = \"red\"\n expect(experiment.winner.name).to eq(\"red\")\n end\n\n it \"should call the on_experiment_winner_choose hook\" do\n expect(Split.configuration.on_experiment_winner_choose).to receive(:call)\n experiment.winner = \"green\"\n end\n\n context \"when has_winner state is memoized\" do\n before { expect(experiment).to_not have_winner }\n\n it \"should keep has_winner state consistent\" do\n experiment.winner = \"red\"\n expect(experiment).to have_winner\n end\n end\n end\n\n describe \"reset_winner\" do\n before { experiment.winner = \"green\" }\n\n it \"should reset the winner\" do\n experiment.reset_winner\n expect(experiment.winner).to be_nil\n end\n\n context \"when has_winner state is memoized\" do\n before { expect(experiment).to have_winner }\n\n it \"should keep has_winner state consistent\" do\n experiment.reset_winner\n expect(experiment).to_not have_winner\n end\n end\n end\n\n describe \"has_winner?\" do\n context \"with winner\" do\n before { experiment.winner = \"red\" }\n\n it \"returns true\" do\n expect(experiment).to have_winner\n end\n end\n\n context \"without winner\" do\n it \"returns false\" do\n expect(experiment).to_not have_winner\n end\n end\n\n it \"memoizes has_winner state\" do\n expect(experiment).to receive(:winner).once\n expect(experiment).to_not have_winner\n expect(experiment).to_not have_winner\n end\n end\n\n describe \"reset\" do\n let(:reset_manually) { false }\n\n before do\n allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)\n experiment.save\n green.increment_participation\n green.increment_participation\n end\n\n it \"should reset all alternatives\" do\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n experiment.reset\n\n expect(green.participant_count).to eq(0)\n expect(green.completed_count).to eq(0)\n end\n\n it \"should reset the winner\" do\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n experiment.reset\n\n expect(experiment.winner).to be_nil\n end\n\n it \"should increment the version\" do\n expect(experiment.version).to eq(0)\n experiment.reset\n expect(experiment.version).to eq(1)\n end\n\n it \"should call the on_experiment_reset hook\" do\n expect(Split.configuration.on_experiment_reset).to receive(:call)\n experiment.reset\n end\n\n it \"should call the on_before_experiment_reset hook\" do\n expect(Split.configuration.on_before_experiment_reset).to receive(:call)\n experiment.reset\n end\n end\n\n describe \"algorithm\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"red\", \"green\") }\n\n it \"should use the default algorithm if none is specified\" do\n expect(experiment.algorithm).to eq(Split.configuration.algorithm)\n end\n\n it \"should use the user specified algorithm for this experiment if specified\" do\n experiment.algorithm = Split::Algorithms::Whiplash\n expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n end\n\n describe \"#next_alternative\" do\n context \"with multiple alternatives\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"red\", \"green\") }\n\n context \"with winner\" do\n it \"should always return the winner\" do\n green = Split::Alternative.new(\"green\", \"link_color\")\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n end\n end\n\n context \"without winner\" do\n it \"should use the specified algorithm\" do\n experiment.algorithm = Split::Algorithms::Whiplash\n expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new(\"green\", \"link_color\"))\n expect(experiment.next_alternative.name).to eq(\"green\")\n end\n end\n end\n\n context \"with single alternative\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\") }\n\n it \"should always return the only alternative\" do\n expect(experiment.next_alternative.name).to eq(\"blue\")\n expect(experiment.next_alternative.name).to eq(\"blue\")\n end\n end\n end\n\n describe \"#cohorting_disabled?\" do\n it \"returns false when nothing has been configured\" do\n expect(experiment.cohorting_disabled?).to eq false\n end\n\n it \"returns true when enable_cohorting is performed\" do\n experiment.enable_cohorting\n expect(experiment.cohorting_disabled?).to eq false\n end\n\n it \"returns false when nothing has been configured\" do\n experiment.disable_cohorting\n expect(experiment.cohorting_disabled?).to eq true\n end\n end\n\n describe \"changing an existing experiment\" do\n def same_but_different_alternative\n Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"yellow\", \"orange\")\n end\n\n it \"should reset an experiment if it is loaded with different alternatives\" do\n experiment.save\n blue.participant_count = 5\n same_experiment = same_but_different_alternative\n expect(same_experiment.alternatives.map(&:name)).to eq([\"blue\", \"yellow\", \"orange\"])\n expect(blue.participant_count).to eq(0)\n end\n\n it \"should only reset once\" do\n experiment.save\n expect(experiment.version).to eq(0)\n same_experiment = same_but_different_alternative\n expect(same_experiment.version).to eq(1)\n same_experiment_again = same_but_different_alternative\n expect(same_experiment_again.version).to eq(1)\n end\n\n context \"when metadata is changed\" do\n it \"should increase version\" do\n experiment.save\n experiment.metadata = { \"foo\" => \"bar\" }\n\n expect { experiment.save }.to change { experiment.version }.by(1)\n end\n\n it \"does not increase version\" do\n experiment.metadata = nil\n experiment.save\n expect { experiment.save }.to change { experiment.version }.by(0)\n end\n end\n\n context \"when experiment configuration is changed\" do\n let(:reset_manually) { false }\n\n before do\n experiment.save\n allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)\n green.increment_participation\n green.increment_participation\n experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),\n goals: %w(purchase))\n experiment.save\n end\n\n it \"resets all alternatives\" do\n expect(green.participant_count).to eq(0)\n expect(green.completed_count).to eq(0)\n end\n\n context \"when reset_manually is set\" do\n let(:reset_manually) { true }\n\n it \"does not reset alternatives\" do\n expect(green.participant_count).to eq(2)\n expect(green.completed_count).to eq(0)\n end\n end\n end\n end\n\n describe \"alternatives passed as non-strings\" do\n it \"should throw an exception if an alternative is passed that is not a string\" do\n expect { Split::ExperimentCatalog.find_or_create(\"link_color\", :blue, :red) }.to raise_error(ArgumentError)\n expect { Split::ExperimentCatalog.find_or_create(\"link_enabled\", true, false) }.to raise_error(ArgumentError)\n end\n end\n\n describe \"specifying weights\" do\n let(:experiment_with_weight) {\n Split::ExperimentCatalog.find_or_create(\"link_color\", { \"blue\" => 1 }, { \"red\" => 2 })\n }\n\n it \"should work for a new experiment\" do\n expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])\n end\n\n it \"should work for an existing experiment\" do\n experiment.save\n expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])\n end\n end\n\n describe \"specifying goals\" do\n let(:experiment) {\n new_experiment([\"purchase\"])\n }\n\n context \"saving experiment\" do\n let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ \"link_color\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\") }\n\n before { experiment.save }\n\n it \"can find existing experiment\" do\n expect(Split::ExperimentCatalog.find(\"link_color\").name).to eq(\"link_color\")\n end\n\n it \"should reset an experiment if it is loaded with different goals\" do\n same_but_different_goals\n expect(Split::ExperimentCatalog.find(\"link_color\").goals).to eq([\"purchase\", \"refund\"])\n end\n end\n\n it \"should have goals\" do\n expect(experiment.goals).to eq([\"purchase\"])\n end\n\n context \"find or create experiment\" do\n it \"should have correct goals\" do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n expect(experiment.goals).to eq([\"purchase\", \"refund\"])\n experiment = Split::ExperimentCatalog.find_or_create(\"link_color3\", \"blue\", \"red\", \"green\")\n expect(experiment.goals).to eq([])\n end\n end\n end\n\n describe \"beta probability calculation\" do\n it \"should return a hash with the probability of each alternative being the best\" do\n experiment = Split::ExperimentCatalog.find_or_create(\"mathematicians\", \"bernoulli\", \"poisson\", \"lagrange\")\n experiment.calc_winning_alternatives\n expect(experiment.alternative_probabilities).not_to be_nil\n end\n\n it \"should return between 46% and 54% probability for an experiment with 2 alternatives and no data\" do\n experiment = Split::ExperimentCatalog.find_or_create(\"scientists\", \"einstein\", \"bohr\")\n experiment.calc_winning_alternatives\n expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)\n end\n\n it \"should calculate the probability of being the winning alternative separately for each goal\", skip: true do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n goal1 = experiment.goals[0]\n goal2 = experiment.goals[1]\n experiment.alternatives.each do |alternative|\n alternative.participant_count = 50\n alternative.set_completed_count(10, goal1)\n alternative.set_completed_count(15+rand(30), goal2)\n end\n experiment.calc_winning_alternatives\n alt = experiment.alternatives[0]\n p_goal1 = alt.p_winner(goal1)\n p_goal2 = alt.p_winner(goal2)\n expect(p_goal1).not_to be_within(0.04).of(p_goal2)\n end\n\n it \"should return nil and not re-calculate probabilities if they have already been calculated today\" do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n expect(experiment.calc_winning_alternatives).not_to be nil\n expect(experiment.calc_winning_alternatives).to be nil\n end\n end\nend\n\n If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives\n @@ -122,5 +122,17 @@ describe Split::Experiment do\n experiment.next_alternative.name.should eql('green')\n end\n end\n-end\n \n+ describe 'changing an existing experiment' do\n+ it \"should reset an experiment if it is loaded with different alternatives\" do\n+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green')\n+ blue = Split::Alternative.find('blue', 'link_color')\n+ blue.participant_count = 5\n+ blue.save\n+ same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange')\n+ same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange'])\n+ new_blue = Split::Alternative.find('blue', 'link_color')\n+ new_blue.participant_count.should eql(0)\n+ end\n+ end\n+end\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":13,"string":"13"},"commit_subject":{"kind":"string","value":"If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".rb"},"lang":{"kind":"string","value":"rb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676491,"cells":{"id":{"kind":"string","value":"10072141"},"text":{"kind":"string","value":" experiment_spec.rb\n # frozen_string_literal: true\n\nrequire \"spec_helper\"\nrequire \"time\"\n\ndescribe Split::Experiment do\n def new_experiment(goals = [])\n Split::Experiment.new(\"link_color\", alternatives: [\"blue\", \"red\", \"green\"], goals: goals)\n end\n\n def alternative(color)\n Split::Alternative.new(color, \"link_color\")\n end\n\n let(:experiment) { new_experiment }\n\n let(:blue) { alternative(\"blue\") }\n let(:green) { alternative(\"green\") }\n\n context \"with an experiment\" do\n let(:experiment) { Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"]) }\n\n it \"should have a name\" do\n expect(experiment.name).to eq(\"basket_text\")\n end\n\n it \"should have alternatives\" do\n expect(experiment.alternatives.length).to be 2\n end\n\n it \"should have alternatives with correct names\" do\n expect(experiment.alternatives.collect { |a| a.name }).to eq([\"Basket\", \"Cart\"])\n end\n\n it \"should be resettable by default\" do\n expect(experiment.resettable).to be_truthy\n end\n\n it \"should save to redis\" do\n experiment.save\n expect(Split.redis.exists?(\"basket_text\")).to be true\n end\n\n it \"should save the start time to redis\" do\n experiment_start_time = Time.at(1372167761)\n expect(Time).to receive(:now).and_return(experiment_start_time)\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to eq(experiment_start_time)\n end\n\n it \"should not save the start time to redis when start_manually is enabled\" do\n expect(Split.configuration).to receive(:start_manually).and_return(true)\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to be_nil\n end\n\n it \"should save the selected algorithm to redis\" do\n experiment_algorithm = Split::Algorithms::Whiplash\n experiment.algorithm = experiment_algorithm\n experiment.save\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").algorithm).to eq(experiment_algorithm)\n end\n\n it \"should handle having a start time stored as a string\" do\n experiment_start_time = Time.parse(\"Sat Mar 03 14:01:03\")\n expect(Time).to receive(:now).twice.and_return(experiment_start_time)\n experiment.save\n Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s)\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to eq(experiment_start_time)\n end\n\n it \"should handle not having a start time\" do\n experiment_start_time = Time.parse(\"Sat Mar 03 14:01:03\")\n expect(Time).to receive(:now).and_return(experiment_start_time)\n experiment.save\n\n Split.redis.hdel(:experiment_start_times, experiment.name)\n\n expect(Split::ExperimentCatalog.find(\"basket_text\").start_time).to be_nil\n end\n\n it \"should not create duplicates when saving multiple times\" do\n experiment.save\n experiment.save\n expect(Split.redis.exists?(\"basket_text\")).to be true\n expect(Split.redis.lrange(\"basket_text\", 0, -1)).to eq(['{\"Basket\":1}', '{\"Cart\":1}'])\n end\n\n describe \"new record?\" do\n it \"should know if it hasn't been saved yet\" do\n expect(experiment.new_record?).to be_truthy\n end\n\n it \"should know if it has been saved yet\" do\n experiment.save\n expect(experiment.new_record?).to be_falsey\n end\n end\n\n describe \"control\" do\n it \"should be the first alternative\" do\n experiment.save\n expect(experiment.control.name).to eq(\"Basket\")\n end\n end\n end\n\n describe \"initialization\" do\n it \"should set the algorithm when passed as an option to the initializer\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash)\n expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n\n it \"should be possible to make an experiment not resettable\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], resettable: false)\n expect(experiment.resettable).to be_falsey\n end\n experiment.next_alternative.name.should eql('green')\n end\n end\nend\n\n end\n\n describe \"persistent configuration\" do\n it \"should persist resettable in redis\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], resettable: false)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.resettable).to be_falsey\n end\n\n describe \"#metadata\" do\n let(:experiment) { Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash, metadata: meta) }\n let(:meta) { { a: \"b\" } }\n\n before do\n experiment.save\n end\n\n it \"should delete the key when metadata is removed\" do\n experiment.metadata = nil\n experiment.save\n\n expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey\n end\n\n context \"simple hash\" do\n let(:meta) { { \"basket\" => \"a\", \"cart\" => \"b\" } }\n\n it \"should persist metadata in redis\" do\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.metadata).to eq(meta)\n end\n end\n\n context \"nested hash\" do\n let(:meta) { { \"basket\" => { \"one\" => \"two\" }, \"cart\" => \"b\" } }\n it \"should persist metadata in redis\" do\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.metadata).to eq(meta)\n end\n end\n end\n\n it \"should persist algorithm in redis\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [\"Basket\", \"Cart\"], algorithm: Split::Algorithms::Whiplash)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"basket_text\")\n expect(e).to eq(experiment)\n expect(e.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n\n it \"should persist a new experiment in redis, that does not exist in the configuration file\" do\n experiment = Split::Experiment.new(\"foobar\", alternatives: [\"tra\", \"la\"], algorithm: Split::Algorithms::Whiplash)\n experiment.save\n\n e = Split::ExperimentCatalog.find(\"foobar\")\n expect(e).to eq(experiment)\n expect(e.alternatives.collect { |a| a.name }).to eq([\"tra\", \"la\"])\n end\n end\n\n describe \"deleting\" do\n it \"should delete itself\" do\n experiment = Split::Experiment.new(\"basket_text\", alternatives: [ \"Basket\", \"Cart\"])\n experiment.save\n\n experiment.delete\n expect(Split.redis.exists?(\"link_color\")).to be false\n expect(Split::ExperimentCatalog.find(\"link_color\")).to be_nil\n end\n\n it \"should increment the version\" do\n expect(experiment.version).to eq(0)\n experiment.delete\n expect(experiment.version).to eq(1)\n end\n\n it \"should call the on_experiment_delete hook\" do\n expect(Split.configuration.on_experiment_delete).to receive(:call)\n experiment.delete\n end\n\n it \"should call the on_before_experiment_delete hook\" do\n expect(Split.configuration.on_before_experiment_delete).to receive(:call)\n experiment.delete\n end\n\n it \"should reset the start time if the experiment should be manually started\" do\n Split.configuration.start_manually = true\n experiment.start\n experiment.delete\n expect(experiment.start_time).to be_nil\n end\n\n it \"should default cohorting back to false\" do\n experiment.disable_cohorting\n expect(experiment.cohorting_disabled?).to eq(true)\n experiment.delete\n expect(experiment.cohorting_disabled?).to eq(false)\n end\n end\n\n describe \"winner\" do\n it \"should have no winner initially\" do\n expect(experiment.winner).to be_nil\n end\n end\n\n describe \"winner=\" do\n it \"should allow you to specify a winner\" do\n experiment.save\n experiment.winner = \"red\"\n expect(experiment.winner.name).to eq(\"red\")\n end\n\n it \"should call the on_experiment_winner_choose hook\" do\n expect(Split.configuration.on_experiment_winner_choose).to receive(:call)\n experiment.winner = \"green\"\n end\n\n context \"when has_winner state is memoized\" do\n before { expect(experiment).to_not have_winner }\n\n it \"should keep has_winner state consistent\" do\n experiment.winner = \"red\"\n expect(experiment).to have_winner\n end\n end\n end\n\n describe \"reset_winner\" do\n before { experiment.winner = \"green\" }\n\n it \"should reset the winner\" do\n experiment.reset_winner\n expect(experiment.winner).to be_nil\n end\n\n context \"when has_winner state is memoized\" do\n before { expect(experiment).to have_winner }\n\n it \"should keep has_winner state consistent\" do\n experiment.reset_winner\n expect(experiment).to_not have_winner\n end\n end\n end\n\n describe \"has_winner?\" do\n context \"with winner\" do\n before { experiment.winner = \"red\" }\n\n it \"returns true\" do\n expect(experiment).to have_winner\n end\n end\n\n context \"without winner\" do\n it \"returns false\" do\n expect(experiment).to_not have_winner\n end\n end\n\n it \"memoizes has_winner state\" do\n expect(experiment).to receive(:winner).once\n expect(experiment).to_not have_winner\n expect(experiment).to_not have_winner\n end\n end\n\n describe \"reset\" do\n let(:reset_manually) { false }\n\n before do\n allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)\n experiment.save\n green.increment_participation\n green.increment_participation\n end\n\n it \"should reset all alternatives\" do\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n experiment.reset\n\n expect(green.participant_count).to eq(0)\n expect(green.completed_count).to eq(0)\n end\n\n it \"should reset the winner\" do\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n experiment.reset\n\n expect(experiment.winner).to be_nil\n end\n\n it \"should increment the version\" do\n expect(experiment.version).to eq(0)\n experiment.reset\n expect(experiment.version).to eq(1)\n end\n\n it \"should call the on_experiment_reset hook\" do\n expect(Split.configuration.on_experiment_reset).to receive(:call)\n experiment.reset\n end\n\n it \"should call the on_before_experiment_reset hook\" do\n expect(Split.configuration.on_before_experiment_reset).to receive(:call)\n experiment.reset\n end\n end\n\n describe \"algorithm\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"red\", \"green\") }\n\n it \"should use the default algorithm if none is specified\" do\n expect(experiment.algorithm).to eq(Split.configuration.algorithm)\n end\n\n it \"should use the user specified algorithm for this experiment if specified\" do\n experiment.algorithm = Split::Algorithms::Whiplash\n expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash)\n end\n end\n\n describe \"#next_alternative\" do\n context \"with multiple alternatives\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"red\", \"green\") }\n\n context \"with winner\" do\n it \"should always return the winner\" do\n green = Split::Alternative.new(\"green\", \"link_color\")\n experiment.winner = \"green\"\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n green.increment_participation\n\n expect(experiment.next_alternative.name).to eq(\"green\")\n end\n end\n\n context \"without winner\" do\n it \"should use the specified algorithm\" do\n experiment.algorithm = Split::Algorithms::Whiplash\n expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new(\"green\", \"link_color\"))\n expect(experiment.next_alternative.name).to eq(\"green\")\n end\n end\n end\n\n context \"with single alternative\" do\n let(:experiment) { Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\") }\n\n it \"should always return the only alternative\" do\n expect(experiment.next_alternative.name).to eq(\"blue\")\n expect(experiment.next_alternative.name).to eq(\"blue\")\n end\n end\n end\n\n describe \"#cohorting_disabled?\" do\n it \"returns false when nothing has been configured\" do\n expect(experiment.cohorting_disabled?).to eq false\n end\n\n it \"returns true when enable_cohorting is performed\" do\n experiment.enable_cohorting\n expect(experiment.cohorting_disabled?).to eq false\n end\n\n it \"returns false when nothing has been configured\" do\n experiment.disable_cohorting\n expect(experiment.cohorting_disabled?).to eq true\n end\n end\n\n describe \"changing an existing experiment\" do\n def same_but_different_alternative\n Split::ExperimentCatalog.find_or_create(\"link_color\", \"blue\", \"yellow\", \"orange\")\n end\n\n it \"should reset an experiment if it is loaded with different alternatives\" do\n experiment.save\n blue.participant_count = 5\n same_experiment = same_but_different_alternative\n expect(same_experiment.alternatives.map(&:name)).to eq([\"blue\", \"yellow\", \"orange\"])\n expect(blue.participant_count).to eq(0)\n end\n\n it \"should only reset once\" do\n experiment.save\n expect(experiment.version).to eq(0)\n same_experiment = same_but_different_alternative\n expect(same_experiment.version).to eq(1)\n same_experiment_again = same_but_different_alternative\n expect(same_experiment_again.version).to eq(1)\n end\n\n context \"when metadata is changed\" do\n it \"should increase version\" do\n experiment.save\n experiment.metadata = { \"foo\" => \"bar\" }\n\n expect { experiment.save }.to change { experiment.version }.by(1)\n end\n\n it \"does not increase version\" do\n experiment.metadata = nil\n experiment.save\n expect { experiment.save }.to change { experiment.version }.by(0)\n end\n end\n\n context \"when experiment configuration is changed\" do\n let(:reset_manually) { false }\n\n before do\n experiment.save\n allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually)\n green.increment_participation\n green.increment_participation\n experiment.set_alternatives_and_options(alternatives: %w(blue red green zip),\n goals: %w(purchase))\n experiment.save\n end\n\n it \"resets all alternatives\" do\n expect(green.participant_count).to eq(0)\n expect(green.completed_count).to eq(0)\n end\n\n context \"when reset_manually is set\" do\n let(:reset_manually) { true }\n\n it \"does not reset alternatives\" do\n expect(green.participant_count).to eq(2)\n expect(green.completed_count).to eq(0)\n end\n end\n end\n end\n\n describe \"alternatives passed as non-strings\" do\n it \"should throw an exception if an alternative is passed that is not a string\" do\n expect { Split::ExperimentCatalog.find_or_create(\"link_color\", :blue, :red) }.to raise_error(ArgumentError)\n expect { Split::ExperimentCatalog.find_or_create(\"link_enabled\", true, false) }.to raise_error(ArgumentError)\n end\n end\n\n describe \"specifying weights\" do\n let(:experiment_with_weight) {\n Split::ExperimentCatalog.find_or_create(\"link_color\", { \"blue\" => 1 }, { \"red\" => 2 })\n }\n\n it \"should work for a new experiment\" do\n expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])\n end\n\n it \"should work for an existing experiment\" do\n experiment.save\n expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2])\n end\n end\n\n describe \"specifying goals\" do\n let(:experiment) {\n new_experiment([\"purchase\"])\n }\n\n context \"saving experiment\" do\n let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ \"link_color\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\") }\n\n before { experiment.save }\n\n it \"can find existing experiment\" do\n expect(Split::ExperimentCatalog.find(\"link_color\").name).to eq(\"link_color\")\n end\n\n it \"should reset an experiment if it is loaded with different goals\" do\n same_but_different_goals\n expect(Split::ExperimentCatalog.find(\"link_color\").goals).to eq([\"purchase\", \"refund\"])\n end\n end\n\n it \"should have goals\" do\n expect(experiment.goals).to eq([\"purchase\"])\n end\n\n context \"find or create experiment\" do\n it \"should have correct goals\" do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n expect(experiment.goals).to eq([\"purchase\", \"refund\"])\n experiment = Split::ExperimentCatalog.find_or_create(\"link_color3\", \"blue\", \"red\", \"green\")\n expect(experiment.goals).to eq([])\n end\n end\n end\n\n describe \"beta probability calculation\" do\n it \"should return a hash with the probability of each alternative being the best\" do\n experiment = Split::ExperimentCatalog.find_or_create(\"mathematicians\", \"bernoulli\", \"poisson\", \"lagrange\")\n experiment.calc_winning_alternatives\n expect(experiment.alternative_probabilities).not_to be_nil\n end\n\n it \"should return between 46% and 54% probability for an experiment with 2 alternatives and no data\" do\n experiment = Split::ExperimentCatalog.find_or_create(\"scientists\", \"einstein\", \"bohr\")\n experiment.calc_winning_alternatives\n expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50)\n end\n\n it \"should calculate the probability of being the winning alternative separately for each goal\", skip: true do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n goal1 = experiment.goals[0]\n goal2 = experiment.goals[1]\n experiment.alternatives.each do |alternative|\n alternative.participant_count = 50\n alternative.set_completed_count(10, goal1)\n alternative.set_completed_count(15+rand(30), goal2)\n end\n experiment.calc_winning_alternatives\n alt = experiment.alternatives[0]\n p_goal1 = alt.p_winner(goal1)\n p_goal2 = alt.p_winner(goal2)\n expect(p_goal1).not_to be_within(0.04).of(p_goal2)\n end\n\n it \"should return nil and not re-calculate probabilities if they have already been calculated today\" do\n experiment = Split::ExperimentCatalog.find_or_create({ \"link_color3\" => [\"purchase\", \"refund\"] }, \"blue\", \"red\", \"green\")\n expect(experiment.calc_winning_alternatives).not_to be nil\n expect(experiment.calc_winning_alternatives).to be nil\n end\n end\nend\n\n If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives\n @@ -122,5 +122,17 @@ describe Split::Experiment do\n experiment.next_alternative.name.should eql('green')\n end\n end\n-end\n \n+ describe 'changing an existing experiment' do\n+ it \"should reset an experiment if it is loaded with different alternatives\" do\n+ experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green')\n+ blue = Split::Alternative.find('blue', 'link_color')\n+ blue.participant_count = 5\n+ blue.save\n+ same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange')\n+ same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange'])\n+ new_blue = Split::Alternative.find('blue', 'link_color')\n+ new_blue.participant_count.should eql(0)\n+ end\n+ end\n+end\n\\ No newline at end of file\n"},"addition_count":{"kind":"number","value":13,"string":"13"},"commit_subject":{"kind":"string","value":"If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".rb"},"lang":{"kind":"string","value":"rb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676492,"cells":{"id":{"kind":"string","value":"10072142"},"text":{"kind":"string","value":" AUTHORS\n Ask Solem \nRune Halvorsen \nRussell Sim \nBrian Rosner \nSverre Johansen \nBo Shi \nCarl Meyer \nVinícius das Chagas Silva \nVanderson Mota dos Santos \nStefan Foulis \nMichael Richardson \nHalldór Rúnarsson \nBrent Tubbs \nDavid Cramer \n\n Added Hugo Lopes Tavares (hugobr) to AUTHORS\n\n @@ -2,3 +2,4 @@ Ask Solem \n Rune Halvorsen \n Russell Sim \n Brian Rosner \n+Hugo Lopes Tavares \n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"Added Hugo Lopes Tavares (hugobr) to AUTHORS"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":""},"lang":{"kind":"string","value":"AUTHORS"},"license":{"kind":"string","value":"bsd-3-clause"},"repo_name":{"kind":"string","value":"ask/chishop"}}},{"rowIdx":10676493,"cells":{"id":{"kind":"string","value":"10072143"},"text":{"kind":"string","value":" tokenizer.ts\n import { deepEqual } from 'assert';\nimport tokenize from '../src/tokenizer';\n\ndescribe('Tokenizer', () => {\n it('numeric values', () => {\n deepEqual(tokenize('p10'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('p-10'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }\n ]);\n\n deepEqual(tokenize('p-10-'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 }\n ]);\n\n deepEqual(tokenize('p-10-20'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }\n ]);\n\n deepEqual(tokenize('p-10--20'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 }\n ]);\n\n deepEqual(tokenize('p-10-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 },\n { type: 'Operator', operator: '-', start: 7, end: 8 },\n { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 8, end: 11 }\n ]);\n\n deepEqual(tokenize('p-10p-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 },\n { type: 'Operator', operator: '-', start: 5, end: 6 },\n { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n\n deepEqual(tokenize('p-10%-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 },\n { type: 'Operator', operator: '-', start: 5, end: 6 },\n { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n });\n\n it('float values', () => {\n deepEqual(tokenize('p.5'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.5, rawValue: '.5', unit: '', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('p-.5'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -0.5, rawValue: '-.5', unit: '', start: 1, end: 4 }\n ]);\n\n deepEqual(tokenize('p.1.2.3'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 },\n { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 3, end: 5 },\n { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 5, end: 7 }\n ]);\n\n deepEqual(tokenize('p.1-.2.3'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 },\n { type: 'Operator', operator: '-', start: 3, end: 4 },\n { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 4, end: 6 },\n { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 6, end: 8 }\n ]);\n\n deepEqual(tokenize('p.1--.2.3'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 },\n { type: 'Operator', operator: '-', start: 3, end: 4 },\n { type: 'NumberValue', value: -0.2, rawValue: '-.2', unit: '', start: 4, end: 7 },\n { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 7, end: 9 }\n ]);\n\n deepEqual(tokenize('10'), [\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 0, end: 2 },\n ]);\n\n deepEqual(tokenize('.1'), [\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 },\n ]);\n\n // NB: now dot should be a part of literal\n // throws(() => tokenize('.foo'), /Unexpected character at 1/);\n });\n\n it('color values', () => {\n deepEqual(tokenize('c#'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '', start: 1, end: 2 }\n ]);\n\n deepEqual(tokenize('c#1'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 17, g: 17, b: 17, a: 1, raw: '1', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#.'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '.', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#f'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 255, g: 255, b: 255, a: 1, raw: 'f', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#a#b#c'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 170, g: 170, b: 170, a: 1, raw: 'a', start: 1, end: 3 },\n { type: 'ColorValue', r: 187, g: 187, b: 187, a: 1, raw: 'b', start: 3, end: 5 },\n { type: 'ColorValue', r: 204, g: 204, b: 204, a: 1, raw: 'c', start: 5, end: 7 }\n ]);\n\n deepEqual(tokenize('c#af'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 175, g: 175, b: 175, a: 1, raw: 'af', start: 1, end: 4 }\n ]);\n\n deepEqual(tokenize('c#fc0'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 1, end: 5 }\n ]);\n\n deepEqual(tokenize('c#11.5'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 17, g: 17, b: 17, a: 0.5, raw: '11.5', start: 1, end: 6 }\n ]);\n\n deepEqual(tokenize('c#.99'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0.99, raw: '.99', start: 1, end: 5 }\n ]);\n\n deepEqual(tokenize('c#t'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0, raw: 't', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#${fff}'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'Literal', value: '#', start: 1, end: 2 },\n { type: 'Field', index: undefined, name: 'fff', start: 2, end: 8 }\n ]);\n });\n\n it('keywords', () => {\n deepEqual(tokenize('m:a'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: ':', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 }\n ]);\n\n deepEqual(tokenize('m-a'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 }\n ]);\n\n deepEqual(tokenize('m-abc'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'abc', start: 2, end: 5 }\n ]);\n\n deepEqual(tokenize('m-a0'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }\n ]);\n\n deepEqual(tokenize('m-a0-a'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'Literal', value: 'a', start: 5, end: 6 }\n ]);\n });\n\n it('arguments', () => {\n deepEqual(tokenize('lg(top, \"red, black\", rgb(0, 0, 0) 10%)'), [\n { type: 'Literal', value: 'lg', start: 0, end: 2 },\n { type: 'Bracket', open: true, start: 2, end: 3 },\n { type: 'Literal', value: 'top', start: 3, end: 6 },\n { type: 'Operator', operator: ',', start: 6, end: 7 },\n { type: 'WhiteSpace', start: 7, end: 8 },\n { type: 'StringValue', value: 'red, black', quote: 'double', start: 8, end: 20 },\n { type: 'Operator', operator: ',', start: 20, end: 21 },\n { type: 'WhiteSpace', start: 21, end: 22 },\n { type: 'Literal', value: 'rgb', start: 22, end: 25 },\n { type: 'Bracket', open: true, start: 25, end: 26 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 26, end: 27 },\n { type: 'Operator', operator: ',', start: 27, end: 28 },\n { type: 'WhiteSpace', start: 28, end: 29 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 },\n { type: 'Operator', operator: ',', start: 30, end: 31 },\n { type: 'WhiteSpace', start: 31, end: 32 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 },\n { type: 'Bracket', open: false, start: 33, end: 34 },\n { type: 'WhiteSpace', start: 34, end: 35 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 },\n { type: 'Bracket', open: false, start: 38, end: 39 }\n ]);\n });\n\n it('important', () => {\n deepEqual(tokenize('!'), [\n { type: 'Operator', operator: '!', start: 0, end: 1 }\n ]);\n\n deepEqual(tokenize('p!'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'Operator', operator: '!', start: 1, end: 2 }\n ]);\n\n deepEqual(tokenize('p10!'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 },\n { type: 'Operator', operator: '!', start: 3, end: 4 }\n deepEqual(tokenize('bd#fc0-1'), [\n { type: 'Literal', value: 'bd', start: 0, end: 2 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 },\n { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 }\n ]);\n\n deepEqual(tokenize('p0+m0'), [\n { type: 'Literal', value: 's', start: 4, end: 5 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 }\n ]);\n\n deepEqual(tokenize('bd#fc0-1'), [\n { type: 'Literal', value: 'bd', start: 0, end: 2 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 },\n { type: 'Operator', operator: '-', start: 6, end: 7 },\n { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 7, end: 8 }\n ]);\n\n deepEqual(tokenize('p0+m0'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 },\n { type: 'Operator', operator: '+', start: 2, end: 3 },\n { type: 'Literal', value: 'm', start: 3, end: 4 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 4, end: 5 }\n ]);\n\n deepEqual(tokenize('p0!+m0!'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 },\n { type: 'Operator', operator: '!', start: 2, end: 3 },\n { type: 'Operator', operator: '+', start: 3, end: 4 },\n { type: 'Literal', value: 'm', start: 4, end: 5 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 },\n { type: 'Operator', operator: '!', start: 6, end: 7 }\n ]);\n\n deepEqual(tokenize('${2:0}%'), [\n { type: 'Field', index: 2, name: '0', start: 0, end: 6 },\n { type: 'Literal', value: '%', start: 6, end: 7 }\n ]);\n\n deepEqual(tokenize('.${1:5}'), [\n { type: 'Literal', value: '.', start: 0, end: 1 },\n { type: 'Field', index: 1, name: '5', start: 1, end: 7 },\n ]);\n });\n\n it('embedded variables', () => {\n deepEqual(tokenize('foo$bar'), [\n { type: 'Literal', value: 'foo', start: 0, end: 3 },\n { type: 'Literal', value: '$bar', start: 3, end: 7 }\n ]);\n\n deepEqual(tokenize('foo$bar-2'), [\n { type: 'Literal', value: 'foo', start: 0, end: 3 },\n { type: 'Literal', value: '$bar-2', start: 3, end: 9 }\n ]);\n\n deepEqual(tokenize('foo$bar@bam'), [\n { type: 'Literal', value: 'foo', start: 0, end: 3 },\n { type: 'Literal', value: '$bar', start: 3, end: 7 },\n { type: 'Literal', value: '@bam', start: 7, end: 11 }\n ]);\n\n deepEqual(tokenize('@k10'), [\n { type: 'Literal', value: '@k', start: 0, end: 2 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 }\n ]);\n });\n});\n\n Working implementation of CSS parser\n\n @@ -45,8 +45,7 @@ describe('Tokenizer', () => {\n deepEqual(tokenize('p-10p-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 },\n- { type: 'Operator', operator: '-', start: 5, end: 6 },\n- { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n+ { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n@@ -54,8 +53,7 @@ describe('Tokenizer', () => {\n deepEqual(tokenize('p-10%-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 },\n- { type: 'Operator', operator: '-', start: 5, end: 6 },\n- { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n+ { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n@@ -246,7 +244,8 @@ describe('Tokenizer', () => {\n deepEqual(tokenize('bd#fc0-1'), [\n { type: 'Literal', value: 'bd', start: 0, end: 2 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 },\n- { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 }\n+ { type: 'Operator', operator: '-', start: 6, end: 7 },\n+ { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 }\n ]);\n \n deepEqual(tokenize('p0+m0'), [\n"},"addition_count":{"kind":"number","value":4,"string":"4"},"commit_subject":{"kind":"string","value":"Working implementation of CSS parser"},"deletion_count":{"kind":"number","value":5,"string":"5"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676494,"cells":{"id":{"kind":"string","value":"10072144"},"text":{"kind":"string","value":" tokenizer.ts\n import { deepEqual } from 'assert';\nimport tokenize from '../src/tokenizer';\n\ndescribe('Tokenizer', () => {\n it('numeric values', () => {\n deepEqual(tokenize('p10'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('p-10'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }\n ]);\n\n deepEqual(tokenize('p-10-'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 }\n ]);\n\n deepEqual(tokenize('p-10-20'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }\n ]);\n\n deepEqual(tokenize('p-10--20'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 }\n ]);\n\n deepEqual(tokenize('p-10-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 },\n { type: 'Operator', operator: '-', start: 7, end: 8 },\n { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 8, end: 11 }\n ]);\n\n deepEqual(tokenize('p-10p-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 },\n { type: 'Operator', operator: '-', start: 5, end: 6 },\n { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n\n deepEqual(tokenize('p-10%-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 },\n { type: 'Operator', operator: '-', start: 5, end: 6 },\n { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n });\n\n it('float values', () => {\n deepEqual(tokenize('p.5'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.5, rawValue: '.5', unit: '', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('p-.5'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -0.5, rawValue: '-.5', unit: '', start: 1, end: 4 }\n ]);\n\n deepEqual(tokenize('p.1.2.3'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 },\n { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 3, end: 5 },\n { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 5, end: 7 }\n ]);\n\n deepEqual(tokenize('p.1-.2.3'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 },\n { type: 'Operator', operator: '-', start: 3, end: 4 },\n { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 4, end: 6 },\n { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 6, end: 8 }\n ]);\n\n deepEqual(tokenize('p.1--.2.3'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 },\n { type: 'Operator', operator: '-', start: 3, end: 4 },\n { type: 'NumberValue', value: -0.2, rawValue: '-.2', unit: '', start: 4, end: 7 },\n { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 7, end: 9 }\n ]);\n\n deepEqual(tokenize('10'), [\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 0, end: 2 },\n ]);\n\n deepEqual(tokenize('.1'), [\n { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 },\n ]);\n\n // NB: now dot should be a part of literal\n // throws(() => tokenize('.foo'), /Unexpected character at 1/);\n });\n\n it('color values', () => {\n deepEqual(tokenize('c#'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '', start: 1, end: 2 }\n ]);\n\n deepEqual(tokenize('c#1'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 17, g: 17, b: 17, a: 1, raw: '1', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#.'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '.', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#f'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 255, g: 255, b: 255, a: 1, raw: 'f', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#a#b#c'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 170, g: 170, b: 170, a: 1, raw: 'a', start: 1, end: 3 },\n { type: 'ColorValue', r: 187, g: 187, b: 187, a: 1, raw: 'b', start: 3, end: 5 },\n { type: 'ColorValue', r: 204, g: 204, b: 204, a: 1, raw: 'c', start: 5, end: 7 }\n ]);\n\n deepEqual(tokenize('c#af'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 175, g: 175, b: 175, a: 1, raw: 'af', start: 1, end: 4 }\n ]);\n\n deepEqual(tokenize('c#fc0'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 1, end: 5 }\n ]);\n\n deepEqual(tokenize('c#11.5'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 17, g: 17, b: 17, a: 0.5, raw: '11.5', start: 1, end: 6 }\n ]);\n\n deepEqual(tokenize('c#.99'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0.99, raw: '.99', start: 1, end: 5 }\n ]);\n\n deepEqual(tokenize('c#t'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0, raw: 't', start: 1, end: 3 }\n ]);\n\n deepEqual(tokenize('c#${fff}'), [\n { type: 'Literal', value: 'c', start: 0, end: 1 },\n { type: 'Literal', value: '#', start: 1, end: 2 },\n { type: 'Field', index: undefined, name: 'fff', start: 2, end: 8 }\n ]);\n });\n\n it('keywords', () => {\n deepEqual(tokenize('m:a'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: ':', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 }\n ]);\n\n deepEqual(tokenize('m-a'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 }\n ]);\n\n deepEqual(tokenize('m-abc'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'abc', start: 2, end: 5 }\n ]);\n\n deepEqual(tokenize('m-a0'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }\n ]);\n\n deepEqual(tokenize('m-a0-a'), [\n { type: 'Literal', value: 'm', start: 0, end: 1 },\n { type: 'Operator', operator: '-', start: 1, end: 2 },\n { type: 'Literal', value: 'a', start: 2, end: 3 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 },\n { type: 'Operator', operator: '-', start: 4, end: 5 },\n { type: 'Literal', value: 'a', start: 5, end: 6 }\n ]);\n });\n\n it('arguments', () => {\n deepEqual(tokenize('lg(top, \"red, black\", rgb(0, 0, 0) 10%)'), [\n { type: 'Literal', value: 'lg', start: 0, end: 2 },\n { type: 'Bracket', open: true, start: 2, end: 3 },\n { type: 'Literal', value: 'top', start: 3, end: 6 },\n { type: 'Operator', operator: ',', start: 6, end: 7 },\n { type: 'WhiteSpace', start: 7, end: 8 },\n { type: 'StringValue', value: 'red, black', quote: 'double', start: 8, end: 20 },\n { type: 'Operator', operator: ',', start: 20, end: 21 },\n { type: 'WhiteSpace', start: 21, end: 22 },\n { type: 'Literal', value: 'rgb', start: 22, end: 25 },\n { type: 'Bracket', open: true, start: 25, end: 26 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 26, end: 27 },\n { type: 'Operator', operator: ',', start: 27, end: 28 },\n { type: 'WhiteSpace', start: 28, end: 29 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 },\n { type: 'Operator', operator: ',', start: 30, end: 31 },\n { type: 'WhiteSpace', start: 31, end: 32 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 },\n { type: 'Bracket', open: false, start: 33, end: 34 },\n { type: 'WhiteSpace', start: 34, end: 35 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 },\n { type: 'Bracket', open: false, start: 38, end: 39 }\n ]);\n });\n\n it('important', () => {\n deepEqual(tokenize('!'), [\n { type: 'Operator', operator: '!', start: 0, end: 1 }\n ]);\n\n deepEqual(tokenize('p!'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'Operator', operator: '!', start: 1, end: 2 }\n ]);\n\n deepEqual(tokenize('p10!'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 },\n { type: 'Operator', operator: '!', start: 3, end: 4 }\n deepEqual(tokenize('bd#fc0-1'), [\n { type: 'Literal', value: 'bd', start: 0, end: 2 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 },\n { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 }\n ]);\n\n deepEqual(tokenize('p0+m0'), [\n { type: 'Literal', value: 's', start: 4, end: 5 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 }\n ]);\n\n deepEqual(tokenize('bd#fc0-1'), [\n { type: 'Literal', value: 'bd', start: 0, end: 2 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 },\n { type: 'Operator', operator: '-', start: 6, end: 7 },\n { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 7, end: 8 }\n ]);\n\n deepEqual(tokenize('p0+m0'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 },\n { type: 'Operator', operator: '+', start: 2, end: 3 },\n { type: 'Literal', value: 'm', start: 3, end: 4 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 4, end: 5 }\n ]);\n\n deepEqual(tokenize('p0!+m0!'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 },\n { type: 'Operator', operator: '!', start: 2, end: 3 },\n { type: 'Operator', operator: '+', start: 3, end: 4 },\n { type: 'Literal', value: 'm', start: 4, end: 5 },\n { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 },\n { type: 'Operator', operator: '!', start: 6, end: 7 }\n ]);\n\n deepEqual(tokenize('${2:0}%'), [\n { type: 'Field', index: 2, name: '0', start: 0, end: 6 },\n { type: 'Literal', value: '%', start: 6, end: 7 }\n ]);\n\n deepEqual(tokenize('.${1:5}'), [\n { type: 'Literal', value: '.', start: 0, end: 1 },\n { type: 'Field', index: 1, name: '5', start: 1, end: 7 },\n ]);\n });\n\n it('embedded variables', () => {\n deepEqual(tokenize('foo$bar'), [\n { type: 'Literal', value: 'foo', start: 0, end: 3 },\n { type: 'Literal', value: '$bar', start: 3, end: 7 }\n ]);\n\n deepEqual(tokenize('foo$bar-2'), [\n { type: 'Literal', value: 'foo', start: 0, end: 3 },\n { type: 'Literal', value: '$bar-2', start: 3, end: 9 }\n ]);\n\n deepEqual(tokenize('foo$bar@bam'), [\n { type: 'Literal', value: 'foo', start: 0, end: 3 },\n { type: 'Literal', value: '$bar', start: 3, end: 7 },\n { type: 'Literal', value: '@bam', start: 7, end: 11 }\n ]);\n\n deepEqual(tokenize('@k10'), [\n { type: 'Literal', value: '@k', start: 0, end: 2 },\n { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 }\n ]);\n });\n});\n\n Working implementation of CSS parser\n\n @@ -45,8 +45,7 @@ describe('Tokenizer', () => {\n deepEqual(tokenize('p-10p-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 },\n- { type: 'Operator', operator: '-', start: 5, end: 6 },\n- { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n+ { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n@@ -54,8 +53,7 @@ describe('Tokenizer', () => {\n deepEqual(tokenize('p-10%-20--30'), [\n { type: 'Literal', value: 'p', start: 0, end: 1 },\n { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 },\n- { type: 'Operator', operator: '-', start: 5, end: 6 },\n- { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 },\n+ { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 },\n { type: 'Operator', operator: '-', start: 8, end: 9 },\n { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 }\n ]);\n@@ -246,7 +244,8 @@ describe('Tokenizer', () => {\n deepEqual(tokenize('bd#fc0-1'), [\n { type: 'Literal', value: 'bd', start: 0, end: 2 },\n { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 },\n- { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 }\n+ { type: 'Operator', operator: '-', start: 6, end: 7 },\n+ { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 }\n ]);\n \n deepEqual(tokenize('p0+m0'), [\n"},"addition_count":{"kind":"number","value":4,"string":"4"},"commit_subject":{"kind":"string","value":"Working implementation of CSS parser"},"deletion_count":{"kind":"number","value":5,"string":"5"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676495,"cells":{"id":{"kind":"string","value":"10072145"},"text":{"kind":"string","value":" index.erb\n <% if @experiments.any? %>\n

    The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.

    \n\n
    \n \n \n \n \n
    \n\n <% paginated(@experiments).each do |experiment| %>\n <% if experiment.goals.empty? %>\n <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %>\n <% else %>\n <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %>\n <% experiment.goals.each do |g| %>\n <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %>\n <% end %>\n <% end %>\n <% end %>\n <%= alternative.participant_count %>\n <%= alternative.participant_count - alternative.completed_count %>\n <%= alternative.completed_count %>\n <%= (alternative.conversion_rate * 100).round(2) %>%\n <%= alternative.z_score %>\n \n <% if experiment.winner %>\n<% end %>\n\n
    \n
    \" method='post'>\n \n \n \n
    \n
    \n\n More robust conversion rate\n\n @@ -21,7 +21,7 @@\n <%= alternative.participant_count %>\n <%= alternative.participant_count - alternative.completed_count %>\n <%= alternative.completed_count %>\n- <%= (alternative.conversion_rate * 100).round(2) %>%\n+ <%= number_to_percentage(alternative.conversion_rate) %>%\n <%= alternative.z_score %>\n \n <% if experiment.winner %>\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"More robust conversion rate"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".erb"},"lang":{"kind":"string","value":"erb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676496,"cells":{"id":{"kind":"string","value":"10072146"},"text":{"kind":"string","value":" index.erb\n <% if @experiments.any? %>\n

    The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.

    \n\n
    \n \n \n \n \n
    \n\n <% paginated(@experiments).each do |experiment| %>\n <% if experiment.goals.empty? %>\n <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %>\n <% else %>\n <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %>\n <% experiment.goals.each do |g| %>\n <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %>\n <% end %>\n <% end %>\n <% end %>\n <%= alternative.participant_count %>\n <%= alternative.participant_count - alternative.completed_count %>\n <%= alternative.completed_count %>\n <%= (alternative.conversion_rate * 100).round(2) %>%\n <%= alternative.z_score %>\n \n <% if experiment.winner %>\n<% end %>\n\n
    \n
    \" method='post'>\n \n \n \n
    \n
    \n\n More robust conversion rate\n\n @@ -21,7 +21,7 @@\n <%= alternative.participant_count %>\n <%= alternative.participant_count - alternative.completed_count %>\n <%= alternative.completed_count %>\n- <%= (alternative.conversion_rate * 100).round(2) %>%\n+ <%= number_to_percentage(alternative.conversion_rate) %>%\n <%= alternative.z_score %>\n \n <% if experiment.winner %>\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"More robust conversion rate"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".erb"},"lang":{"kind":"string","value":"erb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676497,"cells":{"id":{"kind":"string","value":"10072147"},"text":{"kind":"string","value":" index.erb\n <% if @experiments.any? %>\n

    The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.

    \n\n
    \n \n \n \n \n
    \n\n <% paginated(@experiments).each do |experiment| %>\n <% if experiment.goals.empty? %>\n <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %>\n <% else %>\n <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %>\n <% experiment.goals.each do |g| %>\n <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %>\n <% end %>\n <% end %>\n <% end %>\n <%= alternative.participant_count %>\n <%= alternative.participant_count - alternative.completed_count %>\n <%= alternative.completed_count %>\n <%= (alternative.conversion_rate * 100).round(2) %>%\n <%= alternative.z_score %>\n \n <% if experiment.winner %>\n<% end %>\n\n
    \n
    \" method='post'>\n \n \n \n
    \n
    \n\n More robust conversion rate\n\n @@ -21,7 +21,7 @@\n <%= alternative.participant_count %>\n <%= alternative.participant_count - alternative.completed_count %>\n <%= alternative.completed_count %>\n- <%= (alternative.conversion_rate * 100).round(2) %>%\n+ <%= number_to_percentage(alternative.conversion_rate) %>%\n <%= alternative.z_score %>\n \n <% if experiment.winner %>\n"},"addition_count":{"kind":"number","value":1,"string":"1"},"commit_subject":{"kind":"string","value":"More robust conversion rate"},"deletion_count":{"kind":"number","value":1,"string":"1"},"file_extension":{"kind":"string","value":".erb"},"lang":{"kind":"string","value":"erb"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"splitrb/split"}}},{"rowIdx":10676498,"cells":{"id":{"kind":"string","value":"10072148"},"text":{"kind":"string","value":" convert.ts\n import { equal } from 'assert';\nimport parser, { ParserOptions } from '../src';\nimport stringify from './assets/stringify-node';\n\nfunction parse(abbr: string, options?: ParserOptions) {\n return stringify(parser(abbr, options));\n}\n\ndescribe('Convert token abbreviations', () => {\n it('basic', () => {\n equal(parse('input[value=\"text$\"]*2'), '');\n\n equal(parse('ul>li.item$*3'), '
    ');\n equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '
      foo$bar$
    ');\n equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '
      item 1item 2
    ');\n equal(parse('ul>li.item$*'), '
    ');\n equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '
      foo.barhello.world
    ');\n\n equal(parse('p{hi}', { text: ['hello'] }), '

    hihello

    ');\n equal(parse('p*{hi}', { text: ['1', '2'] }), 'hi1

    hi2

    ');\n equal(parse('div>p+p{hi}', { text: ['hello'] }), '

    hihello

    ');\n\n equal(parse('html[lang=${lang}]'), '');\n equal(parse('div{[}+a{}'), '
    [
    ');\n });\n\n it('unroll', () => {\n equal(parse('a>(b>c)+d'), '');\n equal(parse('(a>b)+(c>d)'), '');\n equal(parse('a>((b>c)(d>e))f'), '');\n equal(parse('a>((((b>c))))+d'), '');\n equal(parse('a>(((b>c))*4)+d'), '');\n equal(parse('(div>dl>(dt+dd)*2)'), '
    ');\n\n equal(parse('a*2>b*3'), '');\n equal(parse('a>(b+c)*2'), '');\n equal(parse('a>(b+c)*2+(d+e)*2'), '');\n\n // Should move `
    ` as sibling of `{foo}`\n equal(parse('p>{foo}>div'), '

    foo

    ');\n equal(parse('p>{foo ${0}}>div'), '

    foo ${0}

    ');\n });\n\n it('limit unroll', () => {\n // Limit amount of repeated elements\n equal(parse('a*10', { maxRepeat: 5 }), '');\n equal(parse('a*10'), '');\n equal(parse('a*3>b*3', { maxRepeat: 5 }), '');\n });\n\n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n equal(parse('a$*2>b$@^*3/'), '');\n });\n\n it('href', () => {\n equal(parse('a', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a', { href: true, text: 'test here' }), 'test here');\n equal(parse('a', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a[href=]', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a[href=]', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a[href=]', { href: true, text: 'test here' }), 'test here');\n equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=\"www.google.it\"]', { href: false, text: 'test' }), 'test');\n equal(parse('a[href=\"www.example.com\"]', { href: true, text: 'www.google.it' }), 'www.google.it');\n });\n\n it('wrap basic', () => {\n equal(parse('p', { text: 'test' }), '

    test

    ');\n equal(parse('p', { text: ['test'] }), '

    test

    ');\n equal(parse('p', { text: ['test1', 'test2'] }), '

    test1\\ntest2

    ');\n equal(parse('p', { text: ['test1', '', 'test2'] }), '

    test1\\n\\ntest2

    ');\n equal(parse('p*', { text: ['test1', 'test2'] }), 'test1

    test2

    ');\n equal(parse('p*', { text: ['test1', '', 'test2'] }), 'test1

    test2

    ');\n })\n});\n\n Fix wrap around anchor elements with classes (#656)\n\n\n @@ -21,6 +21,8 @@ describe('Convert token abbreviations', () => {\n equal(parse('div>p+p{hi}', { text: ['hello'] }), '

    hihello

    ');\n \n equal(parse('html[lang=${lang}]'), '');\n+ equal(parse('html.one.two'), '');\n+ equal(parse('html.one[two=three]'), '');\n equal(parse('div{[}+a{}'), '
    [
    ');\n });\n \n@@ -69,6 +71,10 @@ describe('Convert token abbreviations', () => {\n equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n+ equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n+ equal(parse('a.here', { href: true, text: 'www.domain.com' }), 'www.domain.com');\n+ equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n+ equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n \n equal(parse('a[href=\"www.google.it\"]', { href: false, text: 'test' }), 'test');\n equal(parse('a[href=\"www.example.com\"]', { href: true, text: 'www.google.it' }), 'www.google.it');\n"},"addition_count":{"kind":"number","value":6,"string":"6"},"commit_subject":{"kind":"string","value":"Fix wrap around anchor elements with classes (#656)"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}},{"rowIdx":10676499,"cells":{"id":{"kind":"string","value":"10072149"},"text":{"kind":"string","value":" convert.ts\n import { equal } from 'assert';\nimport parser, { ParserOptions } from '../src';\nimport stringify from './assets/stringify-node';\n\nfunction parse(abbr: string, options?: ParserOptions) {\n return stringify(parser(abbr, options));\n}\n\ndescribe('Convert token abbreviations', () => {\n it('basic', () => {\n equal(parse('input[value=\"text$\"]*2'), '');\n\n equal(parse('ul>li.item$*3'), '
    ');\n equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '
      foo$bar$
    ');\n equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '
      item 1item 2
    ');\n equal(parse('ul>li.item$*'), '
    ');\n equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '
      foo.barhello.world
    ');\n\n equal(parse('p{hi}', { text: ['hello'] }), '

    hihello

    ');\n equal(parse('p*{hi}', { text: ['1', '2'] }), 'hi1

    hi2

    ');\n equal(parse('div>p+p{hi}', { text: ['hello'] }), '

    hihello

    ');\n\n equal(parse('html[lang=${lang}]'), '');\n equal(parse('div{[}+a{}'), '
    [
    ');\n });\n\n it('unroll', () => {\n equal(parse('a>(b>c)+d'), '');\n equal(parse('(a>b)+(c>d)'), '');\n equal(parse('a>((b>c)(d>e))f'), '');\n equal(parse('a>((((b>c))))+d'), '');\n equal(parse('a>(((b>c))*4)+d'), '');\n equal(parse('(div>dl>(dt+dd)*2)'), '
    ');\n\n equal(parse('a*2>b*3'), '');\n equal(parse('a>(b+c)*2'), '');\n equal(parse('a>(b+c)*2+(d+e)*2'), '');\n\n // Should move `
    ` as sibling of `{foo}`\n equal(parse('p>{foo}>div'), '

    foo

    ');\n equal(parse('p>{foo ${0}}>div'), '

    foo ${0}

    ');\n });\n\n it('limit unroll', () => {\n // Limit amount of repeated elements\n equal(parse('a*10', { maxRepeat: 5 }), '');\n equal(parse('a*10'), '');\n equal(parse('a*3>b*3', { maxRepeat: 5 }), '');\n });\n\n it('parent repeater', () => {\n equal(parse('a$*2>b$*3/'), '');\n equal(parse('a$*2>b$@^*3/'), '');\n });\n\n it('href', () => {\n equal(parse('a', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a', { href: true, text: 'test here' }), 'test here');\n equal(parse('a', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), 'https://www.google.it');\n equal(parse('a[href=]', { href: true, text: 'www.google.it' }), 'www.google.it');\n equal(parse('a[href=]', { href: true, text: 'google.it' }), 'google.it');\n equal(parse('a[href=]', { href: true, text: 'test here' }), 'test here');\n equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n\n equal(parse('a[href=\"www.google.it\"]', { href: false, text: 'test' }), 'test');\n equal(parse('a[href=\"www.example.com\"]', { href: true, text: 'www.google.it' }), 'www.google.it');\n });\n\n it('wrap basic', () => {\n equal(parse('p', { text: 'test' }), '

    test

    ');\n equal(parse('p', { text: ['test'] }), '

    test

    ');\n equal(parse('p', { text: ['test1', 'test2'] }), '

    test1\\ntest2

    ');\n equal(parse('p', { text: ['test1', '', 'test2'] }), '

    test1\\n\\ntest2

    ');\n equal(parse('p*', { text: ['test1', 'test2'] }), 'test1

    test2

    ');\n equal(parse('p*', { text: ['test1', '', 'test2'] }), 'test1

    test2

    ');\n })\n});\n\n Fix wrap around anchor elements with classes (#656)\n\n\n @@ -21,6 +21,8 @@ describe('Convert token abbreviations', () => {\n equal(parse('div>p+p{hi}', { text: ['hello'] }), '

    hihello

    ');\n \n equal(parse('html[lang=${lang}]'), '');\n+ equal(parse('html.one.two'), '');\n+ equal(parse('html.one[two=three]'), '');\n equal(parse('div{[}+a{}'), '
    [
    ');\n });\n \n@@ -69,6 +71,10 @@ describe('Convert token abbreviations', () => {\n equal(parse('a[href=]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n+ equal(parse('a[class=here]', { href: true, text: 'test@domain.com' }), 'test@domain.com');\n+ equal(parse('a.here', { href: true, text: 'www.domain.com' }), 'www.domain.com');\n+ equal(parse('a[class=here]', { href: true, text: 'test here test@domain.com' }), 'test here test@domain.com');\n+ equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), 'test here www.domain.com');\n \n equal(parse('a[href=\"www.google.it\"]', { href: false, text: 'test' }), 'test');\n equal(parse('a[href=\"www.example.com\"]', { href: true, text: 'www.google.it' }), 'www.google.it');\n"},"addition_count":{"kind":"number","value":6,"string":"6"},"commit_subject":{"kind":"string","value":"Fix wrap around anchor elements with classes (#656)"},"deletion_count":{"kind":"number","value":0,"string":"0"},"file_extension":{"kind":"string","value":".ts"},"lang":{"kind":"string","value":"ts"},"license":{"kind":"string","value":"mit"},"repo_name":{"kind":"string","value":"emmetio/emmet"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":106764,"numItemsPerPage":100,"numTotalItems":10676919,"offset":10676400,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Njc2NjU5OCwic3ViIjoiL2RhdGFzZXRzL0NhcnBlckFJL2dpdGh1Yi1kaWZmcy1kZWR1cGVkIiwiZXhwIjoxNzU2NzcwMTk4LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.ewQZ8WdThvAmLoDJJgF2w3Y6OzXu27ZnQjZli1Tc0qI0zl_jupVFdHqpn9ZpfiR6CrnjEEBHsUkXslseAlu1AQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    Search is not available for this dataset
    id
    stringlengths
    1
    8
    text
    stringlengths
    72
    9.81M
    addition_count
    int64
    0
    10k
    commit_subject
    stringlengths
    0
    3.7k
    deletion_count
    int64
    0
    8.43k
    file_extension
    stringlengths
    0
    32
    lang
    stringlengths
    1
    94
    license
    stringclasses
    10 values
    repo_name
    stringlengths
    9
    59
    10072050
    <NME> .npmignore <BEF> npm-debug.log* node_modules jspm_packages .npm /.* /*.* /test /src /packages <MSG> Exclude snippets from publishing <DFF> @@ -7,3 +7,4 @@ jspm_packages /test /src /packages +/snippets
    1
    Exclude snippets from publishing
    0
    npmignore
    mit
    emmetio/emmet
    10072051
    <NME> AUTHORS <BEF> Ask Solem <[email protected]> Rune Halvorsen <[email protected]> Russell Sim <[email protected]> Brian Rosner <[email protected]> Hugo Lopes Tavares <[email protected]> Sverre Johansen <[email protected]> Bo Shi <[email protected]> Carl Meyer <[email protected]> Vinícius das Chagas Silva <[email protected]> Vanderson Mota dos Santos <[email protected]> Stefan Foulis <[email protected]> Michael Richardson <[email protected]> Halldor Brent Tubbs <[email protected]> David Cramer <[email protected]> <MSG> Found full-name for contributor Halldor <DFF> @@ -10,4 +10,4 @@ Vinícius das Chagas Silva <[email protected]> Vanderson Mota dos Santos <[email protected]> Stefan Foulis <[email protected]> Michael Richardson <[email protected]> -Halldor +Halldór Rúnarsson <[email protected]>
    1
    Found full-name for contributor Halldor
    1
    AUTHORS
    bsd-3-clause
    ask/chishop
    10072052
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_dependency "redis", ">= 4.2" s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '~> 1.14' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> update bundler dev dependency <DFF> @@ -34,7 +34,7 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' - s.add_development_dependency 'bundler', '~> 1.14' + s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12'
    1
    update bundler dev dependency
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072053
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_dependency "redis", ">= 4.2" s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '~> 1.14' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> update bundler dev dependency <DFF> @@ -34,7 +34,7 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' - s.add_development_dependency 'bundler', '~> 1.14' + s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12'
    1
    update bundler dev dependency
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072054
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_paths = ["lib"] s.add_dependency "redis", ">= 4.2" s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '~> 1.14' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12' s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> update bundler dev dependency <DFF> @@ -34,7 +34,7 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' - s.add_development_dependency 'bundler', '~> 1.14' + s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency 'rack-test', '~> 0.6' s.add_development_dependency 'rake', '~> 12'
    1
    update bundler dev dependency
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072055
    <NME> encapsulated_helper_spec.rb <BEF> ADDFILE <MSG> #256 avoiding call to params in EncapsulatedHelper <DFF> @@ -0,0 +1,24 @@ +require 'spec_helper' + +describe Split::EncapsulatedHelper do + include Split::EncapsulatedHelper + + before do + @persistence_adapter = Split.configuration.persistence + Split.configuration.persistence = Hash + end + + after do + Split.configuration.persistence = @persistence_adapter + end + + def params + raise NoMethodError, 'This method is not really defined' + end + + describe "ab_test" do + it "should not raise an error when params raises an error" do + lambda { ab_test('link_color', 'blue', 'red') }.should_not raise_error + end + end +end
    24
    #256 avoiding call to params in EncapsulatedHelper
    0
    .rb
    rb
    mit
    splitrb/split
    10072056
    <NME> encapsulated_helper_spec.rb <BEF> ADDFILE <MSG> #256 avoiding call to params in EncapsulatedHelper <DFF> @@ -0,0 +1,24 @@ +require 'spec_helper' + +describe Split::EncapsulatedHelper do + include Split::EncapsulatedHelper + + before do + @persistence_adapter = Split.configuration.persistence + Split.configuration.persistence = Hash + end + + after do + Split.configuration.persistence = @persistence_adapter + end + + def params + raise NoMethodError, 'This method is not really defined' + end + + describe "ab_test" do + it "should not raise an error when params raises an error" do + lambda { ab_test('link_color', 'blue', 'red') }.should_not raise_error + end + end +end
    24
    #256 avoiding call to params in EncapsulatedHelper
    0
    .rb
    rb
    mit
    splitrb/split
    10072057
    <NME> encapsulated_helper_spec.rb <BEF> ADDFILE <MSG> #256 avoiding call to params in EncapsulatedHelper <DFF> @@ -0,0 +1,24 @@ +require 'spec_helper' + +describe Split::EncapsulatedHelper do + include Split::EncapsulatedHelper + + before do + @persistence_adapter = Split.configuration.persistence + Split.configuration.persistence = Hash + end + + after do + Split.configuration.persistence = @persistence_adapter + end + + def params + raise NoMethodError, 'This method is not really defined' + end + + describe "ab_test" do + it "should not raise an error when params raises an error" do + lambda { ab_test('link_color', 'blue', 'red') }.should_not raise_error + end + end +end
    24
    #256 avoiding call to params in EncapsulatedHelper
    0
    .rb
    rb
    mit
    splitrb/split
    10072058
    <NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } context 'when redis is not available' do before(:each) do Split.stub(:redis).and_raise(Errno::ECONNREFUSED) end context 'and db_failover config option is turned off' do it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #53 from leocassarani/issue-52 Fix failing tests on Rubinius (issue #52) <DFF> @@ -319,7 +319,7 @@ describe Split::Helper do context 'when redis is not available' do before(:each) do - Split.stub(:redis).and_raise(Errno::ECONNREFUSED) + Split.stub(:redis).and_raise(Errno::ECONNREFUSED.new) end context 'and db_failover config option is turned off' do
    1
    Merge pull request #53 from leocassarani/issue-52
    1
    .rb
    rb
    mit
    splitrb/split
    10072059
    <NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } context 'when redis is not available' do before(:each) do Split.stub(:redis).and_raise(Errno::ECONNREFUSED) end context 'and db_failover config option is turned off' do it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #53 from leocassarani/issue-52 Fix failing tests on Rubinius (issue #52) <DFF> @@ -319,7 +319,7 @@ describe Split::Helper do context 'when redis is not available' do before(:each) do - Split.stub(:redis).and_raise(Errno::ECONNREFUSED) + Split.stub(:redis).and_raise(Errno::ECONNREFUSED.new) end context 'and db_failover config option is turned off' do
    1
    Merge pull request #53 from leocassarani/issue-52
    1
    .rb
    rb
    mit
    splitrb/split
    10072060
    <NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment")).to eq "one" expect(ab_test("my_experiment") do |_, meta| meta end).to eq("Meta1") end end context "is not defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: nil } } context 'when redis is not available' do before(:each) do Split.stub(:redis).and_raise(Errno::ECONNREFUSED) end context 'and db_failover config option is turned off' do it "should pass control metadata helper block if library disabled" do Split.configure do |config| config.enabled = false end expect(ab_test("my_experiment") do |_, meta| meta end).to eq({}) end end end describe "ab_finished" do context "for an experiment that the user participates in" do before(:each) do @experiment_name = "link_color" @alternatives = ["blue", "red"] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it "should increment the counter for the completed alternative" do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should not increment the counter if reset is false and the experiment has been already finished" do 2.times { ab_finished(@experiment_name, { reset: false }) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" a = ab_test("button_size", "small", "big") expect(a).to eq("small") expect { ab_finished("button_size") }.not_to change { Split::Alternative.new(a, "button_size").completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, { reset: false }) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end context "for an experiment that the user is excluded from" do before do alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #53 from leocassarani/issue-52 Fix failing tests on Rubinius (issue #52) <DFF> @@ -319,7 +319,7 @@ describe Split::Helper do context 'when redis is not available' do before(:each) do - Split.stub(:redis).and_raise(Errno::ECONNREFUSED) + Split.stub(:redis).and_raise(Errno::ECONNREFUSED.new) end context 'and db_failover config option is turned off' do
    1
    Merge pull request #53 from leocassarani/issue-52
    1
    .rb
    rb
    mit
    splitrb/split
    10072061
    <NME> cookie_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "rack/test" describe Split::Persistence::CookieAdapter do subject { described_class.new(context) } shared_examples "sets cookies correctly" do describe "#[] and #[]=" do it "set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "handles invalid JSON" do context.request.cookies[:split] = { value: '{"foo":2,', expires: Time.now } expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (integer)" do context.request.cookies["split"] = "2" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (array)" do context.request.cookies["split"] = "[\"foo\", \"bar\"]" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the session's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end context "when using Rack" do let(:env) { Rack::MockRequest.env_for("http://example.com:8080/") } let(:request) { Rack::Request.new(env) } let(:response) { Rack::MockResponse.new(200, {}, "") } let(:context) { double(request: request, response: response, cookies: CookiesMock.new) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(context.response.headers["Set-Cookie"]).to match(/\Asplit=%7B%22foo%22%3A%22FOO%22%2C%22bar%22%3A%22BAR%22%7D; path=\/; expires=[a-zA-Z]{3}, \d{2} [a-zA-Z]{3} \d{4} \d{2}:\d{2}:\d{2} [A-Z]{3}\Z/) end it "ensure other added cookies are not overriden" do context.response.set_cookie "dummy", "wow" subject["foo"] = "FOO" expect(context.response.headers["Set-Cookie"]).to include("dummy=wow") expect(context.response.headers["Set-Cookie"]).to include("split=") end end context "when @context is an ActionController::Base" do before :context do require "rails" require "action_controller/railtie" end let(:context) do controller = controller_class.new if controller.respond_to?(:set_request!) controller.set_request!(ActionDispatch::Request.new({})) else # Before rails 5.0 controller.send(:"request=", ActionDispatch::Request.new({})) end response = ActionDispatch::Response.new(200, {}, "").tap do |res| res.request = controller.request end if controller.respond_to?(:set_response!) controller.set_response!(response) else # Before rails 5.0 controller.send(:set_response!, response) end controller end let(:controller_class) { Class.new(ActionController::Base) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(subject.keys).to eq(["foo", "bar"]) expect(subject["foo"]).to eq("FOO") expect(subject["bar"]).to eq("BAR") cookie_jar = context.request.env["action_dispatch.cookies"] expect(cookie_jar["split"]).to eq('{"foo":"FOO","bar":"BAR"}') end end end <MSG> Fix spec for parsing invalid JSON The cookie adapter uses string as a key, so should the spec. Also, context.request.cookies is a hash in both cases, it feels that it should be set directly, not using a hash with "value" and "expires" keys. <DFF> @@ -14,10 +14,8 @@ describe Split::Persistence::CookieAdapter do end it "handles invalid JSON" do - context.request.cookies[:split] = { - value: '{"foo":2,', - expires: Time.now - } + context.request.cookies["split"] = "{\"foo\":2," + expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value")
    2
    Fix spec for parsing invalid JSON
    4
    .rb
    rb
    mit
    splitrb/split
    10072062
    <NME> cookie_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "rack/test" describe Split::Persistence::CookieAdapter do subject { described_class.new(context) } shared_examples "sets cookies correctly" do describe "#[] and #[]=" do it "set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "handles invalid JSON" do context.request.cookies[:split] = { value: '{"foo":2,', expires: Time.now } expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (integer)" do context.request.cookies["split"] = "2" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (array)" do context.request.cookies["split"] = "[\"foo\", \"bar\"]" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the session's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end context "when using Rack" do let(:env) { Rack::MockRequest.env_for("http://example.com:8080/") } let(:request) { Rack::Request.new(env) } let(:response) { Rack::MockResponse.new(200, {}, "") } let(:context) { double(request: request, response: response, cookies: CookiesMock.new) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(context.response.headers["Set-Cookie"]).to match(/\Asplit=%7B%22foo%22%3A%22FOO%22%2C%22bar%22%3A%22BAR%22%7D; path=\/; expires=[a-zA-Z]{3}, \d{2} [a-zA-Z]{3} \d{4} \d{2}:\d{2}:\d{2} [A-Z]{3}\Z/) end it "ensure other added cookies are not overriden" do context.response.set_cookie "dummy", "wow" subject["foo"] = "FOO" expect(context.response.headers["Set-Cookie"]).to include("dummy=wow") expect(context.response.headers["Set-Cookie"]).to include("split=") end end context "when @context is an ActionController::Base" do before :context do require "rails" require "action_controller/railtie" end let(:context) do controller = controller_class.new if controller.respond_to?(:set_request!) controller.set_request!(ActionDispatch::Request.new({})) else # Before rails 5.0 controller.send(:"request=", ActionDispatch::Request.new({})) end response = ActionDispatch::Response.new(200, {}, "").tap do |res| res.request = controller.request end if controller.respond_to?(:set_response!) controller.set_response!(response) else # Before rails 5.0 controller.send(:set_response!, response) end controller end let(:controller_class) { Class.new(ActionController::Base) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(subject.keys).to eq(["foo", "bar"]) expect(subject["foo"]).to eq("FOO") expect(subject["bar"]).to eq("BAR") cookie_jar = context.request.env["action_dispatch.cookies"] expect(cookie_jar["split"]).to eq('{"foo":"FOO","bar":"BAR"}') end end end <MSG> Fix spec for parsing invalid JSON The cookie adapter uses string as a key, so should the spec. Also, context.request.cookies is a hash in both cases, it feels that it should be set directly, not using a hash with "value" and "expires" keys. <DFF> @@ -14,10 +14,8 @@ describe Split::Persistence::CookieAdapter do end it "handles invalid JSON" do - context.request.cookies[:split] = { - value: '{"foo":2,', - expires: Time.now - } + context.request.cookies["split"] = "{\"foo\":2," + expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value")
    2
    Fix spec for parsing invalid JSON
    4
    .rb
    rb
    mit
    splitrb/split
    10072063
    <NME> cookie_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "rack/test" describe Split::Persistence::CookieAdapter do subject { described_class.new(context) } shared_examples "sets cookies correctly" do describe "#[] and #[]=" do it "set and return the value for given key" do subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "handles invalid JSON" do context.request.cookies[:split] = { value: '{"foo":2,', expires: Time.now } expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (integer)" do context.request.cookies["split"] = "2" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end it "ignores valid JSON of invalid type (array)" do context.request.cookies["split"] = "[\"foo\", \"bar\"]" expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value") end end describe "#delete" do it "should delete the given key" do subject["my_key"] = "my_value" subject.delete("my_key") expect(subject["my_key"]).to be_nil end end describe "#keys" do it "should return an array of the session's stored keys" do subject["my_key"] = "my_value" subject["my_second_key"] = "my_second_value" expect(subject.keys).to match(["my_key", "my_second_key"]) end end end context "when using Rack" do let(:env) { Rack::MockRequest.env_for("http://example.com:8080/") } let(:request) { Rack::Request.new(env) } let(:response) { Rack::MockResponse.new(200, {}, "") } let(:context) { double(request: request, response: response, cookies: CookiesMock.new) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(context.response.headers["Set-Cookie"]).to match(/\Asplit=%7B%22foo%22%3A%22FOO%22%2C%22bar%22%3A%22BAR%22%7D; path=\/; expires=[a-zA-Z]{3}, \d{2} [a-zA-Z]{3} \d{4} \d{2}:\d{2}:\d{2} [A-Z]{3}\Z/) end it "ensure other added cookies are not overriden" do context.response.set_cookie "dummy", "wow" subject["foo"] = "FOO" expect(context.response.headers["Set-Cookie"]).to include("dummy=wow") expect(context.response.headers["Set-Cookie"]).to include("split=") end end context "when @context is an ActionController::Base" do before :context do require "rails" require "action_controller/railtie" end let(:context) do controller = controller_class.new if controller.respond_to?(:set_request!) controller.set_request!(ActionDispatch::Request.new({})) else # Before rails 5.0 controller.send(:"request=", ActionDispatch::Request.new({})) end response = ActionDispatch::Response.new(200, {}, "").tap do |res| res.request = controller.request end if controller.respond_to?(:set_response!) controller.set_response!(response) else # Before rails 5.0 controller.send(:set_response!, response) end controller end let(:controller_class) { Class.new(ActionController::Base) } include_examples "sets cookies correctly" it "puts multiple experiments in a single cookie" do subject["foo"] = "FOO" subject["bar"] = "BAR" expect(subject.keys).to eq(["foo", "bar"]) expect(subject["foo"]).to eq("FOO") expect(subject["bar"]).to eq("BAR") cookie_jar = context.request.env["action_dispatch.cookies"] expect(cookie_jar["split"]).to eq('{"foo":"FOO","bar":"BAR"}') end end end <MSG> Fix spec for parsing invalid JSON The cookie adapter uses string as a key, so should the spec. Also, context.request.cookies is a hash in both cases, it feels that it should be set directly, not using a hash with "value" and "expires" keys. <DFF> @@ -14,10 +14,8 @@ describe Split::Persistence::CookieAdapter do end it "handles invalid JSON" do - context.request.cookies[:split] = { - value: '{"foo":2,', - expires: Time.now - } + context.request.cookies["split"] = "{\"foo\":2," + expect(subject["my_key"]).to be_nil subject["my_key"] = "my_value" expect(subject["my_key"]).to eq("my_value")
    2
    Fix spec for parsing invalid JSON
    4
    .rb
    rb
    mit
    splitrb/split
    10072064
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Replace usage of SimpleRandom with RubyStats <DFF> @@ -31,7 +31,7 @@ Gem::Specification.new do |s| s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' - s.add_dependency 'simple-random', '>= 0.9.3' + s.add_dependency 'rubystats', '>= 0.3.0' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15'
    1
    Replace usage of SimpleRandom with RubyStats
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072065
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Replace usage of SimpleRandom with RubyStats <DFF> @@ -31,7 +31,7 @@ Gem::Specification.new do |s| s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' - s.add_dependency 'simple-random', '>= 0.9.3' + s.add_dependency 'rubystats', '>= 0.3.0' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15'
    1
    Replace usage of SimpleRandom with RubyStats
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072066
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random', '>= 0.9.3' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15' s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Replace usage of SimpleRandom with RubyStats <DFF> @@ -31,7 +31,7 @@ Gem::Specification.new do |s| s.add_dependency 'redis', '>= 2.1' s.add_dependency 'sinatra', '>= 1.2.6' - s.add_dependency 'simple-random', '>= 0.9.3' + s.add_dependency 'rubystats', '>= 0.3.0' s.add_development_dependency 'bundler', '>= 1.17' s.add_development_dependency 'simplecov', '~> 0.15'
    1
    Replace usage of SimpleRandom with RubyStats
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072067
    <NME> split.rb <BEF> # frozen_string_literal: true require "redis" require "split/algorithms" require "split/algorithms/block_randomization" require "split/algorithms/weighted_sample" require "split/algorithms/whiplash" require "split/alternative" require "split/cache" require "split/configuration" require "split/encapsulated_helper" require "split/exceptions" require "split/experiment" require "split/experiment_catalog" require "split/extensions/string" require "split/goals_collection" require "split/helper" require "split/combined_experiments_helper" require "split/metric" require "split/persistence" require "split/redis_interface" require "split/trial" require "split/user" require "split/version" require "split/zscore" require "split/engine" if defined?(Rails) module Split extend self attr_accessor :configuration # Accepts: # 1. A redis URL (valid for `Redis.new(url: url)`) # 2. an options hash compatible with `Redis.new` # 3. or a valid Redis instance (one that responds to `#smembers`). Likely, # this will be an instance of either `Redis`, `Redis::Client`, # `Redis::DistRedis`, or `Redis::Namespace`. def redis=(server) @redis = if server.is_a?(String) Redis.new(url: server) elsif server.is_a?(Hash) Redis.new(server) elsif server.respond_to?(:smembers) server else raise ArgumentError, "You must supply a url, options hash or valid Redis connection instance" end end # Returns the current Redis connection. If none has been created, will # create a new one. def redis return @redis if @redis self.redis = self.configuration.redis self.redis end # Call this method to modify defaults in your initializers. # # @example # Split.configure do |config| # config.ignore_ip_addresses = '192.168.2.1' # end end end Split.configure {} if defined?(::Rails) class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure { } } end else Split.configure { } end <MSG> Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails Check to see if being run in Rails application and run in before_initialize <DFF> @@ -66,4 +66,11 @@ module Split end end -Split.configure {} +# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first. +if defined?(::Rails) + class Railtie < Rails::Railtie + config.before_initialize { Split.configure {} } + end +else + Split.configure {} +end
    8
    Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails
    1
    .rb
    rb
    mit
    splitrb/split
    10072068
    <NME> split.rb <BEF> # frozen_string_literal: true require "redis" require "split/algorithms" require "split/algorithms/block_randomization" require "split/algorithms/weighted_sample" require "split/algorithms/whiplash" require "split/alternative" require "split/cache" require "split/configuration" require "split/encapsulated_helper" require "split/exceptions" require "split/experiment" require "split/experiment_catalog" require "split/extensions/string" require "split/goals_collection" require "split/helper" require "split/combined_experiments_helper" require "split/metric" require "split/persistence" require "split/redis_interface" require "split/trial" require "split/user" require "split/version" require "split/zscore" require "split/engine" if defined?(Rails) module Split extend self attr_accessor :configuration # Accepts: # 1. A redis URL (valid for `Redis.new(url: url)`) # 2. an options hash compatible with `Redis.new` # 3. or a valid Redis instance (one that responds to `#smembers`). Likely, # this will be an instance of either `Redis`, `Redis::Client`, # `Redis::DistRedis`, or `Redis::Namespace`. def redis=(server) @redis = if server.is_a?(String) Redis.new(url: server) elsif server.is_a?(Hash) Redis.new(server) elsif server.respond_to?(:smembers) server else raise ArgumentError, "You must supply a url, options hash or valid Redis connection instance" end end # Returns the current Redis connection. If none has been created, will # create a new one. def redis return @redis if @redis self.redis = self.configuration.redis self.redis end # Call this method to modify defaults in your initializers. # # @example # Split.configure do |config| # config.ignore_ip_addresses = '192.168.2.1' # end end end Split.configure {} if defined?(::Rails) class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure { } } end else Split.configure { } end <MSG> Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails Check to see if being run in Rails application and run in before_initialize <DFF> @@ -66,4 +66,11 @@ module Split end end -Split.configure {} +# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first. +if defined?(::Rails) + class Railtie < Rails::Railtie + config.before_initialize { Split.configure {} } + end +else + Split.configure {} +end
    8
    Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails
    1
    .rb
    rb
    mit
    splitrb/split
    10072069
    <NME> split.rb <BEF> # frozen_string_literal: true require "redis" require "split/algorithms" require "split/algorithms/block_randomization" require "split/algorithms/weighted_sample" require "split/algorithms/whiplash" require "split/alternative" require "split/cache" require "split/configuration" require "split/encapsulated_helper" require "split/exceptions" require "split/experiment" require "split/experiment_catalog" require "split/extensions/string" require "split/goals_collection" require "split/helper" require "split/combined_experiments_helper" require "split/metric" require "split/persistence" require "split/redis_interface" require "split/trial" require "split/user" require "split/version" require "split/zscore" require "split/engine" if defined?(Rails) module Split extend self attr_accessor :configuration # Accepts: # 1. A redis URL (valid for `Redis.new(url: url)`) # 2. an options hash compatible with `Redis.new` # 3. or a valid Redis instance (one that responds to `#smembers`). Likely, # this will be an instance of either `Redis`, `Redis::Client`, # `Redis::DistRedis`, or `Redis::Namespace`. def redis=(server) @redis = if server.is_a?(String) Redis.new(url: server) elsif server.is_a?(Hash) Redis.new(server) elsif server.respond_to?(:smembers) server else raise ArgumentError, "You must supply a url, options hash or valid Redis connection instance" end end # Returns the current Redis connection. If none has been created, will # create a new one. def redis return @redis if @redis self.redis = self.configuration.redis self.redis end # Call this method to modify defaults in your initializers. # # @example # Split.configure do |config| # config.ignore_ip_addresses = '192.168.2.1' # end end end Split.configure {} if defined?(::Rails) class Split::Railtie < Rails::Railtie config.before_initialize { Split.configure { } } end else Split.configure { } end <MSG> Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails Check to see if being run in Rails application and run in before_initialize <DFF> @@ -66,4 +66,11 @@ module Split end end -Split.configure {} +# Check to see if being run in a Rails application. If so, wait until before_initialize to run configuration so Gems that create ENV variables have the chance to initialize first. +if defined?(::Rails) + class Railtie < Rails::Railtie + config.before_initialize { Split.configure {} } + end +else + Split.configure {} +end
    8
    Merge pull request #555 from husteadrobert/run_configure_after_initialize_on_rails
    1
    .rb
    rb
    mit
    splitrb/split
    10072070
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 3.0' end s.add_dependency "sinatra", ">= 1.2.6" s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Lock rspec to 3.1.x for now <DFF> @@ -29,5 +29,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' - s.add_development_dependency 'rspec', '~> 3.0' + s.add_development_dependency 'rspec', '~> 3.1.0' end
    1
    Lock rspec to 3.1.x for now
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072071
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 3.0' end s.add_dependency "sinatra", ">= 1.2.6" s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Lock rspec to 3.1.x for now <DFF> @@ -29,5 +29,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' - s.add_development_dependency 'rspec', '~> 3.0' + s.add_development_dependency 'rspec', '~> 3.1.0' end
    1
    Lock rspec to 3.1.x for now
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072072
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.required_ruby_version = ">= 2.5.0" s.required_rubygems_version = ">= 2.0.0" s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '~> 3.0' end s.add_dependency "sinatra", ">= 1.2.6" s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Lock rspec to 3.1.x for now <DFF> @@ -29,5 +29,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'coveralls' s.add_development_dependency 'rack-test' s.add_development_dependency 'rake' - s.add_development_dependency 'rspec', '~> 3.0' + s.add_development_dependency 'rspec', '~> 3.1.0' end
    1
    Lock rspec to 3.1.x for now
    1
    .gemspec
    gemspec
    mit
    splitrb/split
    10072073
    <NME> forms.py <BEF> import os from django import forms from django.conf import settings from djangopypi.models import Project, Classifier, Release from django.utils.translation import ugettext_lazy as _ class ProjectForm(forms.ModelForm): class Meta: model = Project exclude = ['owner', 'classifiers'] class ReleaseForm(forms.ModelForm): class Meta: model = Release exclude = ['project'] class SearchForm(forms.Form): search_value = forms.CharField(max_length=200) <MSG> Integrated djangopypi search engine - TODO: Functional Tests <DFF> @@ -14,8 +14,4 @@ class ProjectForm(forms.ModelForm): class ReleaseForm(forms.ModelForm): class Meta: model = Release - exclude = ['project'] - -class SearchForm(forms.Form): - search_value = forms.CharField(max_length=200) - + exclude = ['project'] \ No newline at end of file
    1
    Integrated djangopypi search engine - TODO: Functional Tests
    5
    .py
    py
    bsd-3-clause
    ask/chishop
    10072074
    <NME> index.ts <BEF> import { Abbreviation } from '@emmetio/abbreviation'; import { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, convertSnippets as parseStylesheetSnippets, CSSAbbreviationScope } from './stylesheet'; import resolveConfig, { UserConfig, Config } from './config'; export default function expandAbbreviation(abbr: string, config?: UserConfig): string { const resolvedConfig = resolveConfig(config); return resolvedConfig.type === 'stylesheet' ? stylesheet(abbr, resolvedConfig) : markup(abbr, resolvedConfig); } /** * Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that * produces structured output like HTML) and outputs it according to options * provided in config */ export function markup(abbr: string | Abbreviation, config: Config) { return stringifyMarkup(parseMarkup(abbr, config), config); } /** * Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for * stylesheet languages like CSS, SASS etc.) and outputs it according to options * provided in config */ export function stylesheet(abbr: string | CSSAbbreviation, config: Config) { return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config'; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config'; <MSG> Export abbreviation parsers from module <DFF> @@ -1,5 +1,5 @@ -import { Abbreviation } from '@emmetio/abbreviation'; -import { CSSAbbreviation } from '@emmetio/css-abbreviation'; +import markupAbbreviation, { Abbreviation } from '@emmetio/abbreviation'; +import stylesheetAbbreviation, { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, @@ -33,6 +33,9 @@ export function stylesheet(abbr: string | CSSAbbreviation, config: Config, snipp return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } -export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; +export { + markupAbbreviation, parseMarkup, stringifyMarkup, + stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets +}; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
    6
    Export abbreviation parsers from module
    3
    .ts
    ts
    mit
    emmetio/emmet
    10072075
    <NME> index.ts <BEF> import { Abbreviation } from '@emmetio/abbreviation'; import { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, convertSnippets as parseStylesheetSnippets, CSSAbbreviationScope } from './stylesheet'; import resolveConfig, { UserConfig, Config } from './config'; export default function expandAbbreviation(abbr: string, config?: UserConfig): string { const resolvedConfig = resolveConfig(config); return resolvedConfig.type === 'stylesheet' ? stylesheet(abbr, resolvedConfig) : markup(abbr, resolvedConfig); } /** * Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that * produces structured output like HTML) and outputs it according to options * provided in config */ export function markup(abbr: string | Abbreviation, config: Config) { return stringifyMarkup(parseMarkup(abbr, config), config); } /** * Expands given *stylesheet* abbreviation (a special Emmet abbreviation designed for * stylesheet languages like CSS, SASS etc.) and outputs it according to options * provided in config */ export function stylesheet(abbr: string | CSSAbbreviation, config: Config) { return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config'; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, AbbreviationContext, default as resolveConfig } from './config'; <MSG> Export abbreviation parsers from module <DFF> @@ -1,5 +1,5 @@ -import { Abbreviation } from '@emmetio/abbreviation'; -import { CSSAbbreviation } from '@emmetio/css-abbreviation'; +import markupAbbreviation, { Abbreviation } from '@emmetio/abbreviation'; +import stylesheetAbbreviation, { CSSAbbreviation } from '@emmetio/css-abbreviation'; import parseMarkup, { stringify as stringifyMarkup } from './markup'; import parseStylesheet, { stringify as stringifyStylesheet, @@ -33,6 +33,9 @@ export function stylesheet(abbr: string | CSSAbbreviation, config: Config, snipp return stringifyStylesheet(parseStylesheet(abbr, config, snippets), config); } -export { parseMarkup, stringifyMarkup, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets }; +export { + markupAbbreviation, parseMarkup, stringifyMarkup, + stylesheetAbbreviation, parseStylesheet, stringifyStylesheet, parseStylesheetSnippets +}; export { default as extract, ExtractOptions, ExtractedAbbreviation } from './extract-abbreviation'; export { GlobalConfig, SyntaxType, Config, UserConfig, Options, default as resolveConfig } from './config';
    6
    Export abbreviation parsers from module
    3
    .ts
    ts
    mit
    emmetio/emmet
    10072076
    <NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/SpaceInsideBlockBraces <DFF> @@ -29,7 +29,7 @@ module Split if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) - count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} + count_control = experiments.count { |k, v| k == experiment_key_without_version || v == 'control' } experiments.size > count_control else !Split.configuration.allow_multiple_experiments &&
    1
    Fix Layout/SpaceInsideBlockBraces
    1
    .rb
    rb
    mit
    splitrb/split
    10072077
    <NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/SpaceInsideBlockBraces <DFF> @@ -29,7 +29,7 @@ module Split if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) - count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} + count_control = experiments.count { |k, v| k == experiment_key_without_version || v == 'control' } experiments.size > count_control else !Split.configuration.allow_multiple_experiments &&
    1
    Fix Layout/SpaceInsideBlockBraces
    1
    .rb
    rb
    mit
    splitrb/split
    10072078
    <NME> user.rb <BEF> # frozen_string_literal: true require "forwardable" module Split class User extend Forwardable def_delegators :@user, :keys, :[], :[]=, :delete attr_reader :user def initialize(context, adapter = nil) @user = adapter || Split::Persistence.adapter.new(context) @cleaned_up = false end def cleanup_old_experiments! return if @cleaned_up keys_without_finished(user.keys).each do |key| experiment = ExperimentCatalog.find key_without_version(key) if experiment.nil? || experiment.has_winner? || experiment.start_time.nil? user.delete key user.delete Experiment.finished_key(key) end end @cleaned_up = true end def max_experiments_reached?(experiment_key) if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} experiments.size > count_control else !Split.configuration.allow_multiple_experiments && keys_without_experiment(user.keys, experiment_key).length > 0 end end def cleanup_old_versions!(experiment) keys = user.keys.select { |k| key_without_version(k) == experiment.name } keys_without_experiment(keys, experiment.key).each { |key| user.delete(key) } end def active_experiments experiment_pairs = {} keys_without_finished(user.keys).each do |key| Metric.possible_experiments(key_without_version(key)).each do |experiment| if !experiment.has_winner? experiment_pairs[key_without_version(key)] = user[key] end end end experiment_pairs end def self.find(user_id, adapter) adapter = adapter.is_a?(Symbol) ? Split::Persistence::ADAPTERS[adapter] : adapter if adapter.respond_to?(:find) User.new(nil, adapter.find(user_id)) else nil end end private def keys_without_experiment(keys, experiment_key) keys.reject { |k| k.match(Regexp.new("^#{experiment_key}(:finished)?$")) } end def keys_without_finished(keys) keys.reject { |k| k.include?(":finished") } end def key_without_version(key) key.split(/\:\d(?!\:)/)[0] end end end <MSG> Fix Layout/SpaceInsideBlockBraces <DFF> @@ -29,7 +29,7 @@ module Split if Split.configuration.allow_multiple_experiments == 'control' experiments = active_experiments experiment_key_without_version = key_without_version(experiment_key) - count_control = experiments.count {|k, v| k == experiment_key_without_version || v == 'control'} + count_control = experiments.count { |k, v| k == experiment_key_without_version || v == 'control' } experiments.size > count_control else !Split.configuration.allow_multiple_experiments &&
    1
    Fix Layout/SpaceInsideBlockBraces
    1
    .rb
    rb
    mit
    splitrb/split
    10072079
    <NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end describe 'ab_finished' do before(:each) do @experiment_name = 'link_color' @alternatives = ['blue', 'red'] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it 'should increment the counter for the completed alternative' do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, {:reset => false}) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it 'should not increment the counter if reset is false and the experiment has been already finished' do 2.times { ab_finished(@experiment_name, {:reset => false}) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it 'should not increment the counter for an experiment that the user is not participating in' do ab_test('button_size', 'small', 'big') # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } end it 'should not increment the counter for an ended experiment' do e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') e.winner = 'small' a = ab_test('button_size', 'small', 'big') expect(a).to eq('small') expect(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, {:reset => false}) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should do nothing where the experiment was not started by this user" do ab_user = nil expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #577 from gnanou/finish_inactive_experiment Handle correctly case when ab_finished is called before ab_test for a user <DFF> @@ -296,98 +296,126 @@ describe Split::Helper do end describe 'ab_finished' do - before(:each) do - @experiment_name = 'link_color' - @alternatives = ['blue', 'red'] - @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) - @alternative_name = ab_test(@experiment_name, *@alternatives) - @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - end + context 'for an experiment that the user participates in' do + before(:each) do + @experiment_name = 'link_color' + @alternatives = ['blue', 'red'] + @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) + @alternative_name = ab_test(@experiment_name, *@alternatives) + @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + end - it 'should increment the counter for the completed alternative' do - ab_finished(@experiment_name) - new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - expect(new_completion_count).to eq(@previous_completion_count + 1) - end + it 'should increment the counter for the completed alternative' do + ab_finished(@experiment_name) + new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + expect(new_completion_count).to eq(@previous_completion_count + 1) + end - it "should set experiment's finished key if reset is false" do - ab_finished(@experiment_name, {:reset => false}) - expect(ab_user[@experiment.key]).to eq(@alternative_name) - expect(ab_user[@experiment.finished_key]).to eq(true) - end + it "should set experiment's finished key if reset is false" do + ab_finished(@experiment_name, {:reset => false}) + expect(ab_user[@experiment.key]).to eq(@alternative_name) + expect(ab_user[@experiment.finished_key]).to eq(true) + end - it 'should not increment the counter if reset is false and the experiment has been already finished' do - 2.times { ab_finished(@experiment_name, {:reset => false}) } - new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - expect(new_completion_count).to eq(@previous_completion_count + 1) - end + it 'should not increment the counter if reset is false and the experiment has been already finished' do + 2.times { ab_finished(@experiment_name, {:reset => false}) } + new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + expect(new_completion_count).to eq(@previous_completion_count + 1) + end - it 'should not increment the counter for an experiment that the user is not participating in' do - ab_test('button_size', 'small', 'big') + it 'should not increment the counter for an ended experiment' do + e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') + e.winner = 'small' + a = ab_test('button_size', 'small', 'big') + expect(a).to eq('small') + expect(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } + end - # So, user should be participating in the link_color experiment and - # receive the control for button_size. As the user is not participating in - # the button size experiment, finishing it should not increase the - # completion count for that alternative. - expect(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } - end + it "should clear out the user's participation from their session" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it 'should not increment the counter for an ended experiment' do - e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') - e.winner = 'small' - a = ab_test('button_size', 'small', 'big') - expect(a).to eq('small') - expect(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } - end + it "should not clear out the users session if reset is false" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name, {:reset => false}) + expect(ab_user[@experiment.key]).to eq(@alternative_name) + expect(ab_user[@experiment.finished_key]).to eq(true) + end - it "should clear out the user's participation from their session" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty - end + it "should reset the users session when experiment is not versioned" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it "should not clear out the users session if reset is false" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name, {:reset => false}) - expect(ab_user[@experiment.key]).to eq(@alternative_name) - expect(ab_user[@experiment.finished_key]).to eq(true) - end + it "should reset the users session when experiment is versioned" do + @experiment.increment_version + @alternative_name = ab_test(@experiment_name, *@alternatives) - it "should reset the users session when experiment is not versioned" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty - end + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it "should reset the users session when experiment is versioned" do - @experiment.increment_version - @alternative_name = ab_test(@experiment_name, *@alternatives) + context "when on_trial_complete is set" do + before { Split.configuration.on_trial_complete = :some_method } + it "should call the method" do + expect(self).to receive(:some_method) + ab_finished(@experiment_name) + end - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty + it "should not call the method without alternative" do + ab_user[@experiment.key] = nil + expect(self).not_to receive(:some_method) + ab_finished(@experiment_name) + end + end end - it "should do nothing where the experiment was not started by this user" do - ab_user = nil - expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception + context 'for an experiment that the user is excluded from' do + before do + alternative = ab_test('link_color', 'blue', 'red') + expect(Split::Alternative.new(alternative, 'link_color').participant_count).to eq(1) + alternative = ab_test('button_size', 'small', 'big') + expect(Split::Alternative.new(alternative, 'button_size').participant_count).to eq(0) + end + + it 'should not increment the completed counter' do + # So, user should be participating in the link_color experiment and + # receive the control for button_size. As the user is not participating in + # the button size experiment, finishing it should not increase the + # completion count for that alternative. + expect(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } + end end - context "when on_trial_complete is set" do - before { Split.configuration.on_trial_complete = :some_method } - it "should call the method" do - expect(self).to receive(:some_method) - ab_finished(@experiment_name) + context 'for an experiment that the user does not participate in' do + before do + Split::ExperimentCatalog.find_or_create(:not_started_experiment, 'control', 'alt') + end + it 'should not raise an exception' do + expect { ab_finished(:not_started_experiment) }.not_to raise_exception end - it "should not call the method without alternative" do - ab_user[@experiment.key] = nil - expect(self).not_to receive(:some_method) - ab_finished(@experiment_name) + it 'should not change the user state when reset is false' do + expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys}.from([]) + end + + it 'should not change the user state when reset is true' do + expect(self).not_to receive(:reset!) + ab_finished(:not_started_experiment) + end + + it 'should not increment the completed counter' do + ab_finished(:not_started_experiment) + expect(Split::Alternative.new('control', :not_started_experiment).completed_count).to eq(0) + expect(Split::Alternative.new('alt', :not_started_experiment).completed_count).to eq(0) end end end
    103
    Merge pull request #577 from gnanou/finish_inactive_experiment
    75
    .rb
    rb
    mit
    splitrb/split
    10072080
    <NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end describe 'ab_finished' do before(:each) do @experiment_name = 'link_color' @alternatives = ['blue', 'red'] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it 'should increment the counter for the completed alternative' do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, {:reset => false}) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it 'should not increment the counter if reset is false and the experiment has been already finished' do 2.times { ab_finished(@experiment_name, {:reset => false}) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it 'should not increment the counter for an experiment that the user is not participating in' do ab_test('button_size', 'small', 'big') # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } end it 'should not increment the counter for an ended experiment' do e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') e.winner = 'small' a = ab_test('button_size', 'small', 'big') expect(a).to eq('small') expect(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, {:reset => false}) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should do nothing where the experiment was not started by this user" do ab_user = nil expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #577 from gnanou/finish_inactive_experiment Handle correctly case when ab_finished is called before ab_test for a user <DFF> @@ -296,98 +296,126 @@ describe Split::Helper do end describe 'ab_finished' do - before(:each) do - @experiment_name = 'link_color' - @alternatives = ['blue', 'red'] - @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) - @alternative_name = ab_test(@experiment_name, *@alternatives) - @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - end + context 'for an experiment that the user participates in' do + before(:each) do + @experiment_name = 'link_color' + @alternatives = ['blue', 'red'] + @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) + @alternative_name = ab_test(@experiment_name, *@alternatives) + @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + end - it 'should increment the counter for the completed alternative' do - ab_finished(@experiment_name) - new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - expect(new_completion_count).to eq(@previous_completion_count + 1) - end + it 'should increment the counter for the completed alternative' do + ab_finished(@experiment_name) + new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + expect(new_completion_count).to eq(@previous_completion_count + 1) + end - it "should set experiment's finished key if reset is false" do - ab_finished(@experiment_name, {:reset => false}) - expect(ab_user[@experiment.key]).to eq(@alternative_name) - expect(ab_user[@experiment.finished_key]).to eq(true) - end + it "should set experiment's finished key if reset is false" do + ab_finished(@experiment_name, {:reset => false}) + expect(ab_user[@experiment.key]).to eq(@alternative_name) + expect(ab_user[@experiment.finished_key]).to eq(true) + end - it 'should not increment the counter if reset is false and the experiment has been already finished' do - 2.times { ab_finished(@experiment_name, {:reset => false}) } - new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - expect(new_completion_count).to eq(@previous_completion_count + 1) - end + it 'should not increment the counter if reset is false and the experiment has been already finished' do + 2.times { ab_finished(@experiment_name, {:reset => false}) } + new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + expect(new_completion_count).to eq(@previous_completion_count + 1) + end - it 'should not increment the counter for an experiment that the user is not participating in' do - ab_test('button_size', 'small', 'big') + it 'should not increment the counter for an ended experiment' do + e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') + e.winner = 'small' + a = ab_test('button_size', 'small', 'big') + expect(a).to eq('small') + expect(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } + end - # So, user should be participating in the link_color experiment and - # receive the control for button_size. As the user is not participating in - # the button size experiment, finishing it should not increase the - # completion count for that alternative. - expect(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } - end + it "should clear out the user's participation from their session" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it 'should not increment the counter for an ended experiment' do - e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') - e.winner = 'small' - a = ab_test('button_size', 'small', 'big') - expect(a).to eq('small') - expect(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } - end + it "should not clear out the users session if reset is false" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name, {:reset => false}) + expect(ab_user[@experiment.key]).to eq(@alternative_name) + expect(ab_user[@experiment.finished_key]).to eq(true) + end - it "should clear out the user's participation from their session" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty - end + it "should reset the users session when experiment is not versioned" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it "should not clear out the users session if reset is false" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name, {:reset => false}) - expect(ab_user[@experiment.key]).to eq(@alternative_name) - expect(ab_user[@experiment.finished_key]).to eq(true) - end + it "should reset the users session when experiment is versioned" do + @experiment.increment_version + @alternative_name = ab_test(@experiment_name, *@alternatives) - it "should reset the users session when experiment is not versioned" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty - end + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it "should reset the users session when experiment is versioned" do - @experiment.increment_version - @alternative_name = ab_test(@experiment_name, *@alternatives) + context "when on_trial_complete is set" do + before { Split.configuration.on_trial_complete = :some_method } + it "should call the method" do + expect(self).to receive(:some_method) + ab_finished(@experiment_name) + end - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty + it "should not call the method without alternative" do + ab_user[@experiment.key] = nil + expect(self).not_to receive(:some_method) + ab_finished(@experiment_name) + end + end end - it "should do nothing where the experiment was not started by this user" do - ab_user = nil - expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception + context 'for an experiment that the user is excluded from' do + before do + alternative = ab_test('link_color', 'blue', 'red') + expect(Split::Alternative.new(alternative, 'link_color').participant_count).to eq(1) + alternative = ab_test('button_size', 'small', 'big') + expect(Split::Alternative.new(alternative, 'button_size').participant_count).to eq(0) + end + + it 'should not increment the completed counter' do + # So, user should be participating in the link_color experiment and + # receive the control for button_size. As the user is not participating in + # the button size experiment, finishing it should not increase the + # completion count for that alternative. + expect(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } + end end - context "when on_trial_complete is set" do - before { Split.configuration.on_trial_complete = :some_method } - it "should call the method" do - expect(self).to receive(:some_method) - ab_finished(@experiment_name) + context 'for an experiment that the user does not participate in' do + before do + Split::ExperimentCatalog.find_or_create(:not_started_experiment, 'control', 'alt') + end + it 'should not raise an exception' do + expect { ab_finished(:not_started_experiment) }.not_to raise_exception end - it "should not call the method without alternative" do - ab_user[@experiment.key] = nil - expect(self).not_to receive(:some_method) - ab_finished(@experiment_name) + it 'should not change the user state when reset is false' do + expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys}.from([]) + end + + it 'should not change the user state when reset is true' do + expect(self).not_to receive(:reset!) + ab_finished(:not_started_experiment) + end + + it 'should not increment the completed counter' do + ab_finished(:not_started_experiment) + expect(Split::Alternative.new('control', :not_started_experiment).completed_count).to eq(0) + expect(Split::Alternative.new('alt', :not_started_experiment).completed_count).to eq(0) end end end
    103
    Merge pull request #577 from gnanou/finish_inactive_experiment
    75
    .rb
    rb
    mit
    splitrb/split
    10072081
    <NME> helper_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" # TODO change some of these tests to use Rack::Test describe Split::Helper do include Split::Helper let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red") } describe "ab_test" do it "should not raise an error when passed strings for alternatives" do expect { ab_test("xyz", "1", "2", "3") }.not_to raise_error end it "should not raise an error when passed an array for alternatives" do expect { ab_test("xyz", ["1", "2", "3"]) }.not_to raise_error end it "should raise the appropriate error when passed integers for alternatives" do expect { ab_test("xyz", 1, 2, 3) }.to raise_error(ArgumentError) end it "should raise the appropriate error when passed symbols for alternatives" do expect { ab_test("xyz", :a, :b, :c) }.to raise_error(ArgumentError) end it "should not raise error when passed an array for goals" do expect { ab_test({ "link_color" => ["purchase", "refund"] }, "blue", "red") }.not_to raise_error end it "should not raise error when passed just one goal" do expect { ab_test({ "link_color" => "purchase" }, "blue", "red") }.not_to raise_error end it "raises an appropriate error when processing combined expirements" do Split.configuration.experiments = { combined_exp_1: { alternatives: [ { name: "control", percent: 50 }, { name: "test-alt", percent: 50 } ], metric: :my_metric, combined_experiments: [:combined_exp_1_sub_1] } } Split::ExperimentCatalog.find_or_create("combined_exp_1") expect { ab_test("combined_exp_1") }.to raise_error(Split::InvalidExperimentsFormatError) end it "should assign a random alternative to a new user when there are an equal number of alternatives assigned" do ab_test("link_color", "blue", "red") expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should increment the participation counter after assignment to a new user" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count + 1) end it "should not increment the counter for an experiment that the user is not participating in" do ab_test("link_color", "blue", "red") e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { # User shouldn't participate in this second experiment ab_test("button_size", "small", "big") }.not_to change { e.participant_count } end it "should not increment the counter for an ended experiment" do e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") e.winner = "small" expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should not increment the counter for an not started experiment" do expect(Split.configuration).to receive(:start_manually).and_return(true) e = Split::ExperimentCatalog.find_or_create("button_size", "small", "big") expect { a = ab_test("button_size", "small", "big") expect(a).to eq("small") }.not_to change { e.participant_count } end it "should return the given alternative for an existing user" do expect(ab_test("link_color", "blue", "red")).to eq ab_test("link_color", "blue", "red") end it "should always return the winner if one is present" do experiment.winner = "orange" expect(ab_test("link_color", "blue", "red")).to eq("orange") end it "should allow the alternative to be forced by passing it in the params" do # ?ab_test[link_color]=blue @params = { "ab_test" => { "link_color" => "blue" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") @params = { "ab_test" => { "link_color" => "red" } } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("red") alternative = ab_test("link_color", { "blue" => 5 }, "red" => 1) expect(alternative).to eq("red") end it "should not allow an arbitrary alternative" do @params = { "ab_test" => { "link_color" => "pink" } } alternative = ab_test("link_color", "blue") expect(alternative).to eq("blue") end it "should not store the split when a param forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end it "SPLIT_DISABLE query parameter should also force the alternative (uses control)" do @params = { "SPLIT_DISABLE" => "true" } alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq("blue") alternative = ab_test("link_color", { "blue" => 1 }, "red" => 5) expect(alternative).to eq("blue") alternative = ab_test("link_color", "red", "blue") expect(alternative).to eq("red") alternative = ab_test("link_color", { "red" => 5 }, "blue" => 1) expect(alternative).to eq("red") end it "should not store the split when Split generically disabled" do @params = { "SPLIT_DISABLE" => "true" } expect(ab_user).not_to receive(:[]=) ab_test("link_color", "blue", "red") end context "when store_override is set" do before { Split.configuration.store_override = true } it "should store the forced alternative" do @params = { "ab_test" => { "link_color" => "blue" } } expect(ab_user).to receive(:[]=).with("link_color", "blue") ab_test("link_color", "blue", "red") end end context "when on_trial_choose is set" do before { Split.configuration.on_trial_choose = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_test("link_color", "blue", "red") end end it "should allow passing a block" do alt = ab_test("link_color", "blue", "red") ret = ab_test("link_color", "blue", "red") { |alternative| "shared/#{alternative}" } expect(ret).to eq("shared/#{alt}") end it "should allow the share of visitors see an alternative to be specified" do ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 }) expect(["red", "blue"]).to include(ab_user["link_color"]) end it "should allow alternative weighting interface as a single hash" do ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.alternatives.map(&:name)).to eq(["blue", "red"]) expect(experiment.alternatives.collect { |a| a.weight }).to match_array([0.01, 0.2]) end it "should only let a user participate in one experiment at a time" do link_color = ab_test("link_color", "blue", "red") ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) big = Split::Alternative.new("big", "button_size") expect(big.participant_count).to eq(0) small = Split::Alternative.new("small", "button_size") expect(small.participant_count).to eq(0) end it "should let a user participate in many experiment with allow_multiple_experiments option" do Split.configure do |config| config.allow_multiple_experiments = true end link_color = ab_test("link_color", "blue", "red") button_size = ab_test("button_size", "small", "big") expect(ab_user["link_color"]).to eq(link_color) expect(ab_user["button_size"]).to eq(button_size) button_size_alt = Split::Alternative.new(button_size, "button_size") expect(button_size_alt.participant_count).to eq(1) end context "with allow_multiple_experiments = 'control'" do it "should let a user participate in many experiment with one non-'control' alternative" do Split.configure do |config| config.allow_multiple_experiments = "control" end groups = 100.times.map do |n| ab_test("test#{n}".to_sym, { "control" => (100 - n) }, { "test#{n}-alt" => n }) end experiments = ab_user.active_experiments expect(experiments.size).to be > 1 count_control = experiments.values.count { |g| g == "control" } expect(count_control).to eq(experiments.size - 1) count_alts = groups.count { |g| g != "control" } expect(count_alts).to eq(1) end context "when user already has experiment" do let(:mock_user) { Split::User.new(self, { "test_0" => "test-alt" }) } before do Split.configure do |config| config.allow_multiple_experiments = "control" end Split::ExperimentCatalog.find_or_initialize("test_0", "control", "test-alt").save Split::ExperimentCatalog.find_or_initialize("test_1", "control", "test-alt").save end it "should restore previously selected alternative" do expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 1 }, { "test-alt" => 100 })).to eq "test-alt" end it "should select the correct alternatives after experiment resets" do experiment = Split::ExperimentCatalog.find(:test_0) experiment.reset mock_user[experiment.key] = "test-alt" expect(ab_user.active_experiments.size).to eq 1 expect(ab_test(:test_0, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "test-alt" end it "lets override existing choice" do pending "this requires user store reset on first call not depending on whelther it is current trial" @params = { "ab_test" => { "test_1" => "test-alt" } } expect(ab_test(:test_0, { "control" => 0 }, { "test-alt" => 100 })).to eq "control" expect(ab_test(:test_1, { "control" => 100 }, { "test-alt" => 1 })).to eq "test-alt" end end end it "should not over-write a finished key when an experiment is on a later version" do experiment.increment_version ab_user = { experiment.key => "blue", experiment.finished_key => true } finished_session = ab_user.dup ab_test("link_color", "blue", "red") expect(ab_user).to eq(finished_session) end end describe "metadata" do context "is defined" do before do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, metadata: { "one" => "Meta1", "two" => "Meta2" } } } end it "should be passed to helper block" do @params = { "ab_test" => { "my_experiment" => "two" } } expect(ab_test("my_experiment")).to eq "two" expect(ab_test("my_experiment") do |alternative, meta| meta end).to eq("Meta2") end describe 'ab_finished' do before(:each) do @experiment_name = 'link_color' @alternatives = ['blue', 'red'] @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) @alternative_name = ab_test(@experiment_name, *@alternatives) @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count end it 'should increment the counter for the completed alternative' do ab_finished(@experiment_name) new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it "should set experiment's finished key if reset is false" do ab_finished(@experiment_name, {:reset => false}) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it 'should not increment the counter if reset is false and the experiment has been already finished' do 2.times { ab_finished(@experiment_name, {:reset => false}) } new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count expect(new_completion_count).to eq(@previous_completion_count + 1) end it 'should not increment the counter for an experiment that the user is not participating in' do ab_test('button_size', 'small', 'big') # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } end it 'should not increment the counter for an ended experiment' do e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') e.winner = 'small' a = ab_test('button_size', 'small', 'big') expect(a).to eq('small') expect(lambda { ab_finished('button_size') }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } end it "should clear out the user's participation from their session" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should not clear out the users session if reset is false" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name, {:reset => false}) expect(ab_user[@experiment.key]).to eq(@alternative_name) expect(ab_user[@experiment.finished_key]).to eq(true) end it "should reset the users session when experiment is not versioned" do expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should reset the users session when experiment is versioned" do @experiment.increment_version @alternative_name = ab_test(@experiment_name, *@alternatives) expect(ab_user[@experiment.key]).to eq(@alternative_name) ab_finished(@experiment_name) expect(ab_user.keys).to be_empty end it "should do nothing where the experiment was not started by this user" do ab_user = nil expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception end context "when on_trial_complete is set" do before { Split.configuration.on_trial_complete = :some_method } it "should call the method" do expect(self).to receive(:some_method) ab_finished(@experiment_name) end it "should not call the method without alternative" do ab_user[@experiment.key] = nil expect(self).not_to receive(:some_method) ab_finished(@experiment_name) end end end alternative = ab_test("link_color", "blue", "red") expect(Split::Alternative.new(alternative, "link_color").participant_count).to eq(1) alternative = ab_test("button_size", "small", "big") expect(Split::Alternative.new(alternative, "button_size").participant_count).to eq(0) end it "should not increment the completed counter" do # So, user should be participating in the link_color experiment and # receive the control for button_size. As the user is not participating in # the button size experiment, finishing it should not increase the # completion count for that alternative. expect { ab_finished("button_size") }.not_to change { Split::Alternative.new("small", "button_size").completed_count } end end context "for an experiment that the user does not participate in" do before do Split::ExperimentCatalog.find_or_create(:not_started_experiment, "control", "alt") end it "should not raise an exception" do expect { ab_finished(:not_started_experiment) }.not_to raise_exception end it "should not change the user state when reset is false" do expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys }.from([]) end it "should not change the user state when reset is true" do expect(self).not_to receive(:reset!) ab_finished(:not_started_experiment) end it "should not increment the completed counter" do ab_finished(:not_started_experiment) expect(Split::Alternative.new("control", :not_started_experiment).completed_count).to eq(0) expect(Split::Alternative.new("alt", :not_started_experiment).completed_count).to eq(0) end end end context "finished with config" do it "passes reset option" do Split.configuration.experiments = { my_experiment: { alternatives: ["one", "two"], resettable: false, } } alternative = ab_test(:my_experiment) experiment = Split::ExperimentCatalog.find :my_experiment ab_finished :my_experiment expect(ab_user[experiment.key]).to eq(alternative) expect(ab_user[experiment.finished_key]).to eq(true) end end context "finished with metric name" do before { Split.configuration.experiments = {} } before { expect(Split::Alternative).to receive(:new).at_least(1).times.and_call_original } def should_finish_experiment(experiment_name, should_finish = true) alts = Split.configuration.experiments[experiment_name][:alternatives] experiment = Split::ExperimentCatalog.find_or_create(experiment_name, *alts) alt_name = ab_user[experiment.key] = alts.first alt = double("alternative") expect(alt).to receive(:name).at_most(1).times.and_return(alt_name) expect(Split::Alternative).to receive(:new).at_most(1).times.with(alt_name, experiment_name.to_s).and_return(alt) if should_finish expect(alt).to receive(:increment_completion).at_most(1).times else expect(alt).not_to receive(:increment_completion) end end it "completes the test" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], metric: :my_metric } should_finish_experiment :my_experiment ab_finished :my_metric end it "completes all relevant tests" do Split.configuration.experiments = { exp_1: { alternatives: [ "1-1", "1-2" ], metric: :my_metric }, exp_2: { alternatives: [ "2-1", "2-2" ], metric: :another_metric }, exp_3: { alternatives: [ "3-1", "3-2" ], metric: :my_metric }, } should_finish_experiment :exp_1 should_finish_experiment :exp_2, false should_finish_experiment :exp_3 ab_finished :my_metric end it "passes reset option" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, resettable: false, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end it "passes through options" do Split.configuration.experiments = { my_exp: { alternatives: ["one", "two"], metric: :my_metric, } } alternative_name = ab_test(:my_exp) exp = Split::ExperimentCatalog.find :my_exp ab_finished :my_metric, reset: false expect(ab_user[exp.key]).to eq(alternative_name) expect(ab_user[exp.finished_key]).to be_truthy end end describe "conversions" do it "should return a conversion rate for an alternative" do alternative_name = ab_test("link_color", "blue", "red") previous_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(previous_convertion_rate).to eq(0.0) ab_finished("link_color") new_convertion_rate = Split::Alternative.new(alternative_name, "link_color").conversion_rate expect(new_convertion_rate).to eq(1.0) end end describe "active experiments" do it "should show an active test" do alternative = ab_test("def", "4", "5", "6") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show a finished test" do alternative = ab_test("def", "4", "5", "6") ab_finished("def", { reset: false }) expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "def" expect(active_experiments.first[1]).to eq alternative end it "should show an active test when an experiment is on a later version" do experiment.reset expect(experiment.version).to eq(1) ab_test("link_color", "blue", "red") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "link_color" end it "should show versioned tests properly" do 10.times { experiment.reset } alternative = ab_test(experiment.name, "blue", "red") ab_finished(experiment.name, reset: false) expect(experiment.version).to eq(10) expect(active_experiments.count).to eq 1 expect(active_experiments).to eq({ "link_color" => alternative }) end it "should show multiple tests" do Split.configure do |config| config.allow_multiple_experiments = true end alternative = ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 2 expect(active_experiments["def"]).to eq alternative expect(active_experiments["ghi"]).to eq another_alternative end it "should not show tests with winners" do Split.configure do |config| config.allow_multiple_experiments = true end e = Split::ExperimentCatalog.find_or_create("def", "4", "5", "6") e.winner = "4" ab_test("def", "4", "5", "6") another_alternative = ab_test("ghi", "7", "8", "9") expect(active_experiments.count).to eq 1 expect(active_experiments.first[0]).to eq "ghi" expect(active_experiments.first[1]).to eq another_alternative end end describe "when user is a robot" do before(:each) do @request = OpenStruct.new(user_agent: "Googlebot/2.1 (+http://www.google.com/bot.html)") end describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not create a experiment" do ab_test("link_color", "blue", "red") expect(Split::Experiment.new("link_color")).to be_a_new_record end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when providing custom ignore logic" do context "using a proc to configure custom logic" do before(:each) do Split.configure do |c| c.ignore_filter = proc { |request| true } # ignore everything end end it "ignores the ab_test" do ab_test("link_color", "blue", "red") red_count = Split::Alternative.new("red", "link_color").participant_count blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((red_count + blue_count)).to be(0) end end end shared_examples_for "a disabled test" do describe "ab_test" do it "should return the control" do alternative = ab_test("link_color", "blue", "red") expect(alternative).to eq experiment.control.name end it "should not increment the participation count" do previous_red_count = Split::Alternative.new("red", "link_color").participant_count previous_blue_count = Split::Alternative.new("blue", "link_color").participant_count ab_test("link_color", "blue", "red") new_red_count = Split::Alternative.new("red", "link_color").participant_count new_blue_count = Split::Alternative.new("blue", "link_color").participant_count expect((new_red_count + new_blue_count)).to eq(previous_red_count + previous_blue_count) end end describe "finished" do it "should not increment the completed count" do alternative_name = ab_test("link_color", "blue", "red") previous_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count ab_finished("link_color") new_completion_count = Split::Alternative.new(alternative_name, "link_color").completed_count expect(new_completion_count).to eq(previous_completion_count) end end end describe "when ip address is ignored" do context "individually" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.130") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it_behaves_like "a disabled test" end context "for a range" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.129") Split.configure do |c| c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "using both a range and a specific value" do before(:each) do @request = OpenStruct.new(ip: "81.19.48.128") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" c.ignore_ip_addresses << /81\.19\.48\.[0-9]+/ end end it_behaves_like "a disabled test" end context "when ignored other address" do before do @request = OpenStruct.new(ip: "1.1.1.1") Split.configure do |c| c.ignore_ip_addresses << "81.19.48.130" end end it "works as usual" do alternative_name = ab_test("link_color", "red", "blue") expect { ab_finished("link_color") }.to change(Split::Alternative.new(alternative_name, "link_color"), :completed_count).by(1) end end end describe "when user is previewing" do before(:each) do @request = OpenStruct.new(headers: { "x-purpose" => "preview" }) end it_behaves_like "a disabled test" end describe "versioned experiments" do it "should use version zero if no version is present" do alternative_name = ab_test("link_color", "blue", "red") expect(experiment.version).to eq(0) expect(ab_user["link_color"]).to eq(alternative_name) end it "should save the version of the experiment to the session" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) end it "should load the experiment even if the version is not 0" do experiment.reset expect(experiment.version).to eq(1) alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(alternative_name) return_alternative_name = ab_test("link_color", "blue", "red") expect(return_alternative_name).to eq(alternative_name) end it "should reset the session of a user on an older version of the experiment" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) new_alternative = Split::Alternative.new(new_alternative_name, "link_color") expect(new_alternative.participant_count).to eq(1) end it "should cleanup old versions of experiments from the session" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(1) experiment.reset expect(experiment.version).to eq(1) alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.participant_count).to eq(0) new_alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color:1"]).to eq(new_alternative_name) end it "should only count completion of users on the current version" do alternative_name = ab_test("link_color", "blue", "red") expect(ab_user["link_color"]).to eq(alternative_name) Split::Alternative.new(alternative_name, "link_color") experiment.reset expect(experiment.version).to eq(1) ab_finished("link_color") alternative = Split::Alternative.new(alternative_name, "link_color") expect(alternative.completed_count).to eq(0) end end context "when redis is not available" do before(:each) do expect(Split).to receive(:redis).at_most(5).times.and_raise(Errno::ECONNREFUSED.new) end context "and db_failover config option is turned off" do before(:each) do Split.configure do |config| config.db_failover = false end end describe "ab_test" do it "should raise an exception" do expect { ab_test("link_color", "blue", "red") }.to raise_error(Errno::ECONNREFUSED) end end describe "finished" do it "should raise an exception" do expect { ab_finished("link_color") }.to raise_error(Errno::ECONNREFUSED) end end describe "disable split testing" do before(:each) do Split.configure do |config| config.enabled = false end end it "should not attempt to connect to redis" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should return control variable" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect { ab_finished("link_color") }.not_to raise_error end end end context "and db_failover config option is turned on" do before(:each) do Split.configure do |config| config.db_failover = true end end describe "ab_test" do it "should not raise an exception" do expect { ab_test("link_color", "blue", "red") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_test("link_color", "blue", "red") end it "should always use first alternative" do expect(ab_test("link_color", "blue", "red")).to eq("blue") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("blue") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("blue") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/blue") end context "and db_failover_allow_parameter_override config option is turned on" do before(:each) do Split.configure do |config| config.db_failover_allow_parameter_override = true end end context "and given an override parameter" do it "should use given override instead of the first alternative" do @params = { "ab_test" => { "link_color" => "red" } } expect(ab_test("link_color", "blue", "red")).to eq("red") expect(ab_test("link_color", "blue", "red", "green")).to eq("red") expect(ab_test("link_color", { "blue" => 0.01 }, "red" => 0.2)).to eq("red") expect(ab_test("link_color", { "blue" => 0.8 }, { "red" => 20 })).to eq("red") expect(ab_test("link_color", "blue", "red") do |alternative| "shared/#{alternative}" end).to eq("shared/red") end end end context "and preloaded config given" do before do Split.configuration.experiments[:link_color] = { alternatives: [ "blue", "red" ], } end it "uses first alternative" do expect(ab_test(:link_color)).to eq("blue") end end end describe "finished" do it "should not raise an exception" do expect { ab_finished("link_color") }.not_to raise_error end it "should call db_failover_on_db_error proc with error as parameter" do Split.configure do |config| config.db_failover_on_db_error = proc do |error| expect(error).to be_a(Errno::ECONNREFUSED) end end expect(Split.configuration.db_failover_on_db_error).to receive(:call).and_call_original ab_finished("link_color") end end end end context "with preloaded config" do before { Split.configuration.experiments = {} } it "pulls options from config file" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } ab_test :my_experiment expect(Split::Experiment.new(:my_experiment).alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(Split::Experiment.new(:my_experiment).goals).to eq([ "goal1", "goal2" ]) end it "can be called multiple times" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: ["goal1", "goal2"] } 5.times { ab_test :my_experiment } experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "other_opt" ]) expect(experiment.goals).to eq([ "goal1", "goal2" ]) expect(experiment.participant_count).to eq(1) end it "accepts multiple goals" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ], goals: [ "goal1", "goal2", "goal3" ] } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([ "goal1", "goal2", "goal3" ]) end it "allow specifying goals to be optional" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "other_opt" ] } experiment = Split::Experiment.new(:my_experiment) expect(experiment.goals).to eq([]) end it "accepts multiple alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ "control_opt", "second_opt", "third_opt" ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.map(&:name)).to eq([ "control_opt", "second_opt", "third_opt" ]) end it "accepts probability on alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 67 }, { name: "second_opt", percent: 10 }, { name: "third_opt", percent: 23 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) expect(experiment.alternatives.collect { |a| [a.name, a.weight] }).to eq([["control_opt", 0.67], ["second_opt", 0.1], ["third_opt", 0.23]]) end it "accepts probability on some alternatives" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt", percent: 34 }, "second_opt", { name: "third_opt", percent: 23 }, "fourth_opt", ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.34], ["second_opt", 0.215], ["third_opt", 0.23], ["fourth_opt", 0.215]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "allows name param without probability" do Split.configuration.experiments[:my_experiment] = { alternatives: [ { name: "control_opt" }, "second_opt", { name: "third_opt", percent: 64 }, ], } ab_test :my_experiment experiment = Split::Experiment.new(:my_experiment) names_and_weights = experiment.alternatives.collect { |a| [a.name, a.weight] } expect(names_and_weights).to eq([["control_opt", 0.18], ["second_opt", 0.18], ["third_opt", 0.64]]) expect(names_and_weights.inject(0) { |sum, nw| sum + nw[1] }).to eq(1.0) end it "fails gracefully if config is missing experiment" do Split.configuration.experiments = { other_experiment: { foo: "Bar" } } expect { ab_test :my_experiment }.to raise_error(Split::ExperimentNotFound) end it "fails gracefully if config is missing" do expect { Split.configuration.experiments = nil }.to raise_error(Split::InvalidExperimentsFormatError) end it "fails gracefully if config is missing alternatives" do Split.configuration.experiments[:my_experiment] = { foo: "Bar" } expect { ab_test :my_experiment }.to raise_error(NoMethodError) end end it "should handle multiple experiments correctly" do experiment2 = Split::ExperimentCatalog.find_or_create("link_color2", "blue", "red") ab_test("link_color", "blue", "red") ab_test("link_color2", "blue", "red") ab_finished("link_color2") experiment2.alternatives.each do |alt| expect(alt.unfinished_count).to eq(0) end end context "with goals" do before do @experiment = { "link_color" => ["purchase", "refund"] } @alternatives = ["blue", "red"] @experiment_name, @goals = normalize_metric(@experiment) @goal1 = @goals[0] @goal2 = @goals[1] end it "should normalize experiment" do expect(@experiment_name).to eq("link_color") expect(@goals).to eq(["purchase", "refund"]) end describe "ab_test" do it "should allow experiment goals interface as a single hash" do ab_test(@experiment, *@alternatives) experiment = Split::ExperimentCatalog.find("link_color") expect(experiment.goals).to eq(["purchase", "refund"]) end end describe "ab_finished" do before do @alternative_name = ab_test(@experiment, *@alternatives) end it "should increment the counter for the specified-goal completed alternative" do expect { ab_finished({ "link_color" => ["purchase"] }) } .to change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal2) }.by(0) .and change { Split::Alternative.new(@alternative_name, @experiment_name).completed_count(@goal1) }.by(1) end end end end <MSG> Merge pull request #577 from gnanou/finish_inactive_experiment Handle correctly case when ab_finished is called before ab_test for a user <DFF> @@ -296,98 +296,126 @@ describe Split::Helper do end describe 'ab_finished' do - before(:each) do - @experiment_name = 'link_color' - @alternatives = ['blue', 'red'] - @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) - @alternative_name = ab_test(@experiment_name, *@alternatives) - @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - end + context 'for an experiment that the user participates in' do + before(:each) do + @experiment_name = 'link_color' + @alternatives = ['blue', 'red'] + @experiment = Split::ExperimentCatalog.find_or_create(@experiment_name, *@alternatives) + @alternative_name = ab_test(@experiment_name, *@alternatives) + @previous_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + end - it 'should increment the counter for the completed alternative' do - ab_finished(@experiment_name) - new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - expect(new_completion_count).to eq(@previous_completion_count + 1) - end + it 'should increment the counter for the completed alternative' do + ab_finished(@experiment_name) + new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + expect(new_completion_count).to eq(@previous_completion_count + 1) + end - it "should set experiment's finished key if reset is false" do - ab_finished(@experiment_name, {:reset => false}) - expect(ab_user[@experiment.key]).to eq(@alternative_name) - expect(ab_user[@experiment.finished_key]).to eq(true) - end + it "should set experiment's finished key if reset is false" do + ab_finished(@experiment_name, {:reset => false}) + expect(ab_user[@experiment.key]).to eq(@alternative_name) + expect(ab_user[@experiment.finished_key]).to eq(true) + end - it 'should not increment the counter if reset is false and the experiment has been already finished' do - 2.times { ab_finished(@experiment_name, {:reset => false}) } - new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count - expect(new_completion_count).to eq(@previous_completion_count + 1) - end + it 'should not increment the counter if reset is false and the experiment has been already finished' do + 2.times { ab_finished(@experiment_name, {:reset => false}) } + new_completion_count = Split::Alternative.new(@alternative_name, @experiment_name).completed_count + expect(new_completion_count).to eq(@previous_completion_count + 1) + end - it 'should not increment the counter for an experiment that the user is not participating in' do - ab_test('button_size', 'small', 'big') + it 'should not increment the counter for an ended experiment' do + e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') + e.winner = 'small' + a = ab_test('button_size', 'small', 'big') + expect(a).to eq('small') + expect(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } + end - # So, user should be participating in the link_color experiment and - # receive the control for button_size. As the user is not participating in - # the button size experiment, finishing it should not increase the - # completion count for that alternative. - expect(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } - end + it "should clear out the user's participation from their session" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it 'should not increment the counter for an ended experiment' do - e = Split::ExperimentCatalog.find_or_create('button_size', 'small', 'big') - e.winner = 'small' - a = ab_test('button_size', 'small', 'big') - expect(a).to eq('small') - expect(lambda { - ab_finished('button_size') - }).not_to change { Split::Alternative.new(a, 'button_size').completed_count } - end + it "should not clear out the users session if reset is false" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name, {:reset => false}) + expect(ab_user[@experiment.key]).to eq(@alternative_name) + expect(ab_user[@experiment.finished_key]).to eq(true) + end - it "should clear out the user's participation from their session" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty - end + it "should reset the users session when experiment is not versioned" do + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it "should not clear out the users session if reset is false" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name, {:reset => false}) - expect(ab_user[@experiment.key]).to eq(@alternative_name) - expect(ab_user[@experiment.finished_key]).to eq(true) - end + it "should reset the users session when experiment is versioned" do + @experiment.increment_version + @alternative_name = ab_test(@experiment_name, *@alternatives) - it "should reset the users session when experiment is not versioned" do - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty - end + expect(ab_user[@experiment.key]).to eq(@alternative_name) + ab_finished(@experiment_name) + expect(ab_user.keys).to be_empty + end - it "should reset the users session when experiment is versioned" do - @experiment.increment_version - @alternative_name = ab_test(@experiment_name, *@alternatives) + context "when on_trial_complete is set" do + before { Split.configuration.on_trial_complete = :some_method } + it "should call the method" do + expect(self).to receive(:some_method) + ab_finished(@experiment_name) + end - expect(ab_user[@experiment.key]).to eq(@alternative_name) - ab_finished(@experiment_name) - expect(ab_user.keys).to be_empty + it "should not call the method without alternative" do + ab_user[@experiment.key] = nil + expect(self).not_to receive(:some_method) + ab_finished(@experiment_name) + end + end end - it "should do nothing where the experiment was not started by this user" do - ab_user = nil - expect(lambda { ab_finished('some_experiment_not_started_by_the_user') }).not_to raise_exception + context 'for an experiment that the user is excluded from' do + before do + alternative = ab_test('link_color', 'blue', 'red') + expect(Split::Alternative.new(alternative, 'link_color').participant_count).to eq(1) + alternative = ab_test('button_size', 'small', 'big') + expect(Split::Alternative.new(alternative, 'button_size').participant_count).to eq(0) + end + + it 'should not increment the completed counter' do + # So, user should be participating in the link_color experiment and + # receive the control for button_size. As the user is not participating in + # the button size experiment, finishing it should not increase the + # completion count for that alternative. + expect(lambda { + ab_finished('button_size') + }).not_to change { Split::Alternative.new('small', 'button_size').completed_count } + end end - context "when on_trial_complete is set" do - before { Split.configuration.on_trial_complete = :some_method } - it "should call the method" do - expect(self).to receive(:some_method) - ab_finished(@experiment_name) + context 'for an experiment that the user does not participate in' do + before do + Split::ExperimentCatalog.find_or_create(:not_started_experiment, 'control', 'alt') + end + it 'should not raise an exception' do + expect { ab_finished(:not_started_experiment) }.not_to raise_exception end - it "should not call the method without alternative" do - ab_user[@experiment.key] = nil - expect(self).not_to receive(:some_method) - ab_finished(@experiment_name) + it 'should not change the user state when reset is false' do + expect { ab_finished(:not_started_experiment, reset: false) }.not_to change { ab_user.keys}.from([]) + end + + it 'should not change the user state when reset is true' do + expect(self).not_to receive(:reset!) + ab_finished(:not_started_experiment) + end + + it 'should not increment the completed counter' do + ab_finished(:not_started_experiment) + expect(Split::Alternative.new('control', :not_started_experiment).completed_count).to eq(0) + expect(Split::Alternative.new('alt', :not_started_experiment).completed_count).to eq(0) end end end
    103
    Merge pull request #577 from gnanou/finish_inactive_experiment
    75
    .rb
    rb
    mit
    splitrb/split
    10072082
    <NME> helpers.rb <BEF> # frozen_string_literal: true module Split module DashboardHelpers def h(text) Rack::Utils.escape_html(text) end def url(*path_parts) [ path_prefix, path_parts ].join("/").squeeze("/") end def path_prefix request.env["SCRIPT_NAME"] end def number_to_percentage(number, precision = 2) round(number * 100) def round(number, precision = 2) begin BigDecimal.new(number.to_s) rescue ArgumentError BigDecimal.new(0) end.round(precision).to_f end def confidence_level(z_score) return z_score if z_score.is_a? String z = round(z_score.to_s.to_f, 3).abs if z >= 2.58 "99% confidence" elsif z >= 1.96 "95% confidence" elsif z >= 1.65 "90% confidence" else "Insufficient confidence" end end end end <MSG> Fix Bigdecimal warnings * replace BigDecimal.new() with BigDecimal() <DFF> @@ -19,9 +19,9 @@ module Split def round(number, precision = 2) begin - BigDecimal.new(number.to_s) + BigDecimal(number.to_s) rescue ArgumentError - BigDecimal.new(0) + BigDecimal(0) end.round(precision).to_f end
    2
    Fix Bigdecimal warnings
    2
    .rb
    rb
    mit
    splitrb/split
    10072083
    <NME> helpers.rb <BEF> # frozen_string_literal: true module Split module DashboardHelpers def h(text) Rack::Utils.escape_html(text) end def url(*path_parts) [ path_prefix, path_parts ].join("/").squeeze("/") end def path_prefix request.env["SCRIPT_NAME"] end def number_to_percentage(number, precision = 2) round(number * 100) def round(number, precision = 2) begin BigDecimal.new(number.to_s) rescue ArgumentError BigDecimal.new(0) end.round(precision).to_f end def confidence_level(z_score) return z_score if z_score.is_a? String z = round(z_score.to_s.to_f, 3).abs if z >= 2.58 "99% confidence" elsif z >= 1.96 "95% confidence" elsif z >= 1.65 "90% confidence" else "Insufficient confidence" end end end end <MSG> Fix Bigdecimal warnings * replace BigDecimal.new() with BigDecimal() <DFF> @@ -19,9 +19,9 @@ module Split def round(number, precision = 2) begin - BigDecimal.new(number.to_s) + BigDecimal(number.to_s) rescue ArgumentError - BigDecimal.new(0) + BigDecimal(0) end.round(precision).to_f end
    2
    Fix Bigdecimal warnings
    2
    .rb
    rb
    mit
    splitrb/split
    10072084
    <NME> helpers.rb <BEF> # frozen_string_literal: true module Split module DashboardHelpers def h(text) Rack::Utils.escape_html(text) end def url(*path_parts) [ path_prefix, path_parts ].join("/").squeeze("/") end def path_prefix request.env["SCRIPT_NAME"] end def number_to_percentage(number, precision = 2) round(number * 100) def round(number, precision = 2) begin BigDecimal.new(number.to_s) rescue ArgumentError BigDecimal.new(0) end.round(precision).to_f end def confidence_level(z_score) return z_score if z_score.is_a? String z = round(z_score.to_s.to_f, 3).abs if z >= 2.58 "99% confidence" elsif z >= 1.96 "95% confidence" elsif z >= 1.65 "90% confidence" else "Insufficient confidence" end end end end <MSG> Fix Bigdecimal warnings * replace BigDecimal.new() with BigDecimal() <DFF> @@ -19,9 +19,9 @@ module Split def round(number, precision = 2) begin - BigDecimal.new(number.to_s) + BigDecimal(number.to_s) rescue ArgumentError - BigDecimal.new(0) + BigDecimal(0) end.round(precision).to_f end
    2
    Fix Bigdecimal warnings
    2
    .rb
    rb
    mit
    splitrb/split
    10072085
    <NME> README.md <BEF> # Emmet — the essential toolkit for web-developers Emmet is a web-developer’s toolkit for boosting HTML & CSS code writing. With Emmet, you can type expressions (_abbreviations_) similar to CSS selectors and convert them into code fragment with a single keystroke. For example, this abbreviation: ``` ul#nav>li.item$*4>a{Item $} ``` ...can be expanded into: ```html <ul id="nav"> <li class="item1"><a href="">Item 1</a></li> <li class="item2"><a href="">Item 2</a></li> <li class="item3"><a href="">Item 3</a></li> <li class="item4"><a href="">Item 4</a></li> </ul> ``` ## Features * **Familiar syntax**: as a web-developer, you already know how to use Emmet. Abbreviation syntax is similar to CSS Selectors with shortcuts for id, class, custom attributes, element nesting and so on. * **Dynamic snippets**: unlike default editor snippets, Emmet abbreviations are dynamic and parsed as-you-type. No need to predefine them for each project, just type `MyComponent>custom-element` to convert any word into a tag. * **CSS properties shortcuts**: Emmet provides special syntax for CSS properties with embedded values. For example, `bd1-s#f.5` will be expanded to `border: 1px solid rgba(255, 255, 255, 0.5)`. * **Available for most popular syntaxes**: use single abbreviation to produce code for most popular syntaxes like HAML, Pug, JSX, SCSS, SASS etc. [Read more about Emmet features](https://docs.emmet.io) This repo contains only core module for parsing and expanding Emmet abbreviations. Editor plugins are available as [separate repos](https://github.com/emmetio). This is a *monorepo*: top-level project contains all the code required for converting abbreviation into code fragment while [`./packages`](/packages) folder contains modules for parsing abbreviations into AST and can be used independently (for example, as lexer for syntax highlighting). ### Installation You can install Emmet as a regular npm module: ```bash npm i emmet@rc ``` Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. ## Usage To expand abbreviation, pass it to default function of `emmet` module: ```js import expand from 'emmet'; console.log(expand('p>a')); // <p><a href=""></a></p> ``` By default, Emmet expands *markup* abbreviation, e.g. abbreviation used for producing nested elements with attributes (like HTML, XML, HAML etc.). If you want to expand *stylesheet* abbreviation, you should pass it as a `type` property of second argument: ```js import expand from 'emmet'; console.log(expand('p10', { type: 'stylesheet' })); // padding: 10px; ``` A stylesheet abbreviation has slightly different syntax compared to markup one: it doesn’t support nesting and attributes but allows embedded values in element name. Alternatively, Emmet supports *syntaxes* with predefined snippets and options: ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'css' })); // padding: 10px; console.log(expand('p10', { syntax: 'stylus' })); // padding 10px ``` Predefined syntaxes already have `type` attribute which describes whether given abbreviation is markup or stylesheet, but if you want to use it with your custom syntax name, you should provide `type` config option as well (default is `markup`): ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'my-custom-syntax', type: 'stylesheet', options: { 'stylesheet.between': '__', 'stylesheet.after': '', } })); // padding__10px ``` You can pass `options` property as well to shape-up final output or enable/disable various features. See [`src/config.ts`](src/config.ts) for more info and available options. ## Extracting abbreviations from text A common workflow with Emmet is to type abbreviation somewhere in source code and then expand it with editor action. To support such workflow, abbreviations must be properly _extracted_ from source code: ```js import expand, { extract } from 'emmet'; const source = 'Hello world ul.tabs>li'; const data = extract(source, 22); // { abbreviation: 'ul.tabs>li' } console.log(expand(data.abbreviation)); // <ul class="tabs"><li></li></ul> ``` The `extract` function accepts source code (most likely, current line) and character location in source from which abbreviation search should be started. The abbreviation is searched in backward direction: the location pointer is moved backward until it finds abbreviation bound. Returned result is an object with `abbreviation` property and `start` and `end` properties which describe location of extracted abbreviation in given source. Most current editors automatically insert closing quote or bracket for `(`, `[` and `{` characters so when user types abbreviation that uses attributes or text, it will end with the following state (`|` is caret location): ``` ul>li[title="Foo|"] ``` E.g. caret location is not at the end of abbreviation and must be moved a few characters ahead. The `extract` function is able to handle such cases with `lookAhead` option (enabled by default). This this option enabled, `extract` method automatically detects auto-inserted characters and adjusts location, which will be available as `end` property of the returned result: ```js import { extract } from 'emmet'; const source = 'a div[title] b'; const loc = 11; // right after "title" word // `lookAhead` is enabled by default console.log(extract(source, loc)); // { abbreviation: 'div[title]', start: 2, end: 12 } console.log(extract(source, loc, { lookAhead: false })); // { abbreviation: 'title', start: 6, end: 11 } ``` By default, `extract` tries to detect _markup_ abbreviations (see above). _stylesheet_ abbreviations has slightly different syntax so in order to extract abbreviations for stylesheet syntaxes like CSS, you should pass `type: 'stylesheet'` option: ```js import { extract } from 'emmet'; const source = 'a{b}'; const loc = 3; // right after "b" console.log(extract(source, loc)); // { abbreviation: 'a{b}', start: 0, end: 4 } // Stylesheet abbreviations does not have `{text}` syntax console.log(extract(source, loc, { type: 'stylesheet' })); // { abbreviation: 'b', start: 2, end: 3 } ``` ### Extract abbreviation with custom prefix Lots of developers uses React (or similar) library for writing UI code which mixes JS and XML (JSX) in the same source code. Since _any_ Latin word can be used as Emmet abbreviation, writing JSX code with Emmet becomes pain since it will interfere with native editor snippets and distract user with false positive abbreviation matches for variable names, methods etc.: ```js var div // `div` is a valid abbreviation, Emmet may transform it to `<div></div>` ``` A possible solution for this problem it to use _prefix_ for abbreviation: abbreviation can be successfully extracted only if its preceded with given prefix. ```js import { extract } from 'emmet'; const source1 = '() => div'; const source2 = '() => <div'; extract(source1, source1.length); // Finds `div` abbreviation extract(source2, source2.length); // Finds `div` abbreviation too extract(source1, source1.length, { prefix: '<' }); // No match, `div` abbreviation is not preceded with `<` prefix extract(source2, source2.length, { prefix: '<' }); // Finds `div` since it preceded with `<` prefix ``` With `prefix` option, you can customize your experience with Emmet in any common syntax (HTML, CSS and so on) if user is distracted too much with Emmet completions for any typed word. A `prefix` may contain multiple character but the last one *must* be a character which is not part of Emmet abbreviation. Good candidates are `<`, `&`, `→` (emoji or Unicode symbol) and so on. <MSG> Updated README <DFF> @@ -37,11 +37,9 @@ This is a *monorepo*: top-level project contains all the code required for conve You can install Emmet as a regular npm module: ```bash -npm i emmet@rc +npm i emmet ``` -Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. - ## Usage To expand abbreviation, pass it to default function of `emmet` module:
    1
    Updated README
    3
    .md
    md
    mit
    emmetio/emmet
    10072086
    <NME> README.md <BEF> # Emmet — the essential toolkit for web-developers Emmet is a web-developer’s toolkit for boosting HTML & CSS code writing. With Emmet, you can type expressions (_abbreviations_) similar to CSS selectors and convert them into code fragment with a single keystroke. For example, this abbreviation: ``` ul#nav>li.item$*4>a{Item $} ``` ...can be expanded into: ```html <ul id="nav"> <li class="item1"><a href="">Item 1</a></li> <li class="item2"><a href="">Item 2</a></li> <li class="item3"><a href="">Item 3</a></li> <li class="item4"><a href="">Item 4</a></li> </ul> ``` ## Features * **Familiar syntax**: as a web-developer, you already know how to use Emmet. Abbreviation syntax is similar to CSS Selectors with shortcuts for id, class, custom attributes, element nesting and so on. * **Dynamic snippets**: unlike default editor snippets, Emmet abbreviations are dynamic and parsed as-you-type. No need to predefine them for each project, just type `MyComponent>custom-element` to convert any word into a tag. * **CSS properties shortcuts**: Emmet provides special syntax for CSS properties with embedded values. For example, `bd1-s#f.5` will be expanded to `border: 1px solid rgba(255, 255, 255, 0.5)`. * **Available for most popular syntaxes**: use single abbreviation to produce code for most popular syntaxes like HAML, Pug, JSX, SCSS, SASS etc. [Read more about Emmet features](https://docs.emmet.io) This repo contains only core module for parsing and expanding Emmet abbreviations. Editor plugins are available as [separate repos](https://github.com/emmetio). This is a *monorepo*: top-level project contains all the code required for converting abbreviation into code fragment while [`./packages`](/packages) folder contains modules for parsing abbreviations into AST and can be used independently (for example, as lexer for syntax highlighting). ### Installation You can install Emmet as a regular npm module: ```bash npm i emmet@rc ``` Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. ## Usage To expand abbreviation, pass it to default function of `emmet` module: ```js import expand from 'emmet'; console.log(expand('p>a')); // <p><a href=""></a></p> ``` By default, Emmet expands *markup* abbreviation, e.g. abbreviation used for producing nested elements with attributes (like HTML, XML, HAML etc.). If you want to expand *stylesheet* abbreviation, you should pass it as a `type` property of second argument: ```js import expand from 'emmet'; console.log(expand('p10', { type: 'stylesheet' })); // padding: 10px; ``` A stylesheet abbreviation has slightly different syntax compared to markup one: it doesn’t support nesting and attributes but allows embedded values in element name. Alternatively, Emmet supports *syntaxes* with predefined snippets and options: ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'css' })); // padding: 10px; console.log(expand('p10', { syntax: 'stylus' })); // padding 10px ``` Predefined syntaxes already have `type` attribute which describes whether given abbreviation is markup or stylesheet, but if you want to use it with your custom syntax name, you should provide `type` config option as well (default is `markup`): ```js import expand from 'emmet'; console.log(expand('p10', { syntax: 'my-custom-syntax', type: 'stylesheet', options: { 'stylesheet.between': '__', 'stylesheet.after': '', } })); // padding__10px ``` You can pass `options` property as well to shape-up final output or enable/disable various features. See [`src/config.ts`](src/config.ts) for more info and available options. ## Extracting abbreviations from text A common workflow with Emmet is to type abbreviation somewhere in source code and then expand it with editor action. To support such workflow, abbreviations must be properly _extracted_ from source code: ```js import expand, { extract } from 'emmet'; const source = 'Hello world ul.tabs>li'; const data = extract(source, 22); // { abbreviation: 'ul.tabs>li' } console.log(expand(data.abbreviation)); // <ul class="tabs"><li></li></ul> ``` The `extract` function accepts source code (most likely, current line) and character location in source from which abbreviation search should be started. The abbreviation is searched in backward direction: the location pointer is moved backward until it finds abbreviation bound. Returned result is an object with `abbreviation` property and `start` and `end` properties which describe location of extracted abbreviation in given source. Most current editors automatically insert closing quote or bracket for `(`, `[` and `{` characters so when user types abbreviation that uses attributes or text, it will end with the following state (`|` is caret location): ``` ul>li[title="Foo|"] ``` E.g. caret location is not at the end of abbreviation and must be moved a few characters ahead. The `extract` function is able to handle such cases with `lookAhead` option (enabled by default). This this option enabled, `extract` method automatically detects auto-inserted characters and adjusts location, which will be available as `end` property of the returned result: ```js import { extract } from 'emmet'; const source = 'a div[title] b'; const loc = 11; // right after "title" word // `lookAhead` is enabled by default console.log(extract(source, loc)); // { abbreviation: 'div[title]', start: 2, end: 12 } console.log(extract(source, loc, { lookAhead: false })); // { abbreviation: 'title', start: 6, end: 11 } ``` By default, `extract` tries to detect _markup_ abbreviations (see above). _stylesheet_ abbreviations has slightly different syntax so in order to extract abbreviations for stylesheet syntaxes like CSS, you should pass `type: 'stylesheet'` option: ```js import { extract } from 'emmet'; const source = 'a{b}'; const loc = 3; // right after "b" console.log(extract(source, loc)); // { abbreviation: 'a{b}', start: 0, end: 4 } // Stylesheet abbreviations does not have `{text}` syntax console.log(extract(source, loc, { type: 'stylesheet' })); // { abbreviation: 'b', start: 2, end: 3 } ``` ### Extract abbreviation with custom prefix Lots of developers uses React (or similar) library for writing UI code which mixes JS and XML (JSX) in the same source code. Since _any_ Latin word can be used as Emmet abbreviation, writing JSX code with Emmet becomes pain since it will interfere with native editor snippets and distract user with false positive abbreviation matches for variable names, methods etc.: ```js var div // `div` is a valid abbreviation, Emmet may transform it to `<div></div>` ``` A possible solution for this problem it to use _prefix_ for abbreviation: abbreviation can be successfully extracted only if its preceded with given prefix. ```js import { extract } from 'emmet'; const source1 = '() => div'; const source2 = '() => <div'; extract(source1, source1.length); // Finds `div` abbreviation extract(source2, source2.length); // Finds `div` abbreviation too extract(source1, source1.length, { prefix: '<' }); // No match, `div` abbreviation is not preceded with `<` prefix extract(source2, source2.length, { prefix: '<' }); // Finds `div` since it preceded with `<` prefix ``` With `prefix` option, you can customize your experience with Emmet in any common syntax (HTML, CSS and so on) if user is distracted too much with Emmet completions for any typed word. A `prefix` may contain multiple character but the last one *must* be a character which is not part of Emmet abbreviation. Good candidates are `<`, `&`, `→` (emoji or Unicode symbol) and so on. <MSG> Updated README <DFF> @@ -37,11 +37,9 @@ This is a *monorepo*: top-level project contains all the code required for conve You can install Emmet as a regular npm module: ```bash -npm i emmet@rc +npm i emmet ``` -Note that current version is still in *release candidate* version so it should be installed with `@rc` tag. After release, it will be available as version 2.x. - ## Usage To expand abbreviation, pass it to default function of `emmet` module:
    1
    Updated README
    3
    .md
    md
    mit
    emmetio/emmet
    10072087
    <NME> setup.py <BEF> #!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from distutils.command.install_data import install_data from distutils.command.install import INSTALL_SCHEMES import sys djangopypi = __import__('djangopypi', {}, {}, ['']) packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir != '': os.chdir(root_dir) djangopypi_dir = "djangopypi" def osx_install_data(install_data): def finalize_options(self): self.set_undefined_options("install", ("install_lib", "install_dir")) "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Programming Language :: Python", ], long_description=codecs.open('README', "r", "utf-8").read(), def fullsplit(path, result=None): if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result) for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] for dirpath, dirnames, filenames in os.walk(djangopypi_dir): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith("."): del dirnames[i] for filename in filenames: if filename.endswith(".py"): packages.append('.'.join(fullsplit(dirpath))) else: data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]]) setup( name='chishop', version=djangopypi.__version__, description='Simple PyPI server written in Django.', author='Ask Solem', author_email='[email protected]', packages=packages, url="http://ask.github.com/chishop", zip_safe=False, data_files=data_files, install_requires=[ 'django>=1.0', 'docutils', 'django-registration>0.7', ], classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Operating System :: OS Independent", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Topic :: System :: Software Distribution", "Programming Language :: Python", ], long_description=codecs.open('README', "r", "utf-8").read(), ) <MSG> Added trove category Topic :: System :: Software Distribution <DFF> @@ -28,6 +28,7 @@ setup( "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", + "Topic :: System :: Software Distribution", "Programming Language :: Python", ], long_description=codecs.open('README', "r", "utf-8").read(),
    1
    Added trove category Topic :: System :: Software Distribution
    0
    .py
    py
    bsd-3-clause
    ask/chishop
    10072088
    <NME> .gitignore <BEF> *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode src/**/*.js src/**/*.map <MSG> chore(.gitignore): Exclude .idea files <DFF> @@ -1,3 +1,4 @@ +.idea *.html.js .DS_Store .grunt
    1
    chore(.gitignore): Exclude .idea files
    0
    gitignore
    mit
    Semantic-Org/Semantic-UI-Angular
    10072089
    <NME> .gitignore <BEF> *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode src/**/*.js src/**/*.map <MSG> chore(.gitignore): Exclude .idea files <DFF> @@ -1,3 +1,4 @@ +.idea *.html.js .DS_Store .grunt
    1
    chore(.gitignore): Exclude .idea files
    0
    gitignore
    mit
    Semantic-Org/Semantic-UI-Angular
    10072090
    <NME> .gitignore <BEF> *.html.js .DS_Store .grunt /node_modules /dist *-SNAPSHOT* typings npm-debug.log .vscode src/**/*.js src/**/*.map <MSG> chore(.gitignore): Exclude .idea files <DFF> @@ -1,3 +1,4 @@ +.idea *.html.js .DS_Store .grunt
    1
    chore(.gitignore): Exclude .idea files
    0
    gitignore
    mit
    Semantic-Org/Semantic-UI-Angular
    10072091
    <NME> lorem.ts <BEF> import { ok, strictEqual as equal } from 'assert'; import expand from '../src'; function wordCount(str: string): number { return str.split(' ').length; } function splitLines(str: string): string[] { return str.split(/\n/); } describe('Lorem Ipsum generator', () => { it('single', () => { let output = expand('lorem'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) > 20); output = expand('lorem5'); ok(/^Lorem,?\sipsum/.test(output)); equal(wordCount(output), 5); output = expand('lorem5-10'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) >= 5 && wordCount(output) <= 10); output = expand('loremru4'); ok(/^Далеко-далеко,?\sза,?\sсловесными/.test(output)); equal(wordCount(output), 4); output = expand('p>lorem'); ok(/^<p>Lorem,?\sipsum/.test(output)); // https://github.com/emmetio/expand-abbreviation/issues/24 output = expand('(p)lorem2'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); output = expand('p(lorem10)'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); }); ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!)); output = expand('ul>lorem5*3', { options: { 'output.indent': '' } }); lines = splitLines(output); equal(lines.length, 5); ok(/^<li>Lorem,?\sipsum/.test(lines[1]!)); ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!)); }); }); <MSG> [markup] Format adjacent text-only/snippet nodes <DFF> @@ -40,6 +40,11 @@ describe('Lorem Ipsum generator', () => { ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); + output = expand('lorem6*2'); + lines = splitLines(output); + ok(/^Lorem,?\sipsum/.test(output)); + equal(lines.length, 2); + output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
    5
    [markup] Format adjacent text-only/snippet nodes
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072092
    <NME> lorem.ts <BEF> import { ok, strictEqual as equal } from 'assert'; import expand from '../src'; function wordCount(str: string): number { return str.split(' ').length; } function splitLines(str: string): string[] { return str.split(/\n/); } describe('Lorem Ipsum generator', () => { it('single', () => { let output = expand('lorem'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) > 20); output = expand('lorem5'); ok(/^Lorem,?\sipsum/.test(output)); equal(wordCount(output), 5); output = expand('lorem5-10'); ok(/^Lorem,?\sipsum/.test(output)); ok(wordCount(output) >= 5 && wordCount(output) <= 10); output = expand('loremru4'); ok(/^Далеко-далеко,?\sза,?\sсловесными/.test(output)); equal(wordCount(output), 4); output = expand('p>lorem'); ok(/^<p>Lorem,?\sipsum/.test(output)); // https://github.com/emmetio/expand-abbreviation/issues/24 output = expand('(p)lorem2'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); output = expand('p(lorem10)'); ok(/^<p><\/p>\nLorem,?\sipsum/.test(output)); }); ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!)); ok(!/^<p>Lorem,?\sipsum/.test(lines[1]!)); output = expand('ul>lorem5*3', { options: { 'output.indent': '' } }); lines = splitLines(output); equal(lines.length, 5); ok(/^<li>Lorem,?\sipsum/.test(lines[1]!)); ok(!/^<li>Lorem,?\sipsum/.test(lines[2]!)); }); }); <MSG> [markup] Format adjacent text-only/snippet nodes <DFF> @@ -40,6 +40,11 @@ describe('Lorem Ipsum generator', () => { ok(/^Lorem,?\sipsum/.test(output)); equal(lines.length, 3); + output = expand('lorem6*2'); + lines = splitLines(output); + ok(/^Lorem,?\sipsum/.test(output)); + equal(lines.length, 2); + output = expand('p*3>lorem'); lines = splitLines(output); ok(/^<p>Lorem,?\sipsum/.test(lines[0]!));
    5
    [markup] Format adjacent text-only/snippet nodes
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072093
    <NME> stylesheet.ts <BEF> import { strictEqual as equal, ok } from 'assert'; import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src'; import score from '../src/stylesheet/score'; const defaultConfig = resolveConfig({ type: 'stylesheet', options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`, 'stylesheet.fuzzySearchMinScore': 0 }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))' }, cache: {}, }); function expand(abbr: string, config = defaultConfig) { return expandAbbreviation(abbr, config); } describe('Stylesheet abbreviations', () => { describe('Scoring', () => { const pick = (abbr: string, items: string[]) => items .map(item => ({ item, score: score(abbr, item, true) })) .filter(obj => obj.score) .sort((a, b) => b.score - a.score) .map(obj => obj.item)[0]; it('compare scores', () => { equal(score('aaa', 'aaa'), 1); equal(score('baa', 'aaa'), 0); ok(!score('b', 'aaa')); ok(score('a', 'aaa')); ok(score('a', 'abc')); ok(score('ac', 'abc')); ok(score('a', 'aaa') < score('aa', 'aaa')); ok(score('ab', 'abc') > score('ab', 'acb')); // acronym bonus ok(score('ab', 'a-b') > score('ab', 'acb')); }); it('pick padding or position', () => { const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt']; equal(pick('p', items), 'p'); equal(pick('poa', items), 'pos'); }); }); it('keywords', () => { equal(expand('bd1-s'), 'border: 1px solid;'); equal(expand('dib'), 'display: inline-block;'); equal(expand('bxsz'), 'box-sizing: ${1:border-box};'); equal(expand('bxz'), 'box-sizing: ${1:border-box};'); equal(expand('bxzc'), 'box-sizing: content-box;'); equal(expand('fl'), 'float: ${1:left};'); equal(expand('fll'), 'float: left;'); equal(expand('pos'), 'position: ${1:relative};'); equal(expand('poa'), 'position: absolute;'); equal(expand('por'), 'position: relative;'); equal(expand('pof'), 'position: fixed;'); equal(expand('pos-a'), 'position: absolute;'); equal(expand('m'), 'margin: ${0};'); equal(expand('m0'), 'margin: 0;'); // use `auto` as global keyword equal(expand('m0-a'), 'margin: 0 auto;'); equal(expand('m-a'), 'margin: auto;'); equal(expand('bg'), 'background: ${1:#000};'); equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};'); equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;'); equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;'); equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;'); equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});'); // https://github.com/emmetio/emmet/issues/610 equal(expand('c'), 'color: ${1:#000};'); equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('list:n'), 'list-style-type: none;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); }); it('numeric with format options', () => { equal(expand('fz10'), 'font-size: 10px;', '`px` for integers'); equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('fz12'), 'font-size: 12px;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); // https://github.com/emmetio/emmet/issues/558 equal(expand('us'), 'user-select: none;'); // https://github.com/microsoft/vscode/issues/105697 equal(expand('opa1'), 'opacity: 1;', 'Unitless property'); equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property'); equal(expand('opa.a'), 'opacity: .a;', 'Unitless property'); }); it('numeric with format options', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', 'stylesheet.unitAliases': { e: 'em', p: '%', x: 'ex', r: ' / @rem' } } }); equal(expand('p0', config), 'padding: 0;', 'No unit for 0'); equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers'); equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats'); equal(expand('p10p', config), 'padding: 10%;', 'unit alias'); equal(expand('z10', config), 'z-index: 10;', 'Unitless property'); equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias'); }); it('important', () => { equal(expand('!'), '!important'); equal(expand('p!'), 'padding: ${0} !important;'); equal(expand('p0!'), 'padding: 0 !important;'); }); it('color', () => { equal(expand('c'), 'color: ${1:#000};'); equal(expand('c#'), 'color: #000;'); equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);'); equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;'); equal(expand('bgc'), 'background-color: #${1:fff};'); }); it('snippets', () => { equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}'); // Insert value into snippet fields equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}'); equal(expand('@k-name10'), '@keyframes name {\n\t10\n}'); equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));'); }); it('multiple properties', () => { equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;'); equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};'); }); it('functions', () => { equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});'); equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);'); }); it('case insensitive matches', () => { equal(expand('trf:rx'), 'transform: rotateX(${1:angle});'); }); it('gradient resolver', () => { equal(expand('lg'), 'background-image: linear-gradient(${0});'); equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));'); }); it('unmatched abbreviation', () => { // This example is useless: it’s unexpected to receive `align-self: unset` // for `auto` snippet // equal(expand('auto', resolveConfig({ // type: 'stylesheet', // options: { 'stylesheet.fuzzySearchMinScore': 0 } // })), 'align-self: unset;'); equal(expand('auto'), 'auto: ${0};'); }); it('CSS-in-JS', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.json': true, 'stylesheet.between': ': ' } }); equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\','); equal(expand('bgc', config), 'backgroundColor: \'#fff\','); }); it('resolve context value', () => { const config = resolveConfig({ type: 'stylesheet', context: { name: 'align-content' } }); equal(expand('s', config), 'start'); equal(expand('a', config), 'auto'); }); it('limit snippets by scope', () => { const sectionScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Section }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); const propertyScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Property }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}'); equal(expand('b', sectionScope), ''); equal(expand('m', propertyScope), 'margin: ;'); }); }); <MSG> [stylesheet] Do not select single unmatched value in snippet Fixes #558 <DFF> @@ -88,7 +88,7 @@ describe('Stylesheet abbreviations', () => { equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); - equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); + equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); @@ -96,6 +96,9 @@ describe('Stylesheet abbreviations', () => { equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); + + // https://github.com/emmetio/emmet/issues/558 + equal(expand('us'), 'user-select: none;'); }); it('numeric with format options', () => {
    4
    [stylesheet] Do not select single unmatched value in snippet
    1
    .ts
    ts
    mit
    emmetio/emmet
    10072094
    <NME> stylesheet.ts <BEF> import { strictEqual as equal, ok } from 'assert'; import { stylesheet as expandAbbreviation, resolveConfig, CSSAbbreviationScope } from '../src'; import score from '../src/stylesheet/score'; const defaultConfig = resolveConfig({ type: 'stylesheet', options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}`, 'stylesheet.fuzzySearchMinScore': 0 }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', gt: 'grid-template: repeat(2,auto) / repeat(auto-fit, minmax(250px, 1fr))' }, cache: {}, }); function expand(abbr: string, config = defaultConfig) { return expandAbbreviation(abbr, config); } describe('Stylesheet abbreviations', () => { describe('Scoring', () => { const pick = (abbr: string, items: string[]) => items .map(item => ({ item, score: score(abbr, item, true) })) .filter(obj => obj.score) .sort((a, b) => b.score - a.score) .map(obj => obj.item)[0]; it('compare scores', () => { equal(score('aaa', 'aaa'), 1); equal(score('baa', 'aaa'), 0); ok(!score('b', 'aaa')); ok(score('a', 'aaa')); ok(score('a', 'abc')); ok(score('ac', 'abc')); ok(score('a', 'aaa') < score('aa', 'aaa')); ok(score('ab', 'abc') > score('ab', 'acb')); // acronym bonus ok(score('ab', 'a-b') > score('ab', 'acb')); }); it('pick padding or position', () => { const items = ['p', 'pb', 'pl', 'pos', 'pa', 'oa', 'soa', 'pr', 'pt']; equal(pick('p', items), 'p'); equal(pick('poa', items), 'pos'); }); }); it('keywords', () => { equal(expand('bd1-s'), 'border: 1px solid;'); equal(expand('dib'), 'display: inline-block;'); equal(expand('bxsz'), 'box-sizing: ${1:border-box};'); equal(expand('bxz'), 'box-sizing: ${1:border-box};'); equal(expand('bxzc'), 'box-sizing: content-box;'); equal(expand('fl'), 'float: ${1:left};'); equal(expand('fll'), 'float: left;'); equal(expand('pos'), 'position: ${1:relative};'); equal(expand('poa'), 'position: absolute;'); equal(expand('por'), 'position: relative;'); equal(expand('pof'), 'position: fixed;'); equal(expand('pos-a'), 'position: absolute;'); equal(expand('m'), 'margin: ${0};'); equal(expand('m0'), 'margin: 0;'); // use `auto` as global keyword equal(expand('m0-a'), 'margin: 0 auto;'); equal(expand('m-a'), 'margin: auto;'); equal(expand('bg'), 'background: ${1:#000};'); equal(expand('bd'), 'border: ${1:1px} ${2:solid} ${3:#000};'); equal(expand('bd0-s#fc0'), 'border: 0 solid #fc0;'); equal(expand('bd0-dd#fc0'), 'border: 0 dot-dash #fc0;'); equal(expand('bd0-h#fc0'), 'border: 0 hidden #fc0;'); equal(expand('trf-trs'), 'transform: translate(${1:x}, ${2:y});'); // https://github.com/emmetio/emmet/issues/610 equal(expand('c'), 'color: ${1:#000};'); equal(expand('cr'), 'color: rgb(${1:0}, ${2:0}, ${3:0});'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('list:n'), 'list-style-type: none;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); }); it('numeric with format options', () => { equal(expand('fz10'), 'font-size: 10px;', '`px` for integers'); equal(expand('fz1.'), 'font-size: 1em;', '`em` for explicit float'); equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); equal(expand('fz12'), 'font-size: 12px;'); equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); // https://github.com/emmetio/emmet/issues/558 equal(expand('us'), 'user-select: none;'); // https://github.com/microsoft/vscode/issues/105697 equal(expand('opa1'), 'opacity: 1;', 'Unitless property'); equal(expand('opa.1'), 'opacity: 0.1;', 'Unitless property'); equal(expand('opa.a'), 'opacity: .a;', 'Unitless property'); }); it('numeric with format options', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.intUnit': 'pt', 'stylesheet.floatUnit': 'vh', 'stylesheet.unitAliases': { e: 'em', p: '%', x: 'ex', r: ' / @rem' } } }); equal(expand('p0', config), 'padding: 0;', 'No unit for 0'); equal(expand('p10', config), 'padding: 10pt;', '`pt` unit for integers'); equal(expand('p.4', config), 'padding: 0.4vh;', '`vh` for floats'); equal(expand('p10p', config), 'padding: 10%;', 'unit alias'); equal(expand('z10', config), 'z-index: 10;', 'Unitless property'); equal(expand('p10r', config), 'padding: 10 / @rem;', 'unit alias'); }); it('important', () => { equal(expand('!'), '!important'); equal(expand('p!'), 'padding: ${0} !important;'); equal(expand('p0!'), 'padding: 0 !important;'); }); it('color', () => { equal(expand('c'), 'color: ${1:#000};'); equal(expand('c#'), 'color: #000;'); equal(expand('c#f.5'), 'color: rgba(255, 255, 255, 0.5);'); equal(expand('c#f.5!'), 'color: rgba(255, 255, 255, 0.5) !important;'); equal(expand('bgc'), 'background-color: #${1:fff};'); }); it('snippets', () => { equal(expand('@'), '@media ${1:screen} {\n\t${0}\n}'); // Insert value into snippet fields equal(expand('@k-name'), '@keyframes name {\n\t${2}\n}'); equal(expand('@k-name10'), '@keyframes name {\n\t10\n}'); equal(expand('gt'), 'grid-template: repeat(2, auto) / repeat(auto-fit, minmax(250px, 1fr));'); }); it('multiple properties', () => { equal(expand('p10+m10-20'), 'padding: 10px;\nmargin: 10px 20px;'); equal(expand('p+bd'), 'padding: ${0};\nborder: ${1:1px} ${2:solid} ${3:#000};'); }); it('functions', () => { equal(expand('trf-s(2)'), 'transform: scale(2, ${2:y});'); equal(expand('trf-s(2, 3)'), 'transform: scale(2, 3);'); }); it('case insensitive matches', () => { equal(expand('trf:rx'), 'transform: rotateX(${1:angle});'); }); it('gradient resolver', () => { equal(expand('lg'), 'background-image: linear-gradient(${0});'); equal(expand('lg(to right, #0, #f00.5)'), 'background-image: linear-gradient(to right, #000, rgba(255, 0, 0, 0.5));'); }); it('unmatched abbreviation', () => { // This example is useless: it’s unexpected to receive `align-self: unset` // for `auto` snippet // equal(expand('auto', resolveConfig({ // type: 'stylesheet', // options: { 'stylesheet.fuzzySearchMinScore': 0 } // })), 'align-self: unset;'); equal(expand('auto'), 'auto: ${0};'); }); it('CSS-in-JS', () => { const config = resolveConfig({ type: 'stylesheet', options: { 'stylesheet.json': true, 'stylesheet.between': ': ' } }); equal(expand('p10+mt10-20', config), 'padding: 10,\nmarginTop: \'10px 20px\','); equal(expand('bgc', config), 'backgroundColor: \'#fff\','); }); it('resolve context value', () => { const config = resolveConfig({ type: 'stylesheet', context: { name: 'align-content' } }); equal(expand('s', config), 'start'); equal(expand('a', config), 'auto'); }); it('limit snippets by scope', () => { const sectionScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Section }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); const propertyScope = resolveConfig({ type: 'stylesheet', context: { name: CSSAbbreviationScope.Property }, snippets: { mten: 'margin: 10px;', fsz: 'font-size', myCenterAwesome: 'body {\n\tdisplay: grid;\n}' } }); equal(expand('m', sectionScope), 'body {\n\tdisplay: grid;\n}'); equal(expand('b', sectionScope), ''); equal(expand('m', propertyScope), 'margin: ;'); }); }); <MSG> [stylesheet] Do not select single unmatched value in snippet Fixes #558 <DFF> @@ -88,7 +88,7 @@ describe('Stylesheet abbreviations', () => { equal(expand('p10p'), 'padding: 10%;', 'unit alias'); equal(expand('z10'), 'z-index: 10;', 'Unitless property'); equal(expand('p10r'), 'padding: 10rem;', 'unit alias'); - equal(expand('mten'), 'margin: ${1:10px};', 'Ignore terminating `;` in snippet'); + equal(expand('mten'), 'margin: 10px;', 'Ignore terminating `;` in snippet'); // https://github.com/microsoft/vscode/issues/59951 equal(expand('fz'), 'font-size: ${0};'); @@ -96,6 +96,9 @@ describe('Stylesheet abbreviations', () => { equal(expand('fsz'), 'font-size: ${0};'); equal(expand('fsz12'), 'font-size: 12px;'); equal(expand('fs'), 'font-style: ${1:italic};'); + + // https://github.com/emmetio/emmet/issues/558 + equal(expand('us'), 'user-select: none;'); }); it('numeric with format options', () => {
    4
    [stylesheet] Do not select single unmatched value in snippet
    1
    .ts
    ts
    mit
    emmetio/emmet
    10072095
    <NME> .gitignore <BEF> ._ .DS_Store .swp <MSG> ignore vim swp files <DFF> @@ -1,3 +1,3 @@ ._ .DS_Store -.swp +*.swp
    1
    ignore vim swp files
    1
    gitignore
    mit
    zacstewart/Meow
    10072096
    <NME> .gitignore <BEF> ._ .DS_Store .swp <MSG> ignore vim swp files <DFF> @@ -1,3 +1,3 @@ ._ .DS_Store -.swp +*.swp
    1
    ignore vim swp files
    1
    gitignore
    mit
    zacstewart/Meow
    10072097
    <NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext end def session def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Merge pull request #677 from splitrb/fix-spec-deprecations Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
    1
    Merge pull request #677 from splitrb/fix-spec-deprecations
    0
    .rb
    rb
    mit
    splitrb/split
    10072098
    <NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext end def session def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Merge pull request #677 from splitrb/fix-spec-deprecations Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
    1
    Merge pull request #677 from splitrb/fix-spec-deprecations
    0
    .rb
    rb
    mit
    splitrb/split
    10072099
    <NME> spec_helper.rb <BEF> # frozen_string_literal: true ENV["RACK_ENV"] = "test" require "rubygems" require "bundler/setup" require "simplecov" SimpleCov.start require "split" require "ostruct" require "yaml" Dir["./spec/support/*.rb"].each { |f| require f } module GlobalSharedContext extend RSpec::SharedContext let(:mock_user) { Split::User.new(double(session: {})) } before(:each) do Split.configuration = Split::Configuration.new Split.redis = Redis.new Split.redis.select(10) Split.redis.flushdb Split::Cache.clear @ab_user = mock_user @params = nil end end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext end def session def session @session ||= {} end def params @params ||= {} end def request(ua = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27") @request ||= begin r = OpenStruct.new r.user_agent = ua r.ip = "192.168.1.1" r end end <MSG> Merge pull request #677 from splitrb/fix-spec-deprecations Remove usage of deprecated implicit block expectation from specs <DFF> @@ -31,6 +31,7 @@ end RSpec.configure do |config| config.order = 'random' config.include GlobalSharedContext + config.raise_errors_for_deprecations! end def session
    1
    Merge pull request #677 from splitrb/fix-spec-deprecations
    0
    .rb
    rb
    mit
    splitrb/split
    10072100
    <NME> snippets.ts <BEF> ADDFILE <MSG> Working on CSS snippet resolver <DFF> @@ -0,0 +1,168 @@ +import parse, { CSSValue, ParseOptions } from '@emmetio/css-abbreviation'; + +export type CSSSnippet = CSSSnippetRaw | CSSSnippetProperty; + +export const enum CSSSnippetType { + Raw = 'Raw', + Property = 'Property' +} + +interface CSSSnippetBase { + type: CSSSnippetType; + key: string; +} + +export interface CSSSnippetRaw extends CSSSnippetBase { + type: CSSSnippetType.Raw; + value: string; +} + +export interface CSSSnippetProperty extends CSSSnippetBase { + type: CSSSnippetType.Property; + property: string; + value: CSSValue[][]; + dependencies: CSSSnippetProperty[]; +} + +export interface CSSKeywordRef { + keyword: string; + + /** Reference to CSS snippet value which contains current keyword */ + index: number; +} + +const reProperty = /^([a-z-]+)(?:\s*:\s*([^\n\r]+))?$/; +const opt: ParseOptions = { value: true }; + +/** + * Creates structure for holding resolved CSS snippet + */ +export default function createSnippet(key: string, value: string): CSSSnippet { + // A snippet could be a raw text snippet (e.g. arbitrary text string) or a + // CSS property with possible values separated by `|`. + // In latter case, we have to parse snippet as CSS abbreviation + const m = value.match(reProperty); + if (m) { + return { + type: CSSSnippetType.Property, + key, + property: m[1], + value: m[2].split('|').map(parseValue), + dependencies: [] + }; + } + + return { type: CSSSnippetType.Raw, key, value }; +} + +/** + * Returns list of unique keywords for current CSS snippet and its dependencies + */ +export function getKeywords(snippet: CSSSnippet): CSSKeywordRef[] { + const stack: CSSSnippetProperty[] = []; + const result: CSSKeywordRef[] = []; + const lookup: Set<string> = new Set(); + let i = 0; + + if (snippet.type === CSSSnippetType.Property) { + // Scan valid CSS-properties only + stack.push(snippet); + } + + while (i < stack.length) { + // NB Keep items in stack instead of push/pop to avoid possible + // circular references + const item = stack[i++]; + + // Extract possible keywords from snippet values + for (let index = 0; index < item.value.length; index++) { + for (const keyword of keywordsFromValue(item.value[index])) { + if (!lookup.has(keyword)) { + result.push({ index, keyword }); + lookup.add(keyword); + } + } + } + + // Add dependencies into scan stack + for (const dep of item.dependencies) { + if (!stack.includes(dep)) { + stack.push(dep); + } + } + } + + return result; +} + +function keywordsFromValue(value: CSSValue[]): string[] { + const keywords: string[] = []; + for (const v of value) { + for (const kw of v.value) { + if (kw.type === 'Literal') { + keywords.push(kw.value); + } else if (kw.type === 'FunctionCall') { + keywords.push(kw.name); + } + } + } + + return keywords; +} + +/** + * Nests more specific CSS properties into shorthand ones, e.g. + * `background-position-x` -> `background-position` -> `background` + */ +export function nest(snippets: CSSSnippet[]): CSSSnippet[] { + snippets = snippets.sort(snippetsSort); + const stack: CSSSnippetProperty[] = []; + let prev: CSSSnippet; + + // For sorted list of CSS properties, create dependency graph where each + // shorthand property contains its more specific one, e.g. + // background -> background-position -> background-position-x + for (const cur of snippets.filter(isProperty)) { + // Check if current property belongs to one from parent stack. + // Since `snippets` array is sorted, items are perfectly aligned + // from shorthands to more specific variants + while (stack.length) { + prev = stack[stack.length - 1]; + + if (cur.property.startsWith(prev.property!) + && cur.property.charCodeAt(prev.property!.length) === 45 /* - */) { + prev.dependencies.push(cur); + stack.push(cur); + break; + } + + stack.pop(); + } + + if (!stack.length) { + stack.push(cur); + } + + } + + return snippets; +} + +/** + * A sorting function for array of snippets + */ +function snippetsSort(a: CSSSnippet, b: CSSSnippet): number { + if (a.key === b.key) { + return 0; + } + + return a.key < b.key ? -1 : 1; +} + +function parseValue(value: string): CSSValue[] { + return parse(value.trim(), opt)[0].value; +} + +function isProperty(snippet: CSSSnippet): snippet is CSSSnippetProperty { + return snippet.type === CSSSnippetType.Property; +}
    168
    Working on CSS snippet resolver
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072101
    <NME> snippets.ts <BEF> ADDFILE <MSG> Working on CSS snippet resolver <DFF> @@ -0,0 +1,168 @@ +import parse, { CSSValue, ParseOptions } from '@emmetio/css-abbreviation'; + +export type CSSSnippet = CSSSnippetRaw | CSSSnippetProperty; + +export const enum CSSSnippetType { + Raw = 'Raw', + Property = 'Property' +} + +interface CSSSnippetBase { + type: CSSSnippetType; + key: string; +} + +export interface CSSSnippetRaw extends CSSSnippetBase { + type: CSSSnippetType.Raw; + value: string; +} + +export interface CSSSnippetProperty extends CSSSnippetBase { + type: CSSSnippetType.Property; + property: string; + value: CSSValue[][]; + dependencies: CSSSnippetProperty[]; +} + +export interface CSSKeywordRef { + keyword: string; + + /** Reference to CSS snippet value which contains current keyword */ + index: number; +} + +const reProperty = /^([a-z-]+)(?:\s*:\s*([^\n\r]+))?$/; +const opt: ParseOptions = { value: true }; + +/** + * Creates structure for holding resolved CSS snippet + */ +export default function createSnippet(key: string, value: string): CSSSnippet { + // A snippet could be a raw text snippet (e.g. arbitrary text string) or a + // CSS property with possible values separated by `|`. + // In latter case, we have to parse snippet as CSS abbreviation + const m = value.match(reProperty); + if (m) { + return { + type: CSSSnippetType.Property, + key, + property: m[1], + value: m[2].split('|').map(parseValue), + dependencies: [] + }; + } + + return { type: CSSSnippetType.Raw, key, value }; +} + +/** + * Returns list of unique keywords for current CSS snippet and its dependencies + */ +export function getKeywords(snippet: CSSSnippet): CSSKeywordRef[] { + const stack: CSSSnippetProperty[] = []; + const result: CSSKeywordRef[] = []; + const lookup: Set<string> = new Set(); + let i = 0; + + if (snippet.type === CSSSnippetType.Property) { + // Scan valid CSS-properties only + stack.push(snippet); + } + + while (i < stack.length) { + // NB Keep items in stack instead of push/pop to avoid possible + // circular references + const item = stack[i++]; + + // Extract possible keywords from snippet values + for (let index = 0; index < item.value.length; index++) { + for (const keyword of keywordsFromValue(item.value[index])) { + if (!lookup.has(keyword)) { + result.push({ index, keyword }); + lookup.add(keyword); + } + } + } + + // Add dependencies into scan stack + for (const dep of item.dependencies) { + if (!stack.includes(dep)) { + stack.push(dep); + } + } + } + + return result; +} + +function keywordsFromValue(value: CSSValue[]): string[] { + const keywords: string[] = []; + for (const v of value) { + for (const kw of v.value) { + if (kw.type === 'Literal') { + keywords.push(kw.value); + } else if (kw.type === 'FunctionCall') { + keywords.push(kw.name); + } + } + } + + return keywords; +} + +/** + * Nests more specific CSS properties into shorthand ones, e.g. + * `background-position-x` -> `background-position` -> `background` + */ +export function nest(snippets: CSSSnippet[]): CSSSnippet[] { + snippets = snippets.sort(snippetsSort); + const stack: CSSSnippetProperty[] = []; + let prev: CSSSnippet; + + // For sorted list of CSS properties, create dependency graph where each + // shorthand property contains its more specific one, e.g. + // background -> background-position -> background-position-x + for (const cur of snippets.filter(isProperty)) { + // Check if current property belongs to one from parent stack. + // Since `snippets` array is sorted, items are perfectly aligned + // from shorthands to more specific variants + while (stack.length) { + prev = stack[stack.length - 1]; + + if (cur.property.startsWith(prev.property!) + && cur.property.charCodeAt(prev.property!.length) === 45 /* - */) { + prev.dependencies.push(cur); + stack.push(cur); + break; + } + + stack.pop(); + } + + if (!stack.length) { + stack.push(cur); + } + + } + + return snippets; +} + +/** + * A sorting function for array of snippets + */ +function snippetsSort(a: CSSSnippet, b: CSSSnippet): number { + if (a.key === b.key) { + return 0; + } + + return a.key < b.key ? -1 : 1; +} + +function parseValue(value: string): CSSValue[] { + return parse(value.trim(), opt)[0].value; +} + +function isProperty(snippet: CSSSnippet): snippet is CSSSnippetProperty { + return snippet.type === CSSSnippetType.Property; +}
    168
    Working on CSS snippet resolver
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072102
    <NME> output-stream.ts <BEF> ADDFILE <MSG> HTML outout (WIP) <DFF> @@ -0,0 +1,61 @@ +import { FormatOptions, Options } from './types'; + +const formatOptions: FormatOptions = { + indent: '\t', + baseIndent: '', + newline: '\n', + field(index: number, placeholder: string) { + return placeholder ? `\${${index}:${placeholder}}` : `\${${index}}`; + } +}; + +export interface OutputStream { + format: FormatOptions; + value: string; + offset: number; + line: number; + column: number; +} + +export default function createOutputStream(options: Options): OutputStream { + return { + format: { ...formatOptions, ...options }, + value: '', + offset: 0, + line: 0, + column: 0 + }; +} + +/** + * Pushes given string into output + */ +export function pushString(stream: OutputStream, value: string) { + stream.value += value; + stream.offset += value.length; + stream.column += value.length; +} + +/** + * Pushes new line into given output stream + */ +export function pushNewline(stream: OutputStream) { + const { baseIndent, newline } = stream.format; + pushString(stream, newline + baseIndent); + stream.line++; + stream.column = baseIndent.length; +} + +/** + * Adds indentation of `size` to current output stream + */ +export function pushIndent(stream: OutputStream, size: number = 1) { + pushString(stream, stream.format.indent.repeat(size)); +} + +/** + * Pushes field/tabstop into output stream + */ +export function pushField(stream: OutputStream, index: number, placeholder: string) { + pushString(stream, stream.format.field(index, placeholder, stream.offset, stream.line, stream.column)); +}
    61
    HTML outout (WIP)
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072103
    <NME> output-stream.ts <BEF> ADDFILE <MSG> HTML outout (WIP) <DFF> @@ -0,0 +1,61 @@ +import { FormatOptions, Options } from './types'; + +const formatOptions: FormatOptions = { + indent: '\t', + baseIndent: '', + newline: '\n', + field(index: number, placeholder: string) { + return placeholder ? `\${${index}:${placeholder}}` : `\${${index}}`; + } +}; + +export interface OutputStream { + format: FormatOptions; + value: string; + offset: number; + line: number; + column: number; +} + +export default function createOutputStream(options: Options): OutputStream { + return { + format: { ...formatOptions, ...options }, + value: '', + offset: 0, + line: 0, + column: 0 + }; +} + +/** + * Pushes given string into output + */ +export function pushString(stream: OutputStream, value: string) { + stream.value += value; + stream.offset += value.length; + stream.column += value.length; +} + +/** + * Pushes new line into given output stream + */ +export function pushNewline(stream: OutputStream) { + const { baseIndent, newline } = stream.format; + pushString(stream, newline + baseIndent); + stream.line++; + stream.column = baseIndent.length; +} + +/** + * Adds indentation of `size` to current output stream + */ +export function pushIndent(stream: OutputStream, size: number = 1) { + pushString(stream, stream.format.indent.repeat(size)); +} + +/** + * Pushes field/tabstop into output stream + */ +export function pushField(stream: OutputStream, index: number, placeholder: string) { + pushString(stream, stream.format.field(index, placeholder, stream.offset, stream.line, stream.column)); +}
    61
    HTML outout (WIP)
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072104
    <NME> configuration.rb <BEF> # frozen_string_literal: true module Split class Configuration attr_accessor :ignore_ip_addresses attr_accessor :ignore_filter attr_accessor :db_failover attr_accessor :db_failover_on_db_error attr_accessor :db_failover_allow_parameter_override attr_accessor :allow_multiple_experiments attr_accessor :enabled attr_accessor :persistence attr_accessor :persistence_cookie_length attr_accessor :persistence_cookie_domain attr_accessor :algorithm attr_accessor :store_override attr_accessor :start_manually attr_accessor :reset_manually attr_accessor :on_trial attr_accessor :on_trial_choose attr_accessor :on_trial_complete attr_accessor :on_experiment_reset attr_accessor :on_experiment_delete attr_accessor :on_before_experiment_reset attr_accessor :on_experiment_winner_choose attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler' 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', "Baiduspider" => "Chinese search engine", "bingbot" => "Microsoft bing bot", "Butterfly" => "Topsy Labs", "Gigabot" => "Gigabot spider", "Googlebot" => "Google spider", "MJ12bot" => "Majestic-12 spider", "msnbot" => "Microsoft bot", "rogerbot" => "SeoMoz spider", "PaperLiBot" => "PaperLi is another content curation service", "Slurp" => "Yahoo spider", "Sogou" => "Chinese search engine", "spider" => "generic web spider", "UnwindFetchor" => "Gnip crawler", "WordPress" => "WordPress spider", "YandexAccessibilityBot" => "Yandex accessibility spider", "YandexBot" => "Yandex spider", "YandexMobileBot" => "Yandex mobile spider", "ZIBB" => "ZIBB spider", # HTTP libraries "Apache-HttpClient" => "Java http library", "AppEngine-Google" => "Google App Engine", "curl" => "curl unix CLI http client", "ColdFusion" => "ColdFusion http library", "EventMachine HttpClient" => "Ruby http library", "Go http package" => "Go http library", "Go-http-client" => "Go http library", "Java" => "Generic Java http library", "libwww-perl" => "Perl client-server library loved by script kids", "lwp-trivial" => "Another Perl library loved by script kids", "Python-urllib" => "Python http library", "PycURL" => "Python http library", "Test Certificate Info" => "C http library?", "Typhoeus" => "Ruby http library", "Wget" => "wget unix CLI http client", # URL expanders / previewers "awe.sm" => "Awe.sm URL expander", "bitlybot" => "bit.ly bot", "[email protected]" => "Linkfluence bot", "facebookexternalhit" => "facebook bot", "Facebot" => "Facebook crawler", "Feedfetcher-Google" => "Google Feedfetcher", "https://developers.google.com/+/web/snippet" => "Google+ Snippet Fetcher", "LinkedInBot" => "LinkedIn bot", "LongURL" => "URL expander service", "NING" => "NING - Yet Another Twitter Swarmer", "Pinterestbot" => "Pinterest Bot", "redditbot" => "Reddit Bot", "ShortLinkTranslate" => "Link shortener", "Slackbot" => "Slackbot link expander", "TweetmemeBot" => "TweetMeMe Crawler", "Twitterbot" => "Twitter URL expander", "UnwindFetch" => "Gnip URL expander", "vkShare" => "VKontake Sharer", # Uptime monitoring "check_http" => "Nagios monitor", "GoogleStackdriverMonitoring" => "Google Cloud monitor", "NewRelicPinger" => "NewRelic monitor", "Panopta" => "Monitoring service", "Pingdom" => "Pingdom monitoring", "SiteUptime" => "Site monitoring services", "UptimeRobot" => "Monitoring service", # ??? "DigitalPersona Fingerprint Software" => "HP Fingerprint scanner", "ShowyouBot" => "Showyou iOS app spider", "ZyBorg" => "Zyborg? Hmmm....", "ELB-HealthChecker" => "ELB Health Check" } end def experiments=(experiments) raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys) @experiments = experiments end def disabled? !enabled end def experiment_for(name) if normalized_experiments # TODO symbols normalized_experiments[name.to_sym] end end def metrics return @metrics if defined?(@metrics) @metrics = {} if self.experiments self.experiments.each do |key, value| metrics = value_for(value, :metric) rescue nil Array(metrics).each do |metric_name| if metric_name @metrics[metric_name.to_sym] ||= [] @metrics[metric_name.to_sym] << Split::Experiment.new(key) end end end end @metrics end def normalized_experiments return nil if @experiments.nil? experiment_config = {} @experiments.keys.each do |name| experiment_config[name.to_sym] = {} end @experiments.each do |experiment_name, settings| alternatives = if (alts = value_for(settings, :alternatives)) normalize_alternatives(alts) end experiment_data = { alternatives: alternatives, goals: value_for(settings, :goals), metadata: value_for(settings, :metadata), algorithm: value_for(settings, :algorithm), resettable: value_for(settings, :resettable) } experiment_data.each do |name, value| experiment_config[experiment_name.to_sym][name] = value if value != nil end end experiment_config end def normalize_alternatives(alternatives) given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v| p, n = a if percent = value_for(v, :percent) [p + percent, n + 1] else a end end num_without_probability = alternatives.length - num_with_probability unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0) if num_with_probability.nonzero? alternatives = alternatives.map do |v| if (name = value_for(v, :name)) && (percent = value_for(v, :percent)) { name => percent / 100.0 } elsif name = value_for(v, :name) { name => unassigned_probability } else { v => unassigned_probability } end end [alternatives.shift, alternatives] else alternatives = alternatives.dup [alternatives.shift, alternatives] end end def robot_regex @robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i end def initialize @ignore_ip_addresses = [] @ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? } @db_failover = false @db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here @on_experiment_reset = proc { |experiment| } @on_experiment_delete = proc { |experiment| } @on_before_experiment_reset = proc { |experiment| } @on_before_experiment_delete = proc { |experiment| } @on_experiment_winner_choose = proc { |experiment| } @db_failover_allow_parameter_override = false @allow_multiple_experiments = false @enabled = true @experiments = {} @persistence = Split::Persistence::SessionAdapter @persistence_cookie_length = 31536000 # One year from now @persistence_cookie_domain = nil @algorithm = Split::Algorithms::WeightedSample @include_rails_helper = true @beta_probability_simulations = 10000 @winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day @redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379") @dashboard_pagination_default_per_page = 10 end private def value_for(hash, key) if hash.kind_of?(Hash) hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym] end end def escaped_bots bots.map { |key, _| Regexp.escape(key) } end end end <MSG> Fixed syntax error <DFF> @@ -37,7 +37,7 @@ module Split 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', - 'UnwindFetchor' => 'Gnip crawler' + 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider',
    1
    Fixed syntax error
    1
    .rb
    rb
    mit
    splitrb/split
    10072105
    <NME> configuration.rb <BEF> # frozen_string_literal: true module Split class Configuration attr_accessor :ignore_ip_addresses attr_accessor :ignore_filter attr_accessor :db_failover attr_accessor :db_failover_on_db_error attr_accessor :db_failover_allow_parameter_override attr_accessor :allow_multiple_experiments attr_accessor :enabled attr_accessor :persistence attr_accessor :persistence_cookie_length attr_accessor :persistence_cookie_domain attr_accessor :algorithm attr_accessor :store_override attr_accessor :start_manually attr_accessor :reset_manually attr_accessor :on_trial attr_accessor :on_trial_choose attr_accessor :on_trial_complete attr_accessor :on_experiment_reset attr_accessor :on_experiment_delete attr_accessor :on_before_experiment_reset attr_accessor :on_experiment_winner_choose attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler' 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', "Baiduspider" => "Chinese search engine", "bingbot" => "Microsoft bing bot", "Butterfly" => "Topsy Labs", "Gigabot" => "Gigabot spider", "Googlebot" => "Google spider", "MJ12bot" => "Majestic-12 spider", "msnbot" => "Microsoft bot", "rogerbot" => "SeoMoz spider", "PaperLiBot" => "PaperLi is another content curation service", "Slurp" => "Yahoo spider", "Sogou" => "Chinese search engine", "spider" => "generic web spider", "UnwindFetchor" => "Gnip crawler", "WordPress" => "WordPress spider", "YandexAccessibilityBot" => "Yandex accessibility spider", "YandexBot" => "Yandex spider", "YandexMobileBot" => "Yandex mobile spider", "ZIBB" => "ZIBB spider", # HTTP libraries "Apache-HttpClient" => "Java http library", "AppEngine-Google" => "Google App Engine", "curl" => "curl unix CLI http client", "ColdFusion" => "ColdFusion http library", "EventMachine HttpClient" => "Ruby http library", "Go http package" => "Go http library", "Go-http-client" => "Go http library", "Java" => "Generic Java http library", "libwww-perl" => "Perl client-server library loved by script kids", "lwp-trivial" => "Another Perl library loved by script kids", "Python-urllib" => "Python http library", "PycURL" => "Python http library", "Test Certificate Info" => "C http library?", "Typhoeus" => "Ruby http library", "Wget" => "wget unix CLI http client", # URL expanders / previewers "awe.sm" => "Awe.sm URL expander", "bitlybot" => "bit.ly bot", "[email protected]" => "Linkfluence bot", "facebookexternalhit" => "facebook bot", "Facebot" => "Facebook crawler", "Feedfetcher-Google" => "Google Feedfetcher", "https://developers.google.com/+/web/snippet" => "Google+ Snippet Fetcher", "LinkedInBot" => "LinkedIn bot", "LongURL" => "URL expander service", "NING" => "NING - Yet Another Twitter Swarmer", "Pinterestbot" => "Pinterest Bot", "redditbot" => "Reddit Bot", "ShortLinkTranslate" => "Link shortener", "Slackbot" => "Slackbot link expander", "TweetmemeBot" => "TweetMeMe Crawler", "Twitterbot" => "Twitter URL expander", "UnwindFetch" => "Gnip URL expander", "vkShare" => "VKontake Sharer", # Uptime monitoring "check_http" => "Nagios monitor", "GoogleStackdriverMonitoring" => "Google Cloud monitor", "NewRelicPinger" => "NewRelic monitor", "Panopta" => "Monitoring service", "Pingdom" => "Pingdom monitoring", "SiteUptime" => "Site monitoring services", "UptimeRobot" => "Monitoring service", # ??? "DigitalPersona Fingerprint Software" => "HP Fingerprint scanner", "ShowyouBot" => "Showyou iOS app spider", "ZyBorg" => "Zyborg? Hmmm....", "ELB-HealthChecker" => "ELB Health Check" } end def experiments=(experiments) raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys) @experiments = experiments end def disabled? !enabled end def experiment_for(name) if normalized_experiments # TODO symbols normalized_experiments[name.to_sym] end end def metrics return @metrics if defined?(@metrics) @metrics = {} if self.experiments self.experiments.each do |key, value| metrics = value_for(value, :metric) rescue nil Array(metrics).each do |metric_name| if metric_name @metrics[metric_name.to_sym] ||= [] @metrics[metric_name.to_sym] << Split::Experiment.new(key) end end end end @metrics end def normalized_experiments return nil if @experiments.nil? experiment_config = {} @experiments.keys.each do |name| experiment_config[name.to_sym] = {} end @experiments.each do |experiment_name, settings| alternatives = if (alts = value_for(settings, :alternatives)) normalize_alternatives(alts) end experiment_data = { alternatives: alternatives, goals: value_for(settings, :goals), metadata: value_for(settings, :metadata), algorithm: value_for(settings, :algorithm), resettable: value_for(settings, :resettable) } experiment_data.each do |name, value| experiment_config[experiment_name.to_sym][name] = value if value != nil end end experiment_config end def normalize_alternatives(alternatives) given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v| p, n = a if percent = value_for(v, :percent) [p + percent, n + 1] else a end end num_without_probability = alternatives.length - num_with_probability unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0) if num_with_probability.nonzero? alternatives = alternatives.map do |v| if (name = value_for(v, :name)) && (percent = value_for(v, :percent)) { name => percent / 100.0 } elsif name = value_for(v, :name) { name => unassigned_probability } else { v => unassigned_probability } end end [alternatives.shift, alternatives] else alternatives = alternatives.dup [alternatives.shift, alternatives] end end def robot_regex @robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i end def initialize @ignore_ip_addresses = [] @ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? } @db_failover = false @db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here @on_experiment_reset = proc { |experiment| } @on_experiment_delete = proc { |experiment| } @on_before_experiment_reset = proc { |experiment| } @on_before_experiment_delete = proc { |experiment| } @on_experiment_winner_choose = proc { |experiment| } @db_failover_allow_parameter_override = false @allow_multiple_experiments = false @enabled = true @experiments = {} @persistence = Split::Persistence::SessionAdapter @persistence_cookie_length = 31536000 # One year from now @persistence_cookie_domain = nil @algorithm = Split::Algorithms::WeightedSample @include_rails_helper = true @beta_probability_simulations = 10000 @winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day @redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379") @dashboard_pagination_default_per_page = 10 end private def value_for(hash, key) if hash.kind_of?(Hash) hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym] end end def escaped_bots bots.map { |key, _| Regexp.escape(key) } end end end <MSG> Fixed syntax error <DFF> @@ -37,7 +37,7 @@ module Split 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', - 'UnwindFetchor' => 'Gnip crawler' + 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider',
    1
    Fixed syntax error
    1
    .rb
    rb
    mit
    splitrb/split
    10072106
    <NME> configuration.rb <BEF> # frozen_string_literal: true module Split class Configuration attr_accessor :ignore_ip_addresses attr_accessor :ignore_filter attr_accessor :db_failover attr_accessor :db_failover_on_db_error attr_accessor :db_failover_allow_parameter_override attr_accessor :allow_multiple_experiments attr_accessor :enabled attr_accessor :persistence attr_accessor :persistence_cookie_length attr_accessor :persistence_cookie_domain attr_accessor :algorithm attr_accessor :store_override attr_accessor :start_manually attr_accessor :reset_manually attr_accessor :on_trial attr_accessor :on_trial_choose attr_accessor :on_trial_complete attr_accessor :on_experiment_reset attr_accessor :on_experiment_delete attr_accessor :on_before_experiment_reset attr_accessor :on_experiment_winner_choose attr_accessor :on_before_experiment_delete attr_accessor :include_rails_helper attr_accessor :beta_probability_simulations attr_accessor :winning_alternative_recalculation_interval attr_accessor :redis attr_accessor :dashboard_pagination_default_per_page attr_accessor :cache attr_reader :experiments attr_writer :bots 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', 'UnwindFetchor' => 'Gnip crawler' 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider', "Baiduspider" => "Chinese search engine", "bingbot" => "Microsoft bing bot", "Butterfly" => "Topsy Labs", "Gigabot" => "Gigabot spider", "Googlebot" => "Google spider", "MJ12bot" => "Majestic-12 spider", "msnbot" => "Microsoft bot", "rogerbot" => "SeoMoz spider", "PaperLiBot" => "PaperLi is another content curation service", "Slurp" => "Yahoo spider", "Sogou" => "Chinese search engine", "spider" => "generic web spider", "UnwindFetchor" => "Gnip crawler", "WordPress" => "WordPress spider", "YandexAccessibilityBot" => "Yandex accessibility spider", "YandexBot" => "Yandex spider", "YandexMobileBot" => "Yandex mobile spider", "ZIBB" => "ZIBB spider", # HTTP libraries "Apache-HttpClient" => "Java http library", "AppEngine-Google" => "Google App Engine", "curl" => "curl unix CLI http client", "ColdFusion" => "ColdFusion http library", "EventMachine HttpClient" => "Ruby http library", "Go http package" => "Go http library", "Go-http-client" => "Go http library", "Java" => "Generic Java http library", "libwww-perl" => "Perl client-server library loved by script kids", "lwp-trivial" => "Another Perl library loved by script kids", "Python-urllib" => "Python http library", "PycURL" => "Python http library", "Test Certificate Info" => "C http library?", "Typhoeus" => "Ruby http library", "Wget" => "wget unix CLI http client", # URL expanders / previewers "awe.sm" => "Awe.sm URL expander", "bitlybot" => "bit.ly bot", "[email protected]" => "Linkfluence bot", "facebookexternalhit" => "facebook bot", "Facebot" => "Facebook crawler", "Feedfetcher-Google" => "Google Feedfetcher", "https://developers.google.com/+/web/snippet" => "Google+ Snippet Fetcher", "LinkedInBot" => "LinkedIn bot", "LongURL" => "URL expander service", "NING" => "NING - Yet Another Twitter Swarmer", "Pinterestbot" => "Pinterest Bot", "redditbot" => "Reddit Bot", "ShortLinkTranslate" => "Link shortener", "Slackbot" => "Slackbot link expander", "TweetmemeBot" => "TweetMeMe Crawler", "Twitterbot" => "Twitter URL expander", "UnwindFetch" => "Gnip URL expander", "vkShare" => "VKontake Sharer", # Uptime monitoring "check_http" => "Nagios monitor", "GoogleStackdriverMonitoring" => "Google Cloud monitor", "NewRelicPinger" => "NewRelic monitor", "Panopta" => "Monitoring service", "Pingdom" => "Pingdom monitoring", "SiteUptime" => "Site monitoring services", "UptimeRobot" => "Monitoring service", # ??? "DigitalPersona Fingerprint Software" => "HP Fingerprint scanner", "ShowyouBot" => "Showyou iOS app spider", "ZyBorg" => "Zyborg? Hmmm....", "ELB-HealthChecker" => "ELB Health Check" } end def experiments=(experiments) raise InvalidExperimentsFormatError.new("Experiments must be a Hash") unless experiments.respond_to?(:keys) @experiments = experiments end def disabled? !enabled end def experiment_for(name) if normalized_experiments # TODO symbols normalized_experiments[name.to_sym] end end def metrics return @metrics if defined?(@metrics) @metrics = {} if self.experiments self.experiments.each do |key, value| metrics = value_for(value, :metric) rescue nil Array(metrics).each do |metric_name| if metric_name @metrics[metric_name.to_sym] ||= [] @metrics[metric_name.to_sym] << Split::Experiment.new(key) end end end end @metrics end def normalized_experiments return nil if @experiments.nil? experiment_config = {} @experiments.keys.each do |name| experiment_config[name.to_sym] = {} end @experiments.each do |experiment_name, settings| alternatives = if (alts = value_for(settings, :alternatives)) normalize_alternatives(alts) end experiment_data = { alternatives: alternatives, goals: value_for(settings, :goals), metadata: value_for(settings, :metadata), algorithm: value_for(settings, :algorithm), resettable: value_for(settings, :resettable) } experiment_data.each do |name, value| experiment_config[experiment_name.to_sym][name] = value if value != nil end end experiment_config end def normalize_alternatives(alternatives) given_probability, num_with_probability = alternatives.inject([0, 0]) do |a, v| p, n = a if percent = value_for(v, :percent) [p + percent, n + 1] else a end end num_without_probability = alternatives.length - num_with_probability unassigned_probability = ((100.0 - given_probability) / num_without_probability / 100.0) if num_with_probability.nonzero? alternatives = alternatives.map do |v| if (name = value_for(v, :name)) && (percent = value_for(v, :percent)) { name => percent / 100.0 } elsif name = value_for(v, :name) { name => unassigned_probability } else { v => unassigned_probability } end end [alternatives.shift, alternatives] else alternatives = alternatives.dup [alternatives.shift, alternatives] end end def robot_regex @robot_regex ||= /\b(?:#{escaped_bots.join('|')})\b|\A\W*\z/i end def initialize @ignore_ip_addresses = [] @ignore_filter = proc { |request| is_robot? || is_ignored_ip_address? } @db_failover = false @db_failover_on_db_error = proc { |error| } # e.g. use Rails logger here @on_experiment_reset = proc { |experiment| } @on_experiment_delete = proc { |experiment| } @on_before_experiment_reset = proc { |experiment| } @on_before_experiment_delete = proc { |experiment| } @on_experiment_winner_choose = proc { |experiment| } @db_failover_allow_parameter_override = false @allow_multiple_experiments = false @enabled = true @experiments = {} @persistence = Split::Persistence::SessionAdapter @persistence_cookie_length = 31536000 # One year from now @persistence_cookie_domain = nil @algorithm = Split::Algorithms::WeightedSample @include_rails_helper = true @beta_probability_simulations = 10000 @winning_alternative_recalculation_interval = 60 * 60 * 24 # 1 day @redis = ENV.fetch(ENV.fetch("REDIS_PROVIDER", "REDIS_URL"), "redis://localhost:6379") @dashboard_pagination_default_per_page = 10 end private def value_for(hash, key) if hash.kind_of?(Hash) hash.has_key?(key.to_s) ? hash[key.to_s] : hash[key.to_sym] end end def escaped_bots bots.map { |key, _| Regexp.escape(key) } end end end <MSG> Fixed syntax error <DFF> @@ -37,7 +37,7 @@ module Split 'Slurp' => 'Yahoo spider', 'Sogou' => 'Chinese search engine', 'spider' => 'generic web spider', - 'UnwindFetchor' => 'Gnip crawler' + 'UnwindFetchor' => 'Gnip crawler', 'WordPress' => 'WordPress spider', 'YandexBot' => 'Yandex spider', 'ZIBB' => 'ZIBB spider',
    1
    Fixed syntax error
    1
    .rb
    rb
    mit
    splitrb/split
    10072107
    <NME> indexPage.template.html <BEF> ADDFILE <MSG> chore(dgeni): Created basic index page <DFF> @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head lang="en"> + <meta charset="UTF-8"> + <title>Semantic-UI-Angular</title> + <link rel="stylesheet" href="lib/semantic-ui/semantic.css"/> +</head> +<body> +<div class="ui page grid"> + <div class="menu ui"> + <h1 class="header item">Semantic-UI-Angular</h1> + <a class="item active" href="#"><i class="lab icon"></i>API Documentation</a> + <span class="right menu"> + <div class="item">v. 0.0.0</div> + </span> + </div> + <div class="ui grid"> + <div class="sixteen wide column"> + <div class="ui segment" ng-include="'partials/api.html'"></div> + </div> + <div class="sixteen wide column"> + <div class="ui right aligned segment">Built by <span><a href="https://github.com/angular/dgeni">Dgeni</a></span> - Open Source &copy;2014</div> + </div> + </div> +</div> +</body> +</html> \ No newline at end of file
    27
    chore(dgeni): Created basic index page
    0
    .html
    template
    mit
    Semantic-Org/Semantic-UI-Angular
    10072108
    <NME> indexPage.template.html <BEF> ADDFILE <MSG> chore(dgeni): Created basic index page <DFF> @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head lang="en"> + <meta charset="UTF-8"> + <title>Semantic-UI-Angular</title> + <link rel="stylesheet" href="lib/semantic-ui/semantic.css"/> +</head> +<body> +<div class="ui page grid"> + <div class="menu ui"> + <h1 class="header item">Semantic-UI-Angular</h1> + <a class="item active" href="#"><i class="lab icon"></i>API Documentation</a> + <span class="right menu"> + <div class="item">v. 0.0.0</div> + </span> + </div> + <div class="ui grid"> + <div class="sixteen wide column"> + <div class="ui segment" ng-include="'partials/api.html'"></div> + </div> + <div class="sixteen wide column"> + <div class="ui right aligned segment">Built by <span><a href="https://github.com/angular/dgeni">Dgeni</a></span> - Open Source &copy;2014</div> + </div> + </div> +</div> +</body> +</html> \ No newline at end of file
    27
    chore(dgeni): Created basic index page
    0
    .html
    template
    mit
    Semantic-Org/Semantic-UI-Angular
    10072109
    <NME> indexPage.template.html <BEF> ADDFILE <MSG> chore(dgeni): Created basic index page <DFF> @@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head lang="en"> + <meta charset="UTF-8"> + <title>Semantic-UI-Angular</title> + <link rel="stylesheet" href="lib/semantic-ui/semantic.css"/> +</head> +<body> +<div class="ui page grid"> + <div class="menu ui"> + <h1 class="header item">Semantic-UI-Angular</h1> + <a class="item active" href="#"><i class="lab icon"></i>API Documentation</a> + <span class="right menu"> + <div class="item">v. 0.0.0</div> + </span> + </div> + <div class="ui grid"> + <div class="sixteen wide column"> + <div class="ui segment" ng-include="'partials/api.html'"></div> + </div> + <div class="sixteen wide column"> + <div class="ui right aligned segment">Built by <span><a href="https://github.com/angular/dgeni">Dgeni</a></span> - Open Source &copy;2014</div> + </div> + </div> +</div> +</body> +</html> \ No newline at end of file
    27
    chore(dgeni): Created basic index page
    0
    .html
    template
    mit
    Semantic-Org/Semantic-UI-Angular
    10072110
    <NME> tests.py <BEF> import unittest import StringIO from djangopypi.views import parse_distutils_request, simple from djangopypi.models import Project, Classifier from django.test.client import Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.http import HttpRequest def create_post_data(action): data = { ":action": action, "metadata_version": "1.0", "name": "foo", "version": "0.1.0-pre2", "summary": "The quick brown fox jumps over the lazy dog.", "home_page": "http://example.com", "author": "Foo Bar Baz", "author_email": "[email protected]", "license": "Apache", "keywords": "foo bar baz", "platform": "UNKNOWN", "classifiers": [ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Operating System :: OS Independent", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Topic :: System :: Software Distribution", "Programming Language :: Python", ], "download_url": "", "provides": "", "requires": "", "obsoletes": "", "description": """ ========= FOOBARBAZ ========= Introduction ------------ ``foo`` :class:`bar` *baz* [foaoa] """, } return data def create_request(data): boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = '\n--' + boundary end_boundary = sep_boundary + '--' body = StringIO.StringIO() for key, value in data.items(): # handle multiple entries for the same name if type(value) not in (type([]), type( () )): value = [value] for value in value: value = unicode(value).encode("utf-8") body.write(sep_boundary) body.write('\nContent-Disposition: form-data; name="%s"'%key) body.write("\n\n") body.write(value) if value and value[-1] == '\r': body.write('\n') # write an extra newline (lurve Macs) body.write(end_boundary) body.write("\n") return body.getvalue() class MockRequest(object): def __init__(self, raw_post_data): self.raw_post_data = raw_post_data self.META = {} data = create_post_data("submit") raw_post_data = create_request(data) post, files = parse_distutils_request(MockRequest(raw_post_data)) print("post: %s files: %s" % (post, files)) self.assertTrue(post) for key in post.keys(): if isinstance(data[key], list): self.assertEquals(data[key], post.getlist(key)) else: self.assertEquals(post[key], data[key]) self.assertEquals(data[key], post.getlist(key)) elif data[key] == "UNKNOWN": self.assertTrue(post[key] is None) else: self.assertEquals(post[key], data[key]) client = Client() class TestSearch(unittest.TestCase): def setUp(self): dummy_user = User.objects.create(username='krill', password='12345', email='[email protected]') Project.objects.create(name='foo', license='Gnu', summary="The quick brown fox jumps over the lazy dog.", owner=dummy_user) def test_search_for_package(self): response = client.post(reverse('djangopypi-search'), {'search_term': 'foo'}) self.assertTrue("The quick brown fox jumps over the lazy dog." in response.content) class TestSimpleView(unittest.TestCase): def create_distutils_httprequest(self, user_data={}): self.post_data = create_post_data(action='user') self.post_data.update(user_data) self.raw_post_data = create_request(self.post_data) request = HttpRequest() request.POST = self.post_data request.method = "POST" request.raw_post_data = self.raw_post_data return request def test_user_registration(self): request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'[email protected]', 'password':'spiderman'}) response = simple(request) self.assertEquals(200, response.status_code) def test_user_registration_with_wrong_data(self): request = self.create_distutils_httprequest({'name': 'peter_parker', 'email':'[email protected]', 'password':'',}) response = simple(request) self.assertEquals(400, response.status_code) <MSG> Fixes broken unittest. "test-suite" now passes again. <DFF> @@ -80,11 +80,12 @@ class TestParseWeirdPostData(unittest.TestCase): data = create_post_data("submit") raw_post_data = create_request(data) post, files = parse_distutils_request(MockRequest(raw_post_data)) - print("post: %s files: %s" % (post, files)) self.assertTrue(post) for key in post.keys(): if isinstance(data[key], list): self.assertEquals(data[key], post.getlist(key)) + elif data[key] == "UNKNOWN": + self.assertTrue(post[key] is None) else: self.assertEquals(post[key], data[key])
    2
    Fixes broken unittest. "test-suite" now passes again.
    1
    .py
    py
    bsd-3-clause
    ask/chishop
    10072111
    <NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>'); equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); equal(parse('html.one.two'), '<html class="one", class="two"></html>'); equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); it('limit unroll', () => { it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: '[email protected]' }), '<a class="here", href="mailto:[email protected]">[email protected]</a>'); equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test here [email protected]' }), '<a class="here", href="">test here [email protected]</a>'); equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> FIxed invalid parsing of repeater number with modifiers <DFF> @@ -47,6 +47,6 @@ describe('Convert token abbreviations', () => { it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); - equal(parse('a$*2>b$^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); + equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); });
    1
    FIxed invalid parsing of repeater number with modifiers
    1
    .ts
    ts
    mit
    emmetio/emmet
    10072112
    <NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>'); equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); equal(parse('html.one.two'), '<html class="one", class="two"></html>'); equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); it('limit unroll', () => { it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: '[email protected]' }), '<a class="here", href="mailto:[email protected]">[email protected]</a>'); equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); equal(parse('a[class=here]', { href: true, text: 'test here [email protected]' }), '<a class="here", href="">test here [email protected]</a>'); equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> FIxed invalid parsing of repeater number with modifiers <DFF> @@ -47,6 +47,6 @@ describe('Convert token abbreviations', () => { it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); - equal(parse('a$*2>b$^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); + equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); });
    1
    FIxed invalid parsing of repeater number with modifiers
    1
    .ts
    ts
    mit
    emmetio/emmet
    10072113
    <NME> expand.ts <BEF> import { strictEqual as equal } from 'assert'; import expand, { resolveConfig } from '../src'; describe('Expand Abbreviation', () => { describe('Markup', () => { it('basic', () => { equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">'); equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); // insert text into abbreviation equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>'); // insert TextMate-style fields/tabstops in output equal(expand('ul>.item$*2', { options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}` } }), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>'); }); it('attributes', () => { const snippets = { test: 'test[!foo bar. baz={}]' }; const opt = { snippets }; const reverse = { options: { 'output.reverseAttributes': true }, snippets }; equal(expand('a.test'), '<a href="" class="test"></a>'); equal(expand('a.test', reverse), '<a class="test" href=""></a>'); equal(expand('test', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>'); equal(expand('map'), '<map name=""></map>'); equal(expand('map[]'), '<map name=""></map>'); equal(expand('map[name="valid"]'), '<map name="valid"></map>'); equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>'); // Apply attributes in reverse order equal(expand('test', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>'); }); it('numbering', () => { equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>'); }); it('syntax', () => { equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 '); equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>'); }); it('custom profile', () => { equal(expand('img'), '<img src="" alt="">'); equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />'); }); it('custom variables', () => { const variables = { charset: 'ru-RU' }; equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>'); equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>'); }); it('custom snippets', () => { const snippets = { link: 'link[foo=bar href]/', foo: '.foo[bar=baz]', repeat: 'div>ul>li{Hello World}*3' }; equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>'); // `link:css` depends on `link` snippet so changing it will result in // altered `link:css` result equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">'); // https://github.com/emmetio/emmet/issues/468 equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>'); }); it('formatter options', () => { equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }), '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); equal(expand('div>p'), '<div>\n\t<p></p>\n</div>'); equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>'); }); it('JSX', () => { const config = { syntax: 'jsx' }; equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>'); equal(expand('label[for=a]', config), '<label htmlFor="a"></label>'); equal(expand('Foo.Bar', config), '<Foo.Bar></Foo.Bar>'); equal(expand('div.{theme.style}', config), '<div className={theme.style}></div>'); }); it('override attributes', () => { const config = { syntax: 'jsx' }; equal(expand('.bar', config), '<div className="bar"></div>'); equal(expand('..bar', config), '<div styleName={styles.bar}></div>'); equal(expand('..foo-bar', config), '<div styleName={styles[\'foo-bar\']}></div>'); equal(expand('.foo', { syntax: 'vue' }), '<div class="foo"></div>'); equal(expand('..foo', { syntax: 'vue' }), '<div :class="foo"></div>'); }); describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>'); }); it('wrap with abbreviation href', () => { equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>'); equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>'); equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>'); equal(expand('map[name="https://example.com"]', { text: ['some text'] }), '<map name="https://example.com">some text</map>'); equal(expand('map[href="https://example.com"]', { text: ['some text'] }), '<map name="" href="https://example.com">some text</map>'); equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }), '<map name="https://example.com"><b>some text</b></map>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }), '<a href="https://example.com"><b><u>some text false</u></b></a>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }), '<a href="https://example.com"><b><u>some text true</u></b></a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>'); }); // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // }); }); describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); <MSG> Fix #619 (#624) <DFF> @@ -116,7 +116,7 @@ describe('Expand Abbreviation', () => { describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { - equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); + equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); });
    1
    Fix #619 (#624)
    1
    .ts
    ts
    mit
    emmetio/emmet
    10072114
    <NME> expand.ts <BEF> import { strictEqual as equal } from 'assert'; import expand, { resolveConfig } from '../src'; describe('Expand Abbreviation', () => { describe('Markup', () => { it('basic', () => { equal(expand('input[value="text$"]*2'), '<input type="text" value="text1"><input type="text" value="text2">'); equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); // insert text into abbreviation equal(expand('ul>.item$*', { text: ['foo', 'bar'] }), '<ul>\n\t<li class="item1">foo</li>\n\t<li class="item2">bar</li>\n</ul>'); // insert TextMate-style fields/tabstops in output equal(expand('ul>.item$*2', { options: { 'output.field': (index, placeholder) => `\${${index}${placeholder ? ':' + placeholder : ''}}` } }), '<ul>\n\t<li class="item1">${1}</li>\n\t<li class="item2">${2}</li>\n</ul>'); }); it('attributes', () => { const snippets = { test: 'test[!foo bar. baz={}]' }; const opt = { snippets }; const reverse = { options: { 'output.reverseAttributes': true }, snippets }; equal(expand('a.test'), '<a href="" class="test"></a>'); equal(expand('a.test', reverse), '<a class="test" href=""></a>'); equal(expand('test', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', opt), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', opt), '<test foo="1" bar="bar" baz={a}></test>'); equal(expand('map'), '<map name=""></map>'); equal(expand('map[]'), '<map name=""></map>'); equal(expand('map[name="valid"]'), '<map name="valid"></map>'); equal(expand('map[href="invalid"]'), '<map name="" href="invalid"></map>'); // Apply attributes in reverse order equal(expand('test', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[foo]', reverse), '<test bar="bar" baz={}></test>'); equal(expand('test[baz=a foo=1]', reverse), '<test baz={a} foo="1" bar="bar"></test>'); }); it('numbering', () => { equal(expand('ul>li.item$@-*5'), '<ul>\n\t<li class="item5"></li>\n\t<li class="item4"></li>\n\t<li class="item3"></li>\n\t<li class="item2"></li>\n\t<li class="item1"></li>\n</ul>'); }); it('syntax', () => { equal(expand('ul>.item$*2', { syntax: 'html' }), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { syntax: 'slim' }), 'ul\n\tli.item1 \n\tli.item2 '); equal(expand('xsl:variable[name=a select=b]>div', { syntax: 'xsl' }), '<xsl:variable name="a">\n\t<div></div>\n</xsl:variable>'); }); it('custom profile', () => { equal(expand('img'), '<img src="" alt="">'); equal(expand('img', { options: { 'output.selfClosingStyle': 'xhtml' } }), '<img src="" alt="" />'); }); it('custom variables', () => { const variables = { charset: 'ru-RU' }; equal(expand('[charset=${charset}]{${charset}}'), '<div charset="UTF-8">UTF-8</div>'); equal(expand('[charset=${charset}]{${charset}}', { variables }), '<div charset="ru-RU">ru-RU</div>'); }); it('custom snippets', () => { const snippets = { link: 'link[foo=bar href]/', foo: '.foo[bar=baz]', repeat: 'div>ul>li{Hello World}*3' }; equal(expand('foo', { snippets }), '<div class="foo" bar="baz"></div>'); // `link:css` depends on `link` snippet so changing it will result in // altered `link:css` result equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); equal(expand('link:css', { snippets }), '<link foo="bar" href="style.css">'); // https://github.com/emmetio/emmet/issues/468 equal(expand('repeat', { snippets }), '<div>\n\t<ul>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t\t<li>Hello World</li>\n\t</ul>\n</div>'); }); it('formatter options', () => { equal(expand('ul>.item$*2'), '<ul>\n\t<li class="item1"></li>\n\t<li class="item2"></li>\n</ul>'); equal(expand('ul>.item$*2', { options: { 'comment.enabled': true } }), '<ul>\n\t<li class="item1"></li>\n\t<!-- /.item1 -->\n\t<li class="item2"></li>\n\t<!-- /.item2 -->\n</ul>'); equal(expand('div>p'), '<div>\n\t<p></p>\n</div>'); equal(expand('div>p', { options: { 'output.formatLeafNode': true } }), '<div>\n\t<p>\n\t\t\n\t</p>\n</div>'); }); it('JSX', () => { const config = { syntax: 'jsx' }; equal(expand('div#foo.bar', config), '<div id="foo" className="bar"></div>'); equal(expand('label[for=a]', config), '<label htmlFor="a"></label>'); equal(expand('Foo.Bar', config), '<Foo.Bar></Foo.Bar>'); equal(expand('div.{theme.style}', config), '<div className={theme.style}></div>'); }); it('override attributes', () => { const config = { syntax: 'jsx' }; equal(expand('.bar', config), '<div className="bar"></div>'); equal(expand('..bar', config), '<div styleName={styles.bar}></div>'); equal(expand('..foo-bar', config), '<div styleName={styles[\'foo-bar\']}></div>'); equal(expand('.foo', { syntax: 'vue' }), '<div class="foo"></div>'); equal(expand('..foo', { syntax: 'vue' }), '<div :class="foo"></div>'); }); describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); equal(expand('p', { text: 'foo<div>foo</div>' }), '<p>foo<div>foo</div></p>'); }); it('wrap with abbreviation href', () => { equal(expand('a', { text: ['www.google.it'] }), '<a href="http://www.google.it">www.google.it</a>'); equal(expand('a', { text: ['then www.google.it'] }), '<a href="">then www.google.it</a>'); equal(expand('a', { text: ['www.google.it'], options: { 'markup.href': false } }), '<a href="">www.google.it</a>'); equal(expand('map[name="https://example.com"]', { text: ['some text'] }), '<map name="https://example.com">some text</map>'); equal(expand('map[href="https://example.com"]', { text: ['some text'] }), '<map name="" href="https://example.com">some text</map>'); equal(expand('map[name="https://example.com"]>b', { text: ['some text'] }), '<map name="https://example.com"><b>some text</b></map>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text false</u>'], options: { 'markup.href': false } }), '<a href="https://example.com"><b><u>some text false</u></b></a>'); equal(expand('a[href="https://example.com"]>b', { text: ['<u>some text true</u>'], options: { 'markup.href': true } }), '<a href="https://example.com"><b><u>some text true</u></b></a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text false</p>'], options: { 'markup.href': false } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text false</p>\n\t</div>\n</a>'); equal(expand('a[href="https://example.com"]>div', { text: ['<p>some text true</p>'], options: { 'markup.href': true } }), '<a href="https://example.com">\n\t<div>\n\t\t<p>some text true</p>\n\t</div>\n</a>'); }); // it.only('debug', () => { // equal(expand('link:css'), '<link rel="stylesheet" href="style.css">'); // }); }); describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); }); <MSG> Fix #619 (#624) <DFF> @@ -116,7 +116,7 @@ describe('Expand Abbreviation', () => { describe('Pug templates', () => { const config = resolveConfig({ syntax: 'pug' }); it('basic', () => { - equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); + equal(expand('!', config), 'doctype html\nhtml(lang="en")\n\thead\n\t\tmeta(charset="UTF-8")\n\t\tmeta(http-equiv="X-UA-Compatible", content="IE=edge")\n\t\tmeta(name="viewport", content="width=device-width, initial-scale=1.0")\n\t\ttitle Document\n\tbody '); }); }); });
    1
    Fix #619 (#624)
    1
    .ts
    ts
    mit
    emmetio/emmet
    10072115
    <NME> parser.ts <BEF> import { strictEqual as equal, throws } from 'assert'; import parser from '../src/parser'; import tokenizer from '../src/tokenizer'; import stringify from './assets/stringify'; import { ParserOptions } from '../src'; const parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options); const str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options)); describe('Parser', () => { it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); equal(str('h$'), '<h$></h$>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); // https://github.com/emmetio/emmet/issues/562 equal(str('li[repeat.for="todo of todoList"]'), '<li repeat.for="todo of todoList"></li>', 'Dots in attribute names'); equal(str('a>b'), '<a><b></b></a>'); equal(str('a+b'), '<a></a><b></b>'); equal(str('a+b>c+d'), '<a></a><b><c></c><d></d></b>'); equal(str('a>b>c+e'), '<a><b><c></c><e></e></b></a>'); equal(str('a>b>c^d'), '<a><b><c></c></b><d></d></a>'); equal(str('a>b>c^^^^d'), '<a><b><c></c></b></a><d></d>'); equal(str('a:b>c'), '<a:b><c></c></a:b>'); equal(str('ul.nav[title="foo"]'), '<ul class=nav title="foo"></ul>'); }); it('groups', () => { equal(str('a>(b>c)+d'), '<a>(<b><c></c></b>)<d></d></a>'); equal(str('(a>b)+(c>d)'), '(<a><b></b></a>)(<c><d></d></c>)'); equal(str('a>((b>c)(d>e))f'), '<a>((<b><c></c></b>)(<d><e></e></d>))<f></f></a>'); equal(str('a>((((b>c))))+d'), '<a>((((<b><c></c></b>))))<d></d></a>'); equal(str('a>(((b>c))*4)+d'), '<a>(((<b><c></c></b>))*4)<d></d></a>'); equal(str('(div>dl>(dt+dd)*2)'), '(<div><dl>(<dt></dt><dd></dd>)*2</dl></div>)'); equal(str('a>()'), '<a>()</a>'); }); it('attributes', () => { equal(str('[].foo'), '<? class=foo></?>'); equal(str('[a]'), '<? a></?>'); equal(str('[a b c [d]]'), '<? a b c [d]></?>'); equal(str('[a=b]'), '<? a=b></?>'); equal(str('[a=b c= d=e]'), '<? a=b c d=e></?>'); equal(str('[a=b.c d=тест]'), '<? a=b.c d=тест></?>'); equal(str('[[a]=b (c)=d]'), '<? [a]=b (c)=d></?>'); // Quoted attribute values equal(str('[a="b"]'), '<? a="b"></?>'); equal(str('[a="b" c=\'d\' e=""]'), '<? a="b" c=\'d\' e=""></?>'); equal(str('[[a]="b" (c)=\'d\']'), '<? [a]="b" (c)=\'d\'></?>'); // Mixed quoted equal(str('[a="foo\'bar" b=\'foo"bar\' c="foo\\\"bar"]'), '<? a="foo\'bar" b=\'foo"bar\' c="foo"bar"></?>'); // Boolean & implied attributes equal(str('[a. b.]'), '<? a. b.></?>'); equal(str('[!a !b.]'), '<? !a !b.></?>'); // Default values equal(str('["a.b"]'), '<? ?="a.b"></?>'); equal(str('[\'a.b\' "c=d" foo=bar "./test.html"]'), '<? ?=\'a.b\' ?="c=d" foo=bar ?="./test.html"></?>'); // Expressions as values equal(str('[foo={1 + 2} bar={fn(1, "foo")}]'), '<? foo={1 + 2} bar={fn(1, "foo")}></?>'); // Tabstops as unquoted values equal(str('[name=${1} value=${2:test}]'), '<? name=${1} value=${2:test}></?>'); }); it('malformed attributes', () => { equal(str('[a'), '<? a></?>'); equal(str('[a={foo]'), '<? a={foo]></?>'); throws(() => str('[a="foo]'), /Unclosed quote/); throws(() => str('[a=b=c]'), /Unexpected "Operator" token/); }); it('elements', () => { equal(str('div'), '<div></div>'); equal(str('div.foo'), '<div class=foo></div>'); equal(str('div#foo'), '<div id=foo></div>'); equal(str('div#foo.bar'), '<div id=foo class=bar></div>'); equal(str('div.foo#bar'), '<div class=foo id=bar></div>'); equal(str('div.foo.bar.baz'), '<div class=foo class=bar class=baz></div>'); equal(str('.foo'), '<? class=foo></?>'); equal(str('#foo'), '<? id=foo></?>'); equal(str('.foo_bar'), '<? class=foo_bar></?>'); equal(str('#foo.bar'), '<? id=foo class=bar></?>'); // Attribute shorthands equal(str('.'), '<? class></?>'); equal(str('#'), '<? id></?>'); equal(str('#.'), '<? id class></?>'); equal(str('.#.'), '<? class id class></?>'); equal(str('.a..'), '<? class=a class></?>'); // Elements with attributes equal(str('div[foo=bar]'), '<div foo=bar></div>'); equal(str('div.a[b=c]'), '<div class=a b=c></div>'); equal(str('div[b=c].a'), '<div b=c class=a></div>'); equal(str('div[a=b][c="d"]'), '<div a=b c="d"></div>'); equal(str('[b=c]'), '<? b=c></?>'); equal(str('.a[b=c]'), '<? class=a b=c></?>'); equal(str('[b=c].a#d'), '<? b=c class=a id=d></?>'); equal(str('[b=c]a'), '<? b=c></?><a></a>', 'Do not consume node name after attribute set'); // Element with text equal(str('div{foo}'), '<div>foo</div>'); equal(str('{foo}'), '<?>foo</?>'); // Mixed equal(str('div.foo{bar}'), '<div class=foo>bar</div>'); equal(str('.foo{bar}#baz'), '<? class=foo id=baz>bar</?>'); equal(str('.foo[b=c]{bar}'), '<? class=foo b=c>bar</?>'); // Repeated element equal(str('div.foo*3'), '<div*3 class=foo></div>'); equal(str('.foo*'), '<?* class=foo></?>'); equal(str('.a[b=c]*10'), '<?*10 class=a b=c></?>'); equal(str('.a*10[b=c]'), '<?*10 class=a b=c></?>'); equal(str('.a*10{text}'), '<?*10 class=a>text</?>'); // Self-closing element equal(str('div/'), '<div />'); equal(str('.foo/'), '<? class=foo />'); equal(str('.foo[bar]/'), '<? class=foo bar />'); equal(str('.foo/*3'), '<?*3 class=foo />'); equal(str('.foo*3/'), '<?*3 class=foo />'); throws(() => parse('/'), /Unexpected character/); }); it('JSX', () => { const opt = { jsx: true }; equal(str('foo.bar', opt), '<foo class=bar></foo>'); equal(str('Foo.bar', opt), '<Foo class=bar></Foo>'); equal(str('Foo.Bar', opt), '<Foo.Bar></Foo.Bar>'); equal(str('Foo.', opt), '<Foo class></Foo>'); equal(str('Foo.Bar.baz', opt), '<Foo.Bar class=baz></Foo.Bar>'); equal(str('Foo.Bar.Baz', opt), '<Foo.Bar.Baz></Foo.Bar.Baz>'); equal(str('.{theme.class}', opt), '<? class=theme.class></?>'); equal(str('#{id}', opt), '<? id=id></?>'); equal(str('Foo.{theme.class}', opt), '<Foo class=theme.class></Foo>'); }); it('errors', () => { throws(() => parse('str?'), /Unexpected character at 4/); throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); }); }); <MSG> Do not throw errors on missing closing brace <DFF> @@ -153,4 +153,11 @@ describe('Parser', () => { throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); + + it('missing braces', () => { + // Do not throw errors on missing closing braces + equal(str('div[title="test"'), '<div title="test"></div>'); + equal(str('div(foo'), '<div></div>(<foo></foo>)'); + equal(str('div{foo'), '<div>foo</div>'); + }); });
    7
    Do not throw errors on missing closing brace
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072116
    <NME> parser.ts <BEF> import { strictEqual as equal, throws } from 'assert'; import parser from '../src/parser'; import tokenizer from '../src/tokenizer'; import stringify from './assets/stringify'; import { ParserOptions } from '../src'; const parse = (abbr: string, options?: ParserOptions) => parser(tokenizer(abbr), options); const str = (abbr: string, options?: ParserOptions) => stringify(parse(abbr, options)); describe('Parser', () => { it('basic abbreviations', () => { equal(str('p'), '<p></p>'); equal(str('p{text}'), '<p>text</p>'); equal(str('h$'), '<h$></h$>'); equal(str('.nav'), '<? class=nav></?>'); equal(str('div.width1\\/2'), '<div class=width1/2></div>'); equal(str('#sample*3'), '<?*3 id=sample></?>'); // https://github.com/emmetio/emmet/issues/562 equal(str('li[repeat.for="todo of todoList"]'), '<li repeat.for="todo of todoList"></li>', 'Dots in attribute names'); equal(str('a>b'), '<a><b></b></a>'); equal(str('a+b'), '<a></a><b></b>'); equal(str('a+b>c+d'), '<a></a><b><c></c><d></d></b>'); equal(str('a>b>c+e'), '<a><b><c></c><e></e></b></a>'); equal(str('a>b>c^d'), '<a><b><c></c></b><d></d></a>'); equal(str('a>b>c^^^^d'), '<a><b><c></c></b></a><d></d>'); equal(str('a:b>c'), '<a:b><c></c></a:b>'); equal(str('ul.nav[title="foo"]'), '<ul class=nav title="foo"></ul>'); }); it('groups', () => { equal(str('a>(b>c)+d'), '<a>(<b><c></c></b>)<d></d></a>'); equal(str('(a>b)+(c>d)'), '(<a><b></b></a>)(<c><d></d></c>)'); equal(str('a>((b>c)(d>e))f'), '<a>((<b><c></c></b>)(<d><e></e></d>))<f></f></a>'); equal(str('a>((((b>c))))+d'), '<a>((((<b><c></c></b>))))<d></d></a>'); equal(str('a>(((b>c))*4)+d'), '<a>(((<b><c></c></b>))*4)<d></d></a>'); equal(str('(div>dl>(dt+dd)*2)'), '(<div><dl>(<dt></dt><dd></dd>)*2</dl></div>)'); equal(str('a>()'), '<a>()</a>'); }); it('attributes', () => { equal(str('[].foo'), '<? class=foo></?>'); equal(str('[a]'), '<? a></?>'); equal(str('[a b c [d]]'), '<? a b c [d]></?>'); equal(str('[a=b]'), '<? a=b></?>'); equal(str('[a=b c= d=e]'), '<? a=b c d=e></?>'); equal(str('[a=b.c d=тест]'), '<? a=b.c d=тест></?>'); equal(str('[[a]=b (c)=d]'), '<? [a]=b (c)=d></?>'); // Quoted attribute values equal(str('[a="b"]'), '<? a="b"></?>'); equal(str('[a="b" c=\'d\' e=""]'), '<? a="b" c=\'d\' e=""></?>'); equal(str('[[a]="b" (c)=\'d\']'), '<? [a]="b" (c)=\'d\'></?>'); // Mixed quoted equal(str('[a="foo\'bar" b=\'foo"bar\' c="foo\\\"bar"]'), '<? a="foo\'bar" b=\'foo"bar\' c="foo"bar"></?>'); // Boolean & implied attributes equal(str('[a. b.]'), '<? a. b.></?>'); equal(str('[!a !b.]'), '<? !a !b.></?>'); // Default values equal(str('["a.b"]'), '<? ?="a.b"></?>'); equal(str('[\'a.b\' "c=d" foo=bar "./test.html"]'), '<? ?=\'a.b\' ?="c=d" foo=bar ?="./test.html"></?>'); // Expressions as values equal(str('[foo={1 + 2} bar={fn(1, "foo")}]'), '<? foo={1 + 2} bar={fn(1, "foo")}></?>'); // Tabstops as unquoted values equal(str('[name=${1} value=${2:test}]'), '<? name=${1} value=${2:test}></?>'); }); it('malformed attributes', () => { equal(str('[a'), '<? a></?>'); equal(str('[a={foo]'), '<? a={foo]></?>'); throws(() => str('[a="foo]'), /Unclosed quote/); throws(() => str('[a=b=c]'), /Unexpected "Operator" token/); }); it('elements', () => { equal(str('div'), '<div></div>'); equal(str('div.foo'), '<div class=foo></div>'); equal(str('div#foo'), '<div id=foo></div>'); equal(str('div#foo.bar'), '<div id=foo class=bar></div>'); equal(str('div.foo#bar'), '<div class=foo id=bar></div>'); equal(str('div.foo.bar.baz'), '<div class=foo class=bar class=baz></div>'); equal(str('.foo'), '<? class=foo></?>'); equal(str('#foo'), '<? id=foo></?>'); equal(str('.foo_bar'), '<? class=foo_bar></?>'); equal(str('#foo.bar'), '<? id=foo class=bar></?>'); // Attribute shorthands equal(str('.'), '<? class></?>'); equal(str('#'), '<? id></?>'); equal(str('#.'), '<? id class></?>'); equal(str('.#.'), '<? class id class></?>'); equal(str('.a..'), '<? class=a class></?>'); // Elements with attributes equal(str('div[foo=bar]'), '<div foo=bar></div>'); equal(str('div.a[b=c]'), '<div class=a b=c></div>'); equal(str('div[b=c].a'), '<div b=c class=a></div>'); equal(str('div[a=b][c="d"]'), '<div a=b c="d"></div>'); equal(str('[b=c]'), '<? b=c></?>'); equal(str('.a[b=c]'), '<? class=a b=c></?>'); equal(str('[b=c].a#d'), '<? b=c class=a id=d></?>'); equal(str('[b=c]a'), '<? b=c></?><a></a>', 'Do not consume node name after attribute set'); // Element with text equal(str('div{foo}'), '<div>foo</div>'); equal(str('{foo}'), '<?>foo</?>'); // Mixed equal(str('div.foo{bar}'), '<div class=foo>bar</div>'); equal(str('.foo{bar}#baz'), '<? class=foo id=baz>bar</?>'); equal(str('.foo[b=c]{bar}'), '<? class=foo b=c>bar</?>'); // Repeated element equal(str('div.foo*3'), '<div*3 class=foo></div>'); equal(str('.foo*'), '<?* class=foo></?>'); equal(str('.a[b=c]*10'), '<?*10 class=a b=c></?>'); equal(str('.a*10[b=c]'), '<?*10 class=a b=c></?>'); equal(str('.a*10{text}'), '<?*10 class=a>text</?>'); // Self-closing element equal(str('div/'), '<div />'); equal(str('.foo/'), '<? class=foo />'); equal(str('.foo[bar]/'), '<? class=foo bar />'); equal(str('.foo/*3'), '<?*3 class=foo />'); equal(str('.foo*3/'), '<?*3 class=foo />'); throws(() => parse('/'), /Unexpected character/); }); it('JSX', () => { const opt = { jsx: true }; equal(str('foo.bar', opt), '<foo class=bar></foo>'); equal(str('Foo.bar', opt), '<Foo class=bar></Foo>'); equal(str('Foo.Bar', opt), '<Foo.Bar></Foo.Bar>'); equal(str('Foo.', opt), '<Foo class></Foo>'); equal(str('Foo.Bar.baz', opt), '<Foo.Bar class=baz></Foo.Bar>'); equal(str('Foo.Bar.Baz', opt), '<Foo.Bar.Baz></Foo.Bar.Baz>'); equal(str('.{theme.class}', opt), '<? class=theme.class></?>'); equal(str('#{id}', opt), '<? id=id></?>'); equal(str('Foo.{theme.class}', opt), '<Foo class=theme.class></Foo>'); }); it('errors', () => { throws(() => parse('str?'), /Unexpected character at 4/); throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); }); }); <MSG> Do not throw errors on missing closing brace <DFF> @@ -153,4 +153,11 @@ describe('Parser', () => { throws(() => parse('foo,bar'), /Unexpected character at 4/); equal(str('foo\\,bar'), '<foo,bar></foo,bar>'); }); + + it('missing braces', () => { + // Do not throw errors on missing closing braces + equal(str('div[title="test"'), '<div title="test"></div>'); + equal(str('div(foo'), '<div></div>(<foo></foo>)'); + equal(str('div{foo'), '<div>foo</div>'); + }); });
    7
    Do not throw errors on missing closing brace
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072117
    <NME> rating.ts <BEF> ADDFILE <MSG> Merge pull request #51 from mxth/rating Refactor rating component <DFF> @@ -0,0 +1,173 @@ +///<reference path="../../../typings/angularjs/angular.d.ts"/> + +'use strict'; + +const ratingConfig = { + max: 5, + size: '', + stateActive: 'active', + stateHover: 'selected', + stateHoverParent: 'selected', + type: 'star' +}; + +class SmRatingController { + static $inject = ['$scope', '$element', '$attrs']; + + hoverValue: number; + readonly: boolean; + + stateHoverParent: string; + + ratingStates: RatingState[]; + icons: Icon[]; + + ngModel: ng.INgModelController; + + constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) { + const + ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))), + stateActive = this.evalAttribute('stateActive'), + stateHover = this.evalAttribute('stateHover'), + stateHoverParent = this.evalAttribute('stateHoverParent'); + + if (angular.isDefined($attrs.readonly)) { + $scope.$watch($attrs.readonly, (readonly: boolean) => { + this.readonly = readonly; + }); + } + + this.icons = ratingStates.map((state, index): Icon => { + const + iconElm = angular.element('<i class="icon"></i>'), + value = index + 1; + + iconElm.on('mouseenter', () => { + $scope.$apply(() => { + if (!this.readonly) { + this.hoverValue = value; + this.$element.addClass(stateHoverParent); + this.updateStateHover(); + } + if (angular.isDefined(this.$attrs.onHover)) { + this.$scope.$eval(this.$attrs.onHover, { value: value }); + } + }); + }); + + iconElm.on('click', () => { + this.rate(value); + }); + + return angular.extend(<Icon>{ + element: iconElm, + index: index, + stateActive: stateActive, + stateHover: stateHover + }, state); + }); + + this.icons.forEach(icon => { + $element.append(icon.element); + }); + + $element + .addClass('ui rating') + .addClass($attrs.type || ratingConfig.type) + .addClass($attrs.size || ratingConfig.size) + .attr({ + 'aria-valuemax': this.icons.length, + 'aria-valuemin': 0, + role: 'slider', + tabindex: 0 + }) + .on('mouseleave', () => { + this.hoverValue = -1; + if (angular.isDefined($attrs.onLeave)) { + $scope.$evalAsync($attrs.onLeave); + } + $element.removeClass(stateHoverParent); + this.updateStateHover(); + }) + .on('keydown', (evt: any) => { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }); + } + + rate(value: number) { + if (!this.readonly && value >= 0 && value <= this.icons.length) { + this.ngModel.$setViewValue(value); + this.ngModel.$render(); + } + } + + init(ngModel: ng.INgModelController) { + this.ngModel = ngModel; + + ngModel.$render = () => { + const value = ngModel.$viewValue; + this.$element.attr('aria-valuenow', value); + + this.icons.forEach((icon: Icon, index) => { + icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive); + }); + }; + + ngModel.$formatters.push((value) => { + if (angular.isNumber(value) && value % 1 !== 0) { + value = Math.round(value); + } + return value; + }); + } + + updateStateHover() { + this.icons.forEach((icon: Icon, index) => { + icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover); + }); + } + + evalAttribute(attr: string) { + return angular.isDefined(this.$attrs[attr]) ? + this.$scope.$eval(this.$attrs[attr]) : + ratingConfig[attr]; + } +} + +class SmRatingDirective implements ng.IDirective { + static instance(): ng.IDirective { + return new SmRatingDirective; + } + + restrict = 'E'; + require = ['smRating', 'ngModel']; + controller = SmRatingController; + link = ( + scope: ng.IScope, + element: ng.IAugmentedJQuery, + attrs, + ctrls: [SmRatingController, ng.INgModelController] + ) => { + const [smRating, ngModel] = ctrls; + smRating.init(ngModel); + }; +} + +interface Icon extends RatingState { + index: number; + element: ng.IAugmentedJQuery; +} + +interface RatingState { + stateActive: string; + stateHover: string; +} + +export const smRatingModule = angular + .module('semantic.ui.modules.rating', []) + .directive('smRating', SmRatingDirective.instance) + .constant('ratingConfig', ratingConfig);
    173
    Merge pull request #51 from mxth/rating
    0
    .ts
    ts
    mit
    Semantic-Org/Semantic-UI-Angular
    10072118
    <NME> rating.ts <BEF> ADDFILE <MSG> Merge pull request #51 from mxth/rating Refactor rating component <DFF> @@ -0,0 +1,173 @@ +///<reference path="../../../typings/angularjs/angular.d.ts"/> + +'use strict'; + +const ratingConfig = { + max: 5, + size: '', + stateActive: 'active', + stateHover: 'selected', + stateHoverParent: 'selected', + type: 'star' +}; + +class SmRatingController { + static $inject = ['$scope', '$element', '$attrs']; + + hoverValue: number; + readonly: boolean; + + stateHoverParent: string; + + ratingStates: RatingState[]; + icons: Icon[]; + + ngModel: ng.INgModelController; + + constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) { + const + ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))), + stateActive = this.evalAttribute('stateActive'), + stateHover = this.evalAttribute('stateHover'), + stateHoverParent = this.evalAttribute('stateHoverParent'); + + if (angular.isDefined($attrs.readonly)) { + $scope.$watch($attrs.readonly, (readonly: boolean) => { + this.readonly = readonly; + }); + } + + this.icons = ratingStates.map((state, index): Icon => { + const + iconElm = angular.element('<i class="icon"></i>'), + value = index + 1; + + iconElm.on('mouseenter', () => { + $scope.$apply(() => { + if (!this.readonly) { + this.hoverValue = value; + this.$element.addClass(stateHoverParent); + this.updateStateHover(); + } + if (angular.isDefined(this.$attrs.onHover)) { + this.$scope.$eval(this.$attrs.onHover, { value: value }); + } + }); + }); + + iconElm.on('click', () => { + this.rate(value); + }); + + return angular.extend(<Icon>{ + element: iconElm, + index: index, + stateActive: stateActive, + stateHover: stateHover + }, state); + }); + + this.icons.forEach(icon => { + $element.append(icon.element); + }); + + $element + .addClass('ui rating') + .addClass($attrs.type || ratingConfig.type) + .addClass($attrs.size || ratingConfig.size) + .attr({ + 'aria-valuemax': this.icons.length, + 'aria-valuemin': 0, + role: 'slider', + tabindex: 0 + }) + .on('mouseleave', () => { + this.hoverValue = -1; + if (angular.isDefined($attrs.onLeave)) { + $scope.$evalAsync($attrs.onLeave); + } + $element.removeClass(stateHoverParent); + this.updateStateHover(); + }) + .on('keydown', (evt: any) => { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }); + } + + rate(value: number) { + if (!this.readonly && value >= 0 && value <= this.icons.length) { + this.ngModel.$setViewValue(value); + this.ngModel.$render(); + } + } + + init(ngModel: ng.INgModelController) { + this.ngModel = ngModel; + + ngModel.$render = () => { + const value = ngModel.$viewValue; + this.$element.attr('aria-valuenow', value); + + this.icons.forEach((icon: Icon, index) => { + icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive); + }); + }; + + ngModel.$formatters.push((value) => { + if (angular.isNumber(value) && value % 1 !== 0) { + value = Math.round(value); + } + return value; + }); + } + + updateStateHover() { + this.icons.forEach((icon: Icon, index) => { + icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover); + }); + } + + evalAttribute(attr: string) { + return angular.isDefined(this.$attrs[attr]) ? + this.$scope.$eval(this.$attrs[attr]) : + ratingConfig[attr]; + } +} + +class SmRatingDirective implements ng.IDirective { + static instance(): ng.IDirective { + return new SmRatingDirective; + } + + restrict = 'E'; + require = ['smRating', 'ngModel']; + controller = SmRatingController; + link = ( + scope: ng.IScope, + element: ng.IAugmentedJQuery, + attrs, + ctrls: [SmRatingController, ng.INgModelController] + ) => { + const [smRating, ngModel] = ctrls; + smRating.init(ngModel); + }; +} + +interface Icon extends RatingState { + index: number; + element: ng.IAugmentedJQuery; +} + +interface RatingState { + stateActive: string; + stateHover: string; +} + +export const smRatingModule = angular + .module('semantic.ui.modules.rating', []) + .directive('smRating', SmRatingDirective.instance) + .constant('ratingConfig', ratingConfig);
    173
    Merge pull request #51 from mxth/rating
    0
    .ts
    ts
    mit
    Semantic-Org/Semantic-UI-Angular
    10072119
    <NME> rating.ts <BEF> ADDFILE <MSG> Merge pull request #51 from mxth/rating Refactor rating component <DFF> @@ -0,0 +1,173 @@ +///<reference path="../../../typings/angularjs/angular.d.ts"/> + +'use strict'; + +const ratingConfig = { + max: 5, + size: '', + stateActive: 'active', + stateHover: 'selected', + stateHoverParent: 'selected', + type: 'star' +}; + +class SmRatingController { + static $inject = ['$scope', '$element', '$attrs']; + + hoverValue: number; + readonly: boolean; + + stateHoverParent: string; + + ratingStates: RatingState[]; + icons: Icon[]; + + ngModel: ng.INgModelController; + + constructor(public $scope: ng.IScope, public $element: ng.IAugmentedJQuery, public $attrs) { + const + ratingStates: RatingState[] = this.evalAttribute('ratingStates') || Array.apply(null, Array(this.evalAttribute('max'))), + stateActive = this.evalAttribute('stateActive'), + stateHover = this.evalAttribute('stateHover'), + stateHoverParent = this.evalAttribute('stateHoverParent'); + + if (angular.isDefined($attrs.readonly)) { + $scope.$watch($attrs.readonly, (readonly: boolean) => { + this.readonly = readonly; + }); + } + + this.icons = ratingStates.map((state, index): Icon => { + const + iconElm = angular.element('<i class="icon"></i>'), + value = index + 1; + + iconElm.on('mouseenter', () => { + $scope.$apply(() => { + if (!this.readonly) { + this.hoverValue = value; + this.$element.addClass(stateHoverParent); + this.updateStateHover(); + } + if (angular.isDefined(this.$attrs.onHover)) { + this.$scope.$eval(this.$attrs.onHover, { value: value }); + } + }); + }); + + iconElm.on('click', () => { + this.rate(value); + }); + + return angular.extend(<Icon>{ + element: iconElm, + index: index, + stateActive: stateActive, + stateHover: stateHover + }, state); + }); + + this.icons.forEach(icon => { + $element.append(icon.element); + }); + + $element + .addClass('ui rating') + .addClass($attrs.type || ratingConfig.type) + .addClass($attrs.size || ratingConfig.size) + .attr({ + 'aria-valuemax': this.icons.length, + 'aria-valuemin': 0, + role: 'slider', + tabindex: 0 + }) + .on('mouseleave', () => { + this.hoverValue = -1; + if (angular.isDefined($attrs.onLeave)) { + $scope.$evalAsync($attrs.onLeave); + } + $element.removeClass(stateHoverParent); + this.updateStateHover(); + }) + .on('keydown', (evt: any) => { + if (/(37|38|39|40)/.test(evt.which)) { + evt.preventDefault(); + evt.stopPropagation(); + this.rate(this.ngModel.$viewValue + (evt.which === 38 || evt.which === 39 ? 1 : -1)); + } + }); + } + + rate(value: number) { + if (!this.readonly && value >= 0 && value <= this.icons.length) { + this.ngModel.$setViewValue(value); + this.ngModel.$render(); + } + } + + init(ngModel: ng.INgModelController) { + this.ngModel = ngModel; + + ngModel.$render = () => { + const value = ngModel.$viewValue; + this.$element.attr('aria-valuenow', value); + + this.icons.forEach((icon: Icon, index) => { + icon.element[index < value ? 'addClass' : 'removeClass'](icon.stateActive); + }); + }; + + ngModel.$formatters.push((value) => { + if (angular.isNumber(value) && value % 1 !== 0) { + value = Math.round(value); + } + return value; + }); + } + + updateStateHover() { + this.icons.forEach((icon: Icon, index) => { + icon.element[index < this.hoverValue ? 'addClass' : 'removeClass'](icon.stateHover); + }); + } + + evalAttribute(attr: string) { + return angular.isDefined(this.$attrs[attr]) ? + this.$scope.$eval(this.$attrs[attr]) : + ratingConfig[attr]; + } +} + +class SmRatingDirective implements ng.IDirective { + static instance(): ng.IDirective { + return new SmRatingDirective; + } + + restrict = 'E'; + require = ['smRating', 'ngModel']; + controller = SmRatingController; + link = ( + scope: ng.IScope, + element: ng.IAugmentedJQuery, + attrs, + ctrls: [SmRatingController, ng.INgModelController] + ) => { + const [smRating, ngModel] = ctrls; + smRating.init(ngModel); + }; +} + +interface Icon extends RatingState { + index: number; + element: ng.IAugmentedJQuery; +} + +interface RatingState { + stateActive: string; + stateHover: string; +} + +export const smRatingModule = angular + .module('semantic.ui.modules.rating', []) + .directive('smRating', SmRatingDirective.instance) + .constant('ratingConfig', ratingConfig);
    173
    Merge pull request #51 from mxth/rating
    0
    .ts
    ts
    mit
    Semantic-Org/Semantic-UI-Angular
    10072120
    <NME> style.css <BEF> html { background: #efefef; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 13px; } body { padding: 0 10px; margin: 10px auto 0; } .header { background: #ededed; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#576a76), color-stop(100%,#4d5256)); background: -moz-linear-gradient(top, #576076 0%, #414e58 100%); background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%); background: -o-linear-gradient(top, #576a76 0%, #414e58 100%); background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%); background: linear-gradient(top, #576a76 0%, #414e58 100%); border-bottom: 1px solid #fff; -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; border-top-left-radius: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-right-radius:5px; border-top-right-radius: 5px; overflow:hidden; padding: 10px 5%; text-shadow:0 1px 0 #000; } } .reset{ font-size:10px; line-height:38px; } .header ul li { display: inline; } .header ul li a { color: #eee; text-decoration: none; margin-right: 10px; display: inline-block; padding: 4px 8px; -moz-border-radius: 10px; -webkit-border-radius:10px; border-radius: 10px; } .header ul li a:hover { background: rgba(255,255,255,0.1); } .header ul li a:active { -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); } .header ul li.current a { background: rgba(255,255,255,0.1); -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); color: #fff; } .header p.environment { clear: both; padding: 10px 0 0 0; color: #BBB; font-style: italic; float: right; } #main { padding: 10px 5%; background: #f9f9f9; border:1px solid #ccc; border-top:none; -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2); -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2); box-shadow: 0 3px 10px rgba(0,0,0,0.2); overflow: hidden; } #main .logo { float: right; margin: 10px; } #main span.hl { background: #efefef; padding: 2px; } #main h1 { margin: 10px 0; font-size: 190%; font-weight: bold; color: #0080FF; } #main table { width: 100%; margin:0 0 10px; } #main table tr td, #main table tr th { border-bottom: 1px solid #ccc; padding: 6px; } #main table tr th { background: #efefef; color: #888; font-size: 80%; text-transform:uppercase; } #main table tr td.no-data { text-align: center; padding: 40px 0; color: #999; font-style: italic; font-size: 130%; } #main a { color: #111; } #main p { margin: 5px 0; } #main p.intro { margin-bottom: 15px; font-size: 85%; color: #999; margin-top: 0; line-height: 1.3; } #main h1.wi { margin-bottom: 5px; } #main p.sub { font-size: 95%; color: #999; } .experiment { background:#fff; border: 1px solid #eee; border-bottom:none; margin:30px 0; } .experiment_with_goal { margin: -32px 0 30px 0; } .experiment .experiment-header { background: #f4f4f4; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f4f4), color-stop(100%,#e0e0e0)); background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%); background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); border-top:1px solid #fff; overflow:hidden; padding:0 10px; } .experiment h2 { color:#888; margin: 12px 0 12px 0; font-size: 1em; font-weight:bold; float:left; text-shadow:0 1px 0 rgba(255,255,255,0.8); } .experiment h2 .goal { font-style: italic; } .experiment h2 .version { font-style:italic; font-size:0.8em; color:#bbb; font-weight:normal; } .experiment table em{ font-style:italic; font-size:0.9em; color:#bbb; } .experiment table .totals td { background: #eee; font-weight: bold; } #footer { padding: 10px 5%; color: #999; font-size: 85%; line-height: 1.5; padding-top: 10px; } #footer p a { color: #999; } .inline-controls { float:right; } .inline-controls small { color: #888; font-size: 11px; } .inline-controls form { display: inline-block; font-size: 10px; line-height: 38px; } .inline-controls input { margin-left: 10px; } .worse, .better { color: #773F3F; font-size: 10px; font-weight:bold; } .better { color: #408C48; } .experiment a.button, .experiment button, .experiment input[type="submit"] { padding: 4px 10px; overflow: hidden; background: #d8dae0; -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5); -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5); box-shadow: 0 1px 0 rgba(0,0,0,0.5); border:none; -moz-border-radius: 30px; -webkit-border-radius:30px; border-radius: 30px; color:#2e3035; cursor: pointer; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; text-decoration: none; text-shadow:0 1px 0 rgba(255,255,255,0.8); -moz-user-select: none; -webkit-user-select:none; user-select: none; white-space: nowrap; } a.button:hover, button:hover, input[type="submit"]:hover, a.button:focus, button:focus, input[type="submit"]:focus{ background:#bbbfc7; } a.button:active, button:active, input[type="submit"]:active{ -moz-box-shadow: inset 0 0 4px #484d57; -webkit-box-shadow:inset 0 0 4px #484d57; box-shadow: inset 0 0 4px #484d57; position:relative; top:1px; } a.button.red, button.red, input[type="submit"].red, a.button.green, button.green, input[type="submit"].green { color:#fff; text-shadow:0 1px 0 rgba(0,0,0,0.4); } a.button.red, button.red, input[type="submit"].red { background:#a56d6d; } a.button.red:hover, button.red:hover, input[type="submit"].red:hover, a.button.red:focus, button.red:focus, input[type="submit"].red:focus { background:#895C5C; } a.button.green, button.green, input[type="submit"].green { background:#8daa92; } a.button.green:hover, button.green:hover, input[type="submit"].green:hover, a.button.green:focus, button.green:focus, input[type="submit"].green:focus { background:#768E7A; } .dashboard-controls input, .dashboard-controls select { padding: 10px; } .dashboard-controls-bottom { margin-top: 10px; } .pagination { text-align: center; font-size: 15px; } .pagination a, .paginaton span { display: inline-block; padding: 5px; } .divider { display: inline-block; margin-left: 10px; } <MSG> no more massive clickable area on the reset button <DFF> @@ -35,6 +35,7 @@ h2{ } .reset{ + display:inline-block; font-size:10px; line-height:38px; }
    1
    no more massive clickable area on the reset button
    0
    .css
    css
    mit
    splitrb/split
    10072121
    <NME> style.css <BEF> html { background: #efefef; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 13px; } body { padding: 0 10px; margin: 10px auto 0; } .header { background: #ededed; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#576a76), color-stop(100%,#4d5256)); background: -moz-linear-gradient(top, #576076 0%, #414e58 100%); background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%); background: -o-linear-gradient(top, #576a76 0%, #414e58 100%); background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%); background: linear-gradient(top, #576a76 0%, #414e58 100%); border-bottom: 1px solid #fff; -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; border-top-left-radius: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-right-radius:5px; border-top-right-radius: 5px; overflow:hidden; padding: 10px 5%; text-shadow:0 1px 0 #000; } } .reset{ font-size:10px; line-height:38px; } .header ul li { display: inline; } .header ul li a { color: #eee; text-decoration: none; margin-right: 10px; display: inline-block; padding: 4px 8px; -moz-border-radius: 10px; -webkit-border-radius:10px; border-radius: 10px; } .header ul li a:hover { background: rgba(255,255,255,0.1); } .header ul li a:active { -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); } .header ul li.current a { background: rgba(255,255,255,0.1); -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); color: #fff; } .header p.environment { clear: both; padding: 10px 0 0 0; color: #BBB; font-style: italic; float: right; } #main { padding: 10px 5%; background: #f9f9f9; border:1px solid #ccc; border-top:none; -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2); -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2); box-shadow: 0 3px 10px rgba(0,0,0,0.2); overflow: hidden; } #main .logo { float: right; margin: 10px; } #main span.hl { background: #efefef; padding: 2px; } #main h1 { margin: 10px 0; font-size: 190%; font-weight: bold; color: #0080FF; } #main table { width: 100%; margin:0 0 10px; } #main table tr td, #main table tr th { border-bottom: 1px solid #ccc; padding: 6px; } #main table tr th { background: #efefef; color: #888; font-size: 80%; text-transform:uppercase; } #main table tr td.no-data { text-align: center; padding: 40px 0; color: #999; font-style: italic; font-size: 130%; } #main a { color: #111; } #main p { margin: 5px 0; } #main p.intro { margin-bottom: 15px; font-size: 85%; color: #999; margin-top: 0; line-height: 1.3; } #main h1.wi { margin-bottom: 5px; } #main p.sub { font-size: 95%; color: #999; } .experiment { background:#fff; border: 1px solid #eee; border-bottom:none; margin:30px 0; } .experiment_with_goal { margin: -32px 0 30px 0; } .experiment .experiment-header { background: #f4f4f4; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f4f4), color-stop(100%,#e0e0e0)); background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%); background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); border-top:1px solid #fff; overflow:hidden; padding:0 10px; } .experiment h2 { color:#888; margin: 12px 0 12px 0; font-size: 1em; font-weight:bold; float:left; text-shadow:0 1px 0 rgba(255,255,255,0.8); } .experiment h2 .goal { font-style: italic; } .experiment h2 .version { font-style:italic; font-size:0.8em; color:#bbb; font-weight:normal; } .experiment table em{ font-style:italic; font-size:0.9em; color:#bbb; } .experiment table .totals td { background: #eee; font-weight: bold; } #footer { padding: 10px 5%; color: #999; font-size: 85%; line-height: 1.5; padding-top: 10px; } #footer p a { color: #999; } .inline-controls { float:right; } .inline-controls small { color: #888; font-size: 11px; } .inline-controls form { display: inline-block; font-size: 10px; line-height: 38px; } .inline-controls input { margin-left: 10px; } .worse, .better { color: #773F3F; font-size: 10px; font-weight:bold; } .better { color: #408C48; } .experiment a.button, .experiment button, .experiment input[type="submit"] { padding: 4px 10px; overflow: hidden; background: #d8dae0; -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5); -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5); box-shadow: 0 1px 0 rgba(0,0,0,0.5); border:none; -moz-border-radius: 30px; -webkit-border-radius:30px; border-radius: 30px; color:#2e3035; cursor: pointer; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; text-decoration: none; text-shadow:0 1px 0 rgba(255,255,255,0.8); -moz-user-select: none; -webkit-user-select:none; user-select: none; white-space: nowrap; } a.button:hover, button:hover, input[type="submit"]:hover, a.button:focus, button:focus, input[type="submit"]:focus{ background:#bbbfc7; } a.button:active, button:active, input[type="submit"]:active{ -moz-box-shadow: inset 0 0 4px #484d57; -webkit-box-shadow:inset 0 0 4px #484d57; box-shadow: inset 0 0 4px #484d57; position:relative; top:1px; } a.button.red, button.red, input[type="submit"].red, a.button.green, button.green, input[type="submit"].green { color:#fff; text-shadow:0 1px 0 rgba(0,0,0,0.4); } a.button.red, button.red, input[type="submit"].red { background:#a56d6d; } a.button.red:hover, button.red:hover, input[type="submit"].red:hover, a.button.red:focus, button.red:focus, input[type="submit"].red:focus { background:#895C5C; } a.button.green, button.green, input[type="submit"].green { background:#8daa92; } a.button.green:hover, button.green:hover, input[type="submit"].green:hover, a.button.green:focus, button.green:focus, input[type="submit"].green:focus { background:#768E7A; } .dashboard-controls input, .dashboard-controls select { padding: 10px; } .dashboard-controls-bottom { margin-top: 10px; } .pagination { text-align: center; font-size: 15px; } .pagination a, .paginaton span { display: inline-block; padding: 5px; } .divider { display: inline-block; margin-left: 10px; } <MSG> no more massive clickable area on the reset button <DFF> @@ -35,6 +35,7 @@ h2{ } .reset{ + display:inline-block; font-size:10px; line-height:38px; }
    1
    no more massive clickable area on the reset button
    0
    .css
    css
    mit
    splitrb/split
    10072122
    <NME> style.css <BEF> html { background: #efefef; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 13px; } body { padding: 0 10px; margin: 10px auto 0; } .header { background: #ededed; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#576a76), color-stop(100%,#4d5256)); background: -moz-linear-gradient(top, #576076 0%, #414e58 100%); background: -webkit-linear-gradient(top, #576a76 0%, #414e58 100%); background: -o-linear-gradient(top, #576a76 0%, #414e58 100%); background: -ms-linear-gradient(top, #576a76 0%, #414e58 100%); background: linear-gradient(top, #576a76 0%, #414e58 100%); border-bottom: 1px solid #fff; -moz-border-radius-topleft: 5px; -webkit-border-top-left-radius: 5px; border-top-left-radius: 5px; -moz-border-radius-topright: 5px; -webkit-border-top-right-radius:5px; border-top-right-radius: 5px; overflow:hidden; padding: 10px 5%; text-shadow:0 1px 0 #000; } } .reset{ font-size:10px; line-height:38px; } .header ul li { display: inline; } .header ul li a { color: #eee; text-decoration: none; margin-right: 10px; display: inline-block; padding: 4px 8px; -moz-border-radius: 10px; -webkit-border-radius:10px; border-radius: 10px; } .header ul li a:hover { background: rgba(255,255,255,0.1); } .header ul li a:active { -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); } .header ul li.current a { background: rgba(255,255,255,0.1); -moz-box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); -webkit-box-shadow:inset 0 1px 0 rgba(0,0,0,0.2); box-shadow: inset 0 1px 0 rgba(0,0,0,0.2); color: #fff; } .header p.environment { clear: both; padding: 10px 0 0 0; color: #BBB; font-style: italic; float: right; } #main { padding: 10px 5%; background: #f9f9f9; border:1px solid #ccc; border-top:none; -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.2); -webkit-box-shadow:0 3px 10px rgba(0,0,0,0.2); box-shadow: 0 3px 10px rgba(0,0,0,0.2); overflow: hidden; } #main .logo { float: right; margin: 10px; } #main span.hl { background: #efefef; padding: 2px; } #main h1 { margin: 10px 0; font-size: 190%; font-weight: bold; color: #0080FF; } #main table { width: 100%; margin:0 0 10px; } #main table tr td, #main table tr th { border-bottom: 1px solid #ccc; padding: 6px; } #main table tr th { background: #efefef; color: #888; font-size: 80%; text-transform:uppercase; } #main table tr td.no-data { text-align: center; padding: 40px 0; color: #999; font-style: italic; font-size: 130%; } #main a { color: #111; } #main p { margin: 5px 0; } #main p.intro { margin-bottom: 15px; font-size: 85%; color: #999; margin-top: 0; line-height: 1.3; } #main h1.wi { margin-bottom: 5px; } #main p.sub { font-size: 95%; color: #999; } .experiment { background:#fff; border: 1px solid #eee; border-bottom:none; margin:30px 0; } .experiment_with_goal { margin: -32px 0 30px 0; } .experiment .experiment-header { background: #f4f4f4; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f4f4f4), color-stop(100%,#e0e0e0)); background: -moz-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -webkit-linear-gradient(top, #f4f4f4 0%, #e0e0e0 100%); background: -o-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: -ms-linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); background: linear-gradient (top, #f4f4f4 0%, #e0e0e0 100%); border-top:1px solid #fff; overflow:hidden; padding:0 10px; } .experiment h2 { color:#888; margin: 12px 0 12px 0; font-size: 1em; font-weight:bold; float:left; text-shadow:0 1px 0 rgba(255,255,255,0.8); } .experiment h2 .goal { font-style: italic; } .experiment h2 .version { font-style:italic; font-size:0.8em; color:#bbb; font-weight:normal; } .experiment table em{ font-style:italic; font-size:0.9em; color:#bbb; } .experiment table .totals td { background: #eee; font-weight: bold; } #footer { padding: 10px 5%; color: #999; font-size: 85%; line-height: 1.5; padding-top: 10px; } #footer p a { color: #999; } .inline-controls { float:right; } .inline-controls small { color: #888; font-size: 11px; } .inline-controls form { display: inline-block; font-size: 10px; line-height: 38px; } .inline-controls input { margin-left: 10px; } .worse, .better { color: #773F3F; font-size: 10px; font-weight:bold; } .better { color: #408C48; } .experiment a.button, .experiment button, .experiment input[type="submit"] { padding: 4px 10px; overflow: hidden; background: #d8dae0; -moz-box-shadow: 0 1px 0 rgba(0,0,0,0.5); -webkit-box-shadow:0 1px 0 rgba(0,0,0,0.5); box-shadow: 0 1px 0 rgba(0,0,0,0.5); border:none; -moz-border-radius: 30px; -webkit-border-radius:30px; border-radius: 30px; color:#2e3035; cursor: pointer; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; text-decoration: none; text-shadow:0 1px 0 rgba(255,255,255,0.8); -moz-user-select: none; -webkit-user-select:none; user-select: none; white-space: nowrap; } a.button:hover, button:hover, input[type="submit"]:hover, a.button:focus, button:focus, input[type="submit"]:focus{ background:#bbbfc7; } a.button:active, button:active, input[type="submit"]:active{ -moz-box-shadow: inset 0 0 4px #484d57; -webkit-box-shadow:inset 0 0 4px #484d57; box-shadow: inset 0 0 4px #484d57; position:relative; top:1px; } a.button.red, button.red, input[type="submit"].red, a.button.green, button.green, input[type="submit"].green { color:#fff; text-shadow:0 1px 0 rgba(0,0,0,0.4); } a.button.red, button.red, input[type="submit"].red { background:#a56d6d; } a.button.red:hover, button.red:hover, input[type="submit"].red:hover, a.button.red:focus, button.red:focus, input[type="submit"].red:focus { background:#895C5C; } a.button.green, button.green, input[type="submit"].green { background:#8daa92; } a.button.green:hover, button.green:hover, input[type="submit"].green:hover, a.button.green:focus, button.green:focus, input[type="submit"].green:focus { background:#768E7A; } .dashboard-controls input, .dashboard-controls select { padding: 10px; } .dashboard-controls-bottom { margin-top: 10px; } .pagination { text-align: center; font-size: 15px; } .pagination a, .paginaton span { display: inline-block; padding: 5px; } .divider { display: inline-block; margin-left: 10px; } <MSG> no more massive clickable area on the reset button <DFF> @@ -35,6 +35,7 @@ h2{ } .reset{ + display:inline-block; font-size:10px; line-height:38px; }
    1
    no more massive clickable area on the reset button
    0
    .css
    css
    mit
    splitrb/split
    10072123
    <NME> .jscsrc <BEF> { "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "case", "return", "try", "catch", "typeof" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceBeforeBlockStatements": true, "requireParenthesesAroundIIFE": true, "requireSpacesInConditionalExpression": true, "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, "requireBlocksOnNewline": 1, "disallowEmptyBlocks": true, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, "disallowSpaceAfterObjectKeys": true, "requireCommaBeforeLineBreak": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowSpaceBeforePostfixUnaryOperators": true, "disallowSpaceBeforeBinaryOperators": [ "," ], "requireSpaceBeforeBinaryOperators": true, "requireSpaceAfterBinaryOperators": true, "disallowKeywords": [ "with" ], "disallowMultipleLineBreaks": true, "validateLineBreaks": "LF", "validateQuoteMarks": true, "validateIndentation": 2, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowTrailingComma": true, "disallowKeywordsOnNewLine": [ "else" ], "requireLineFeedAtFileEnd": true, "requireCapitalizedConstructors": true, "requireDotNotation": true, "disallowYodaConditions": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireSpaceBeforeObjectValues": true } <MSG> chore(.jsscrc) Updated jssc to use rules as for angularjs <DFF> @@ -1,75 +1,40 @@ { - "requireCurlyBraces": [ - "if", - "else", - "for", - "while", - "do", - "try", - "catch" - ], - "requireSpaceAfterKeywords": [ - "if", - "else", - "for", - "while", - "do", - "switch", - "case", - "return", - "try", - "catch", - "typeof" - ], - "requireSpaceBeforeBinaryOperators": [ - "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", - "&=", "|=", "^=", "+=", - - "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", - "|", "^", "&&", "||", "===", "==", ">=", - "<=", "<", ">", "!=", "!==" - ], - "requireSpaceBeforeBlockStatements": true, - "requireParenthesesAroundIIFE": true, - "requireSpacesInConditionalExpression": true, - "disallowSpacesInNamedFunctionExpression": { + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineStrings": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "disallowSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - "requireBlocksOnNewline": 1, - "disallowEmptyBlocks": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, - "disallowSpaceAfterObjectKeys": true, - "requireCommaBeforeLineBreak": true, - "disallowSpaceAfterPrefixUnaryOperators": true, - "disallowSpaceBeforePostfixUnaryOperators": true, - "disallowSpaceBeforeBinaryOperators": [ - "," - ], - "requireSpaceBeforeBinaryOperators": true, - "requireSpaceAfterBinaryOperators": true, - "disallowKeywords": [ "with" ], - "disallowMultipleLineBreaks": true, - "validateLineBreaks": "LF", - "validateQuoteMarks": true, - "validateIndentation": 2, - "disallowMixedSpacesAndTabs": true, - "disallowTrailingWhitespace": true, "disallowTrailingComma": true, - "disallowKeywordsOnNewLine": [ "else" ], + "disallowTrailingWhitespace": true, + "requireCommaBeforeLineBreak": true, "requireLineFeedAtFileEnd": true, - "requireCapitalizedConstructors": true, - "requireDotNotation": true, - "disallowYodaConditions": true, - "requireSpacesInFunctionExpression": { - "beforeOpeningCurlyBrace": true + "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": { + "afterTest": true, + "beforeConsequent": true, + "afterConsequent": true, + "beforeAlternate": true }, - "disallowSpacesInFunctionExpression": { - "beforeOpeningRoundBrace": true + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true }, - "disallowSpaceAfterObjectKeys": true, - "requireSpaceBeforeObjectValues": true -} \ No newline at end of file + "validateLineBreaks": "LF", + "validateParameterSeparator": ", " +}
    28
    chore(.jsscrc) Updated jssc to use rules as for angularjs
    63
    jscsrc
    mit
    Semantic-Org/Semantic-UI-Angular
    10072124
    <NME> .jscsrc <BEF> { "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "case", "return", "try", "catch", "typeof" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceBeforeBlockStatements": true, "requireParenthesesAroundIIFE": true, "requireSpacesInConditionalExpression": true, "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, "requireBlocksOnNewline": 1, "disallowEmptyBlocks": true, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, "disallowSpaceAfterObjectKeys": true, "requireCommaBeforeLineBreak": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowSpaceBeforePostfixUnaryOperators": true, "disallowSpaceBeforeBinaryOperators": [ "," ], "requireSpaceBeforeBinaryOperators": true, "requireSpaceAfterBinaryOperators": true, "disallowKeywords": [ "with" ], "disallowMultipleLineBreaks": true, "validateLineBreaks": "LF", "validateQuoteMarks": true, "validateIndentation": 2, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowTrailingComma": true, "disallowKeywordsOnNewLine": [ "else" ], "requireLineFeedAtFileEnd": true, "requireCapitalizedConstructors": true, "requireDotNotation": true, "disallowYodaConditions": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireSpaceBeforeObjectValues": true } <MSG> chore(.jsscrc) Updated jssc to use rules as for angularjs <DFF> @@ -1,75 +1,40 @@ { - "requireCurlyBraces": [ - "if", - "else", - "for", - "while", - "do", - "try", - "catch" - ], - "requireSpaceAfterKeywords": [ - "if", - "else", - "for", - "while", - "do", - "switch", - "case", - "return", - "try", - "catch", - "typeof" - ], - "requireSpaceBeforeBinaryOperators": [ - "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", - "&=", "|=", "^=", "+=", - - "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", - "|", "^", "&&", "||", "===", "==", ">=", - "<=", "<", ">", "!=", "!==" - ], - "requireSpaceBeforeBlockStatements": true, - "requireParenthesesAroundIIFE": true, - "requireSpacesInConditionalExpression": true, - "disallowSpacesInNamedFunctionExpression": { + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineStrings": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "disallowSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - "requireBlocksOnNewline": 1, - "disallowEmptyBlocks": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, - "disallowSpaceAfterObjectKeys": true, - "requireCommaBeforeLineBreak": true, - "disallowSpaceAfterPrefixUnaryOperators": true, - "disallowSpaceBeforePostfixUnaryOperators": true, - "disallowSpaceBeforeBinaryOperators": [ - "," - ], - "requireSpaceBeforeBinaryOperators": true, - "requireSpaceAfterBinaryOperators": true, - "disallowKeywords": [ "with" ], - "disallowMultipleLineBreaks": true, - "validateLineBreaks": "LF", - "validateQuoteMarks": true, - "validateIndentation": 2, - "disallowMixedSpacesAndTabs": true, - "disallowTrailingWhitespace": true, "disallowTrailingComma": true, - "disallowKeywordsOnNewLine": [ "else" ], + "disallowTrailingWhitespace": true, + "requireCommaBeforeLineBreak": true, "requireLineFeedAtFileEnd": true, - "requireCapitalizedConstructors": true, - "requireDotNotation": true, - "disallowYodaConditions": true, - "requireSpacesInFunctionExpression": { - "beforeOpeningCurlyBrace": true + "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": { + "afterTest": true, + "beforeConsequent": true, + "afterConsequent": true, + "beforeAlternate": true }, - "disallowSpacesInFunctionExpression": { - "beforeOpeningRoundBrace": true + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true }, - "disallowSpaceAfterObjectKeys": true, - "requireSpaceBeforeObjectValues": true -} \ No newline at end of file + "validateLineBreaks": "LF", + "validateParameterSeparator": ", " +}
    28
    chore(.jsscrc) Updated jssc to use rules as for angularjs
    63
    jscsrc
    mit
    Semantic-Org/Semantic-UI-Angular
    10072125
    <NME> .jscsrc <BEF> { "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "case", "return", "try", "catch", "typeof" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceBeforeBlockStatements": true, "requireParenthesesAroundIIFE": true, "requireSpacesInConditionalExpression": true, "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, "requireBlocksOnNewline": 1, "disallowEmptyBlocks": true, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, "disallowSpaceAfterObjectKeys": true, "requireCommaBeforeLineBreak": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowSpaceBeforePostfixUnaryOperators": true, "disallowSpaceBeforeBinaryOperators": [ "," ], "requireSpaceBeforeBinaryOperators": true, "requireSpaceAfterBinaryOperators": true, "disallowKeywords": [ "with" ], "disallowMultipleLineBreaks": true, "validateLineBreaks": "LF", "validateQuoteMarks": true, "validateIndentation": 2, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowTrailingComma": true, "disallowKeywordsOnNewLine": [ "else" ], "requireLineFeedAtFileEnd": true, "requireCapitalizedConstructors": true, "requireDotNotation": true, "disallowYodaConditions": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpaceAfterObjectKeys": true, "requireSpaceBeforeObjectValues": true } <MSG> chore(.jsscrc) Updated jssc to use rules as for angularjs <DFF> @@ -1,75 +1,40 @@ { - "requireCurlyBraces": [ - "if", - "else", - "for", - "while", - "do", - "try", - "catch" - ], - "requireSpaceAfterKeywords": [ - "if", - "else", - "for", - "while", - "do", - "switch", - "case", - "return", - "try", - "catch", - "typeof" - ], - "requireSpaceBeforeBinaryOperators": [ - "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", - "&=", "|=", "^=", "+=", - - "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", - "|", "^", "&&", "||", "===", "==", ">=", - "<=", "<", ">", "!=", "!==" - ], - "requireSpaceBeforeBlockStatements": true, - "requireParenthesesAroundIIFE": true, - "requireSpacesInConditionalExpression": true, - "disallowSpacesInNamedFunctionExpression": { + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineStrings": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "disallowSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true }, "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - "requireBlocksOnNewline": 1, - "disallowEmptyBlocks": true, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, "disallowSpacesInsideArrayBrackets": true, "disallowSpacesInsideParentheses": true, - "disallowSpaceAfterObjectKeys": true, - "requireCommaBeforeLineBreak": true, - "disallowSpaceAfterPrefixUnaryOperators": true, - "disallowSpaceBeforePostfixUnaryOperators": true, - "disallowSpaceBeforeBinaryOperators": [ - "," - ], - "requireSpaceBeforeBinaryOperators": true, - "requireSpaceAfterBinaryOperators": true, - "disallowKeywords": [ "with" ], - "disallowMultipleLineBreaks": true, - "validateLineBreaks": "LF", - "validateQuoteMarks": true, - "validateIndentation": 2, - "disallowMixedSpacesAndTabs": true, - "disallowTrailingWhitespace": true, "disallowTrailingComma": true, - "disallowKeywordsOnNewLine": [ "else" ], + "disallowTrailingWhitespace": true, + "requireCommaBeforeLineBreak": true, "requireLineFeedAtFileEnd": true, - "requireCapitalizedConstructors": true, - "requireDotNotation": true, - "disallowYodaConditions": true, - "requireSpacesInFunctionExpression": { - "beforeOpeningCurlyBrace": true + "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], + "requireSpaceBeforeBlockStatements": true, + "requireSpacesInConditionalExpression": { + "afterTest": true, + "beforeConsequent": true, + "afterConsequent": true, + "beforeAlternate": true }, - "disallowSpacesInFunctionExpression": { - "beforeOpeningRoundBrace": true + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true }, - "disallowSpaceAfterObjectKeys": true, - "requireSpaceBeforeObjectValues": true -} \ No newline at end of file + "validateLineBreaks": "LF", + "validateParameterSeparator": ", " +}
    28
    chore(.jsscrc) Updated jssc to use rules as for angularjs
    63
    jscsrc
    mit
    Semantic-Org/Semantic-UI-Angular
    10072126
    <NME> buildout.cfg <BEF> [buildout] parts = django find-links = http://bitbucket.org/ubernostrum/django-registration/downloads/django-registration-0.8-alpha-1.tar.gz unzip = true eggs = pkginfo django-registration==0.8-alpha-1 [django] recipe = djangorecipe version = 1.1.1 settings = settings eggs = ${buildout:eggs} test = djangopypi project = chishop wsgi = true <MSG> Use development settings by default <DFF> @@ -8,7 +8,7 @@ eggs = pkginfo [django] recipe = djangorecipe version = 1.1.1 -settings = settings +settings = development eggs = ${buildout:eggs} test = djangopypi project = chishop
    1
    Use development settings by default
    1
    .cfg
    cfg
    bsd-3-clause
    ask/chishop
    10072127
    <NME> extract-abbreviation.ts <BEF> ADDFILE <MSG> Unit tests and docs for abbreviation extractor <DFF> @@ -0,0 +1,126 @@ +import { deepStrictEqual, strictEqual, ok } from 'assert'; +import extractAbbreviation, { ExtractOptions, ExtractedAbbreviation } from '../src/extract-abbreviation'; +import isAtHTMLTag from '../src/extract-abbreviation/is-html'; +import scanner from '../src/extract-abbreviation/reader'; +import { consumeQuoted } from '../src/extract-abbreviation/quotes'; + +function extract(abbr: string, options?: Partial<ExtractOptions>) { + let caretPos: number | undefined = abbr.indexOf('|'); + if (caretPos !== -1) { + abbr = abbr.slice(0, caretPos) + abbr.slice(caretPos + 1); + } else { + caretPos = void 0; + } + + return extractAbbreviation(abbr, caretPos, options); +} + +function result(abbreviation: string, location: number, start = location): ExtractedAbbreviation { + return { + abbreviation, + location, + start: start != null ? start : location, + end: location + abbreviation.length + }; +} + +describe('Extract abbreviation', () => { + it('basic', () => { + deepStrictEqual(extract('.bar'), result('.bar', 0)); + deepStrictEqual(extract('.foo .bar'), result('.bar', 5)); + deepStrictEqual(extract('.foo @bar'), result('@bar', 5)); + deepStrictEqual(extract('.foo img/'), result('img/', 5)); + deepStrictEqual(extract('текстdiv'), result('div', 5)); + deepStrictEqual(extract('foo div[foo="текст" bar=текст2]'), result('div[foo="текст" bar=текст2]', 4)); + }); + + it('abbreviation with operators', () => { + deepStrictEqual(extract('a foo+bar.baz'), result('foo+bar.baz', 2)); + deepStrictEqual(extract('a foo>bar+baz*3'), result('foo>bar+baz*3', 2)); + }); + + it('abbreviation with attributes', () => { + deepStrictEqual(extract('a foo[bar|]'), result('foo[bar]', 2)); + deepStrictEqual(extract('a foo[bar="baz" a b]'), result('foo[bar="baz" a b]', 2)); + deepStrictEqual(extract('foo bar[a|] baz'), result('bar[a]', 4)); + }); + + it('tag test', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('foo>bar'), result('foo>bar', 0)); + deepStrictEqual(extract('<foo>bar'), result('bar', 5)); + deepStrictEqual(extract('<foo>bar[a="d" b="c"]>baz'), result('bar[a="d" b="c"]>baz', 5)); + }); + + it('stylesheet abbreviation', () => { + deepStrictEqual(extract('foo{bar|}'), result('foo{bar}', 0)); + deepStrictEqual(extract('foo{bar|}', { type: 'stylesheet' }), result('bar', 4)); + }); + + it('prefixed extract', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '<' }), result('foo>bar[a b="c"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar[a b="<"]>baz', { prefix: '<' }), result('foo>bar[a b="<"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar{<}>baz', { prefix: '<' }), result('foo>bar{<}>baz', 1, 0)); + + // Multiple prefix characters + deepStrictEqual(extract('foo>>>bar[a b="c"]>baz', { prefix: '>>>' }), result('bar[a b="c"]>baz', 6, 3)); + + // Absent prefix + strictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '&&' }), void 0); + }); + + it('HTML test', () => { + const html = (str: string) => isAtHTMLTag(scanner(str)); + + // simple tag + ok(html('<div>')); + ok(html('<div/>')); + ok(html('<div />')); + ok(html('</div>')); + + // tag with attributes + ok(html('<div foo="bar">')); + ok(html('<div foo=bar>')); + ok(html('<div foo>')); + ok(html('<div a="b" c=d>')); + ok(html('<div a=b c=d>')); + ok(html('<div a=^b$ c=d>')); + ok(html('<div a=b c=^%d]$>')); + ok(html('<div title=привет>')); + ok(html('<div title=привет123>')); + ok(html('<foo-bar>')); + + // invalid tags + ok(!html('div>')); + ok(!html('<div')); + ok(!html('<div привет>')); + ok(!html('<div =bar>')); + ok(!html('<div foo=>')); + ok(!html('[a=b c=d]>')); + ok(!html('div[a=b c=d]>')); + }); + + it('consume quotes', () => { + let s = scanner(' "foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 1); + + s = scanner('"foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('""'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('"a\\\"b"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + // don’t eat anything + s = scanner('foo'); + ok(!consumeQuoted(s)); + strictEqual(s.pos, 3); + }); +});
    126
    Unit tests and docs for abbreviation extractor
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072128
    <NME> extract-abbreviation.ts <BEF> ADDFILE <MSG> Unit tests and docs for abbreviation extractor <DFF> @@ -0,0 +1,126 @@ +import { deepStrictEqual, strictEqual, ok } from 'assert'; +import extractAbbreviation, { ExtractOptions, ExtractedAbbreviation } from '../src/extract-abbreviation'; +import isAtHTMLTag from '../src/extract-abbreviation/is-html'; +import scanner from '../src/extract-abbreviation/reader'; +import { consumeQuoted } from '../src/extract-abbreviation/quotes'; + +function extract(abbr: string, options?: Partial<ExtractOptions>) { + let caretPos: number | undefined = abbr.indexOf('|'); + if (caretPos !== -1) { + abbr = abbr.slice(0, caretPos) + abbr.slice(caretPos + 1); + } else { + caretPos = void 0; + } + + return extractAbbreviation(abbr, caretPos, options); +} + +function result(abbreviation: string, location: number, start = location): ExtractedAbbreviation { + return { + abbreviation, + location, + start: start != null ? start : location, + end: location + abbreviation.length + }; +} + +describe('Extract abbreviation', () => { + it('basic', () => { + deepStrictEqual(extract('.bar'), result('.bar', 0)); + deepStrictEqual(extract('.foo .bar'), result('.bar', 5)); + deepStrictEqual(extract('.foo @bar'), result('@bar', 5)); + deepStrictEqual(extract('.foo img/'), result('img/', 5)); + deepStrictEqual(extract('текстdiv'), result('div', 5)); + deepStrictEqual(extract('foo div[foo="текст" bar=текст2]'), result('div[foo="текст" bar=текст2]', 4)); + }); + + it('abbreviation with operators', () => { + deepStrictEqual(extract('a foo+bar.baz'), result('foo+bar.baz', 2)); + deepStrictEqual(extract('a foo>bar+baz*3'), result('foo>bar+baz*3', 2)); + }); + + it('abbreviation with attributes', () => { + deepStrictEqual(extract('a foo[bar|]'), result('foo[bar]', 2)); + deepStrictEqual(extract('a foo[bar="baz" a b]'), result('foo[bar="baz" a b]', 2)); + deepStrictEqual(extract('foo bar[a|] baz'), result('bar[a]', 4)); + }); + + it('tag test', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('foo>bar'), result('foo>bar', 0)); + deepStrictEqual(extract('<foo>bar'), result('bar', 5)); + deepStrictEqual(extract('<foo>bar[a="d" b="c"]>baz'), result('bar[a="d" b="c"]>baz', 5)); + }); + + it('stylesheet abbreviation', () => { + deepStrictEqual(extract('foo{bar|}'), result('foo{bar}', 0)); + deepStrictEqual(extract('foo{bar|}', { type: 'stylesheet' }), result('bar', 4)); + }); + + it('prefixed extract', () => { + deepStrictEqual(extract('<foo>bar[a b="c"]>baz'), result('bar[a b="c"]>baz', 5)); + deepStrictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '<' }), result('foo>bar[a b="c"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar[a b="<"]>baz', { prefix: '<' }), result('foo>bar[a b="<"]>baz', 1, 0)); + deepStrictEqual(extract('<foo>bar{<}>baz', { prefix: '<' }), result('foo>bar{<}>baz', 1, 0)); + + // Multiple prefix characters + deepStrictEqual(extract('foo>>>bar[a b="c"]>baz', { prefix: '>>>' }), result('bar[a b="c"]>baz', 6, 3)); + + // Absent prefix + strictEqual(extract('<foo>bar[a b="c"]>baz', { prefix: '&&' }), void 0); + }); + + it('HTML test', () => { + const html = (str: string) => isAtHTMLTag(scanner(str)); + + // simple tag + ok(html('<div>')); + ok(html('<div/>')); + ok(html('<div />')); + ok(html('</div>')); + + // tag with attributes + ok(html('<div foo="bar">')); + ok(html('<div foo=bar>')); + ok(html('<div foo>')); + ok(html('<div a="b" c=d>')); + ok(html('<div a=b c=d>')); + ok(html('<div a=^b$ c=d>')); + ok(html('<div a=b c=^%d]$>')); + ok(html('<div title=привет>')); + ok(html('<div title=привет123>')); + ok(html('<foo-bar>')); + + // invalid tags + ok(!html('div>')); + ok(!html('<div')); + ok(!html('<div привет>')); + ok(!html('<div =bar>')); + ok(!html('<div foo=>')); + ok(!html('[a=b c=d]>')); + ok(!html('div[a=b c=d]>')); + }); + + it('consume quotes', () => { + let s = scanner(' "foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 1); + + s = scanner('"foo"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('""'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + s = scanner('"a\\\"b"'); + ok(consumeQuoted(s)); + strictEqual(s.pos, 0); + + // don’t eat anything + s = scanner('foo'); + ok(!consumeQuoted(s)); + strictEqual(s.pos, 3); + }); +});
    126
    Unit tests and docs for abbreviation extractor
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072129
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' end s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Add debugger gem <DFF> @@ -25,9 +25,10 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' - s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' - s.add_development_dependency 'rspec', '~> 3.0' - s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' + s.add_development_dependency 'debugger' + s.add_development_dependency 'rack-test' + s.add_development_dependency 'rake' + s.add_development_dependency 'rspec', '~> 3.0' end
    4
    Add debugger gem
    3
    .gemspec
    gemspec
    mit
    splitrb/split
    10072130
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' end s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Add debugger gem <DFF> @@ -25,9 +25,10 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' - s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' - s.add_development_dependency 'rspec', '~> 3.0' - s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' + s.add_development_dependency 'debugger' + s.add_development_dependency 'rack-test' + s.add_development_dependency 'rake' + s.add_development_dependency 'rspec', '~> 3.0' end
    4
    Add debugger gem
    3
    .gemspec
    gemspec
    mit
    splitrb/split
    10072131
    <NME> split.gemspec <BEF> # -*- encoding: utf-8 -*- # frozen_string_literal: true $:.push File.expand_path("../lib", __FILE__) require "split/version" Gem::Specification.new do |s| s.name = "split" s.version = Split::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Andrew Nesbitt"] s.licenses = ["MIT"] s.email = ["[email protected]"] s.homepage = "https://github.com/splitrb/split" s.summary = "Rack based split testing framework" s.metadata = { "homepage_uri" => "https://github.com/splitrb/split", "changelog_uri" => "https://github.com/splitrb/split/blob/main/CHANGELOG.md", "source_code_uri" => "https://github.com/splitrb/split", "bug_tracker_uri" => "https://github.com/splitrb/split/issues", "wiki_uri" => "https://github.com/splitrb/split/wiki", "mailing_list_uri" => "https://groups.google.com/d/forum/split-ruby" } s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' end s.add_dependency "rubystats", ">= 0.3.0" s.add_development_dependency "bundler", ">= 1.17" s.add_development_dependency "simplecov", "~> 0.15" s.add_development_dependency "rack-test", "~> 2.0" s.add_development_dependency "rake", "~> 13" s.add_development_dependency "rspec", "~> 3.7" s.add_development_dependency "pry", "~> 0.10" s.add_development_dependency "rails", ">= 5.0" end <MSG> Add debugger gem <DFF> @@ -25,9 +25,10 @@ Gem::Specification.new do |s| s.add_dependency 'sinatra', '>= 1.2.6' s.add_dependency 'simple-random' - s.add_development_dependency 'rake' s.add_development_dependency 'bundler', '~> 1.6' - s.add_development_dependency 'rspec', '~> 3.0' - s.add_development_dependency 'rack-test' s.add_development_dependency 'coveralls' + s.add_development_dependency 'debugger' + s.add_development_dependency 'rack-test' + s.add_development_dependency 'rake' + s.add_development_dependency 'rspec', '~> 3.0' end
    4
    Add debugger gem
    3
    .gemspec
    gemspec
    mit
    splitrb/split
    10072132
    <NME> transducers.js <BEF> // basic protocol helpers var symbolExists = typeof Symbol !== 'undefined'; var protocols = { iterator: symbolExists ? Symbol.iterator : '@@iterator' }; function throwProtocolError(name, coll) { throw new Error("don't know how to " + name + " collection: " + coll); } function fulfillsProtocol(obj, name) { if(name === 'iterator') { // Accept ill-formed iterators that don't conform to the // protocol by accepting just next() return obj[protocols.iterator] || obj.next; } return obj[protocols[name]]; } function getProtocolProperty(obj, name) { return obj[protocols[name]]; } function iterator(coll) { var iter = getProtocolProperty(coll, 'iterator'); if(iter) { return iter.call(coll); } else if(coll.next) { // Basic duck typing to accept an ill-formed iterator that doesn't // conform to the iterator protocol (all iterators should have the // @@iterator method and return themselves, but some engines don't // have that on generators like older v8) return coll; } else if(isArray(coll)) { return new ArrayIterator(coll); } else if(isObject(coll)) { return new ObjectIterator(coll); } } function ArrayIterator(arr) { this.arr = arr; this.index = 0; } ArrayIterator.prototype.next = function() { if(this.index < this.arr.length) { return { value: this.arr[this.index++], done: false }; } return { done: true } }; function ObjectIterator(obj) { this.obj = obj; this.keys = Object.keys(obj); this.index = 0; } ObjectIterator.prototype.next = function() { if(this.index < this.keys.length) { var k = this.keys[this.index++]; return { value: [k, this.obj[k]], done: false }; } return { done: true } }; // helpers var toString = Object.prototype.toString; var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) { return toString.call(obj) == '[object Array]'; }; function isFunction(x) { return typeof x === 'function'; } function isObject(x) { return x instanceof Object && Object.getPrototypeOf(x) === Object.getPrototypeOf({}); } function isNumber(x) { return typeof x === 'number'; } function Reduced(value) { this.val = val; } function reduce(coll, f, init) { if(isArray(coll)) { var result = init; var index = -1; var len = coll.length; while(++index < len) { result = f(result, coll[index]); if(result instanceof Reduced) { return result.val; } } return result; } else if(fulfillsProtocol(coll, 'iterator')) { var result = init; var iter = iterator(coll); var val = iter.next(); while(!val.done) { result = f(result, val.value); if(result instanceof Reduced) { return result.val; } val = iter.next(); } return result; } else if(isObject(coll)) { return reduce(Object.keys(coll), function(result, k) { return f(result, [k, coll[k]]); }, init); } throwProtocolError('reduce', coll); } function transduce(xform, reducer, init, coll) { reducer = xform(reducer); if(!coll) { coll = init; init = reducer.init(); } var res = reduce(coll, function(res, input) { return reducer.step(res, input); }, init); return reducer.result(res); } function compose() { while(++index < len) { result = xform['@@transducer/step'](result, coll[index]); if(isReduced(result)) { result = deref(result); break; } } return xform['@@transducer/result'](result); } else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) { var result = init; var iter = iterator(coll); var val = iter.next(); while(!val.done) { result = xform['@@transducer/step'](result, val.value); if(isReduced(result)) { result = deref(result); break; } val = iter.next(); } return xform['@@transducer/result'](result); } throwProtocolError('iterate', coll); } function transduce(coll, xform, reducer, init) { xform = xform(reducer); if(init === undefined) { init = xform['@@transducer/init'](); } return reduce(coll, xform, init); } function compose() { var funcs = Array.prototype.slice.call(arguments); return function(r) { var value = r; for(var i=funcs.length-1; i>=0; i--) { value = funcs[i](value); } return value; } } } function arrayMap(f, arr, ctx) { var index = -1; var length = arr.length; var result = Array(length); throw new Error('init value unavailable'); }; t['@@transducer/result'] = function(v) { return v; }; return result; } function arrayFilter(f, arr, ctx) { var len = arr.length; var result = []; f = bound(f, ctx, 2); if(!ctx) { return f; } else { switch(count) { case 1: return function(x) { return f.call(ctx, x); } case 2: return function(x, y) { return f.call(ctx, x, y); } default: return f.bind(ctx); } } } function arrayMap(arr, f, ctx) { var index = -1; var length = arr.length; var result = Array(length); f = bound(f, ctx, 2); while (++index < length) { result[index] = f(arr[index], index); } return result; if(coll) { if(isArray(coll)) { return arrayMap(f, coll, ctx); } return seq(coll, map(f)); } for(var i=0; i<len; i++) { if(f(arr[i], i)) { result.push(arr[i]); } } return result; } function Map(f, xform) { this.xform = xform; this.f = f; } Map.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Map.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Map.prototype['@@transducer/step'] = function(res, input) { return this.xform['@@transducer/step'](res, this.f(input)); }; function map(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { if(isArray(coll)) { return arrayFilter(f, coll, ctx); } return seq(coll, filter(f)); } return function(xform) { return new Map(f, xform); } } function Filter(f, xform) { this.xform = xform; this.f = f; } Filter.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Filter.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Filter.prototype['@@transducer/step'] = function(res, input) { if(this.f(input)) { return this.xform['@@transducer/step'](res, input); } return res; }; function filter(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { if(isArray(coll)) { return arrayFilter(coll, f, ctx); } return seq(coll, filter(f)); } return function(xform) { return new Filter(f, xform); }; } function remove(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); return filter(coll, function(x) { return !f(x); }); } function keep(coll) { return filter(coll, function(x) { return x != null }); } function Dedupe(xform) { this.xform = xform; this.last = undefined; } Dedupe.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Dedupe.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Dedupe.prototype['@@transducer/step'] = function(result, input) { if(input !== this.last) { this.last = input; return this.xform['@@transducer/step'](result, input); } return result; }; function dedupe(coll) { if(coll) { return seq(coll, dedupe()); } return function(xform) { return new Dedupe(xform); } } function TakeWhile(f, xform) { this.xform = xform; this.f = f; } TakeWhile.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; TakeWhile.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; TakeWhile.prototype['@@transducer/step'] = function(result, input) { if(this.f(input)) { return this.xform['@@transducer/step'](result, input); } return new Reduced(result); }; function takeWhile(coll, f, ctx) { if(isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if(coll) { return seq(coll, takeWhile(f)); } return function(xform) { return new TakeWhile(f, xform); } } function Take(n, xform) { this.n = n; this.i = 0; this.xform = xform; } Take.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Take.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Take.prototype['@@transducer/step'] = function(result, input) { if (this.i < this.n) { result = this.xform['@@transducer/step'](result, input); if(this.i + 1 >= this.n) { // Finish reducing on the same step as the final value. TODO: // double-check that this doesn't break any semantics result = ensureReduced(result); } } this.i++; return result; }; function take(coll, n) { if(isNumber(coll)) { n = coll; coll = null } if(coll) { return seq(coll, take(n)); } return function(xform) { return new Take(n, xform); } } function Drop(n, xform) { this.n = n; this.i = 0; this.xform = xform; } Drop.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Drop.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Drop.prototype['@@transducer/step'] = function(result, input) { if(this.i++ < this.n) { return result; } return this.xform['@@transducer/step'](result, input); }; function drop(coll, n) { if(isNumber(coll)) { n = coll; coll = null } if(coll) { return seq(coll, drop(n)); } return function(xform) { return new Drop(n, xform); } } function DropWhile(f, xform) { this.xform = xform; this.f = f; this.dropping = true; } DropWhile.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Cat.prototype.step = function(result, input) { var xform = this.xform; return reduce(input, function(res, input) { return xform.step(res, input) }, result); }; function cat(xform) { if(coll) { return seq(coll, dropWhile(f)); } return function(xform) { return new DropWhile(f, xform); } } function Partition(n, xform) { this.n = n; this.i = 0; this.xform = xform; this.part = new Array(n); } Partition.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Partition.prototype['@@transducer/result'] = function(v) { if (this.i > 0) { return ensureUnreduced(this.xform['@@transducer/step'](v, this.part.slice(0, this.i))); } return this.xform['@@transducer/result'](v); }; Partition.prototype['@@transducer/step'] = function(result, input) { this.part[this.i] = input; this.i += 1; if (this.i === this.n) { var out = this.part.slice(0, this.n); this.part = new Array(this.n); this.i = 0; return this.xform['@@transducer/step'](result, out); } return result; }; function partition(coll, n) { if (isNumber(coll)) { n = coll; coll = null; } if (coll) { return seq(coll, partition(n)); } return function(xform) { return new Partition(n, xform); }; } var NOTHING = {}; function PartitionBy(f, xform) { // TODO: take an "opts" object that allows the user to specify // equality this.f = f; this.xform = xform; this.part = []; this.last = NOTHING; function array(coll, xform) { if(!xform) { return reduce(coll, push, []); } return transduce(xform, arrayReducer, [], coll); } function obj(coll, xform) { if(!xform) { return reduce(coll, merge, {}); } return transduce(xform, objReducer, {}, coll); } PartitionBy.prototype['@@transducer/step'] = function(result, input) { var current = this.f(input); if (current === this.last || this.last === NOTHING) { this.part.push(input); } else { result = this.xform['@@transducer/step'](result, this.part); this.part = [input]; } this.last = current; return result; }; function partitionBy(coll, f, ctx) { if (isFunction(coll)) { ctx = f; f = coll; coll = null; } f = bound(f, ctx); if (coll) { return seq(coll, partitionBy(f)); } return function(xform) { return new PartitionBy(f, xform); }; } function Interpose(sep, xform) { this.sep = sep; this.xform = xform; this.started = false; } Interpose.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Interpose.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Interpose.prototype['@@transducer/step'] = function(result, input) { if (this.started) { var withSep = this.xform['@@transducer/step'](result, this.sep); if (isReduced(withSep)) { return withSep; } else { return this.xform['@@transducer/step'](withSep, input); } } else { this.started = true; return this.xform['@@transducer/step'](result, input); } }; /** * Returns a new collection containing elements of the given * collection, separated by the specified separator. Returns a * transducer if a collection is not provided. */ function interpose(coll, separator) { if (arguments.length === 1) { separator = coll; return function(xform) { return new Interpose(separator, xform); }; } return seq(coll, interpose(separator)); } function Repeat(n, xform) { this.xform = xform; this.n = n; } Repeat.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Repeat.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Repeat.prototype['@@transducer/step'] = function(result, input) { var n = this.n; var r = result; for (var i = 0; i < n; i++) { r = this.xform['@@transducer/step'](r, input); if (isReduced(r)) { break; } } return r; }; /** * Returns a new collection containing elements of the given * collection, each repeated n times. Returns a transducer if a * collection is not provided. */ function repeat(coll, n) { if (arguments.length === 1) { n = coll; return function(xform) { return new Repeat(n, xform); }; } return seq(coll, repeat(n)); } function TakeNth(n, xform) { this.xform = xform; this.n = n; this.i = -1; } TakeNth.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; TakeNth.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; TakeNth.prototype['@@transducer/step'] = function(result, input) { this.i += 1; if (this.i % this.n === 0) { return this.xform['@@transducer/step'](result, input); } return result; }; /** * Returns a new collection of every nth element of the given * collection. Returns a transducer if a collection is not provided. */ function takeNth(coll, nth) { if (arguments.length === 1) { nth = coll; return function(xform) { return new TakeNth(nth, xform); }; } return seq(coll, takeNth(nth)); } // pure transducers (cannot take collections) function Cat(xform) { this.xform = xform; } Cat.prototype['@@transducer/init'] = function() { return this.xform['@@transducer/init'](); }; Cat.prototype['@@transducer/result'] = function(v) { return this.xform['@@transducer/result'](v); }; Cat.prototype['@@transducer/step'] = function(result, input) { var xform = this.xform; var newxform = {}; newxform['@@transducer/init'] = function() { return xform['@@transducer/init'](); }; newxform['@@transducer/result'] = function(v) { return v; }; newxform['@@transducer/step'] = function(result, input) { var val = xform['@@transducer/step'](result, input); return isReduced(val) ? deref(val) : val; }; return reduce(input, newxform, result); }; function cat(xform) { return new Cat(xform); } function mapcat(f, ctx) { f = bound(f, ctx); return compose(map(f), cat); } // collection helpers function push(arr, x) { arr.push(x); return arr; } function merge(obj, x) { if(isArray(x) && x.length === 2) { obj[x[0]] = x[1]; } else { var keys = Object.keys(x); var len = keys.length; for(var i=0; i<len; i++) { obj[keys[i]] = x[keys[i]]; } } return obj; } var arrayReducer = {}; arrayReducer['@@transducer/init'] = function() { return []; }; arrayReducer['@@transducer/result'] = function(v) { return v; }; arrayReducer['@@transducer/step'] = push; var objReducer = {}; objReducer['@@transducer/init'] = function() { return {}; }; objReducer['@@transducer/result'] = function(v) { return v; }; objReducer['@@transducer/step'] = merge; // building new collections function toArray(coll, xform) { if(!xform) { return reduce(coll, arrayReducer, []); } return transduce(coll, xform, arrayReducer, []); } function toObj(coll, xform) { if(!xform) { return reduce(coll, objReducer, {}); } return transduce(coll, xform, objReducer, {}); } function toIter(coll, xform) { if(!xform) { return iterator(coll); } return new LazyTransformer(xform, coll); } function seq(coll, xform) { if(isArray(coll)) { return transduce(coll, xform, arrayReducer, []); } else if(isObject(coll)) { return transduce(coll, xform, objReducer, {}); } else if(coll['@@transducer/step']) { var init; if(coll['@@transducer/init']) { init = coll['@@transducer/init'](); } else { init = new coll.constructor(); } return transduce(coll, xform, coll, init); } else if(fulfillsProtocol(coll, 'iterator')) { return new LazyTransformer(xform, coll); } throwProtocolError('sequence', coll); } function into(to, xform, from) { if(isArray(to)) { return transduce(from, xform, arrayReducer, to); } else if(isObject(to)) { return transduce(from, xform, objReducer, to); } else if(to['@@transducer/step']) { return transduce(from, xform, to, to); } throwProtocolError('into', to); } // laziness var stepper = {}; stepper['@@transducer/result'] = function(v) { return isReduced(v) ? deref(v) : v; }; stepper['@@transducer/step'] = function(lt, x) { lt.items.push(x); return lt.rest; }; function Stepper(xform, iter) { this.xform = xform(stepper); this.iter = iter; } Stepper.prototype['@@transducer/step'] = function(lt) { var len = lt.items.length; while(lt.items.length === len) { var n = this.iter.next(); if(n.done || isReduced(n.value)) { // finalize this.xform['@@transducer/result'](this); break; } // step this.xform['@@transducer/step'](lt, n.value); } } function LazyTransformer(xform, coll) { this.iter = iterator(coll); this.items = []; this.stepper = new Stepper(xform, iterator(coll)); } LazyTransformer.prototype[protocols.iterator] = function() { return this; } LazyTransformer.prototype.next = function() { this['@@transducer/step'](); if(this.items.length) { return { value: this.items.pop(), done: false } } else { return { done: true }; } }; LazyTransformer.prototype['@@transducer/step'] = function() { if(!this.items.length) { this.stepper['@@transducer/step'](this); } } // util function range(n) { var arr = new Array(n); for(var i=0; i<arr.length; i++) { arr[i] = i; } return arr; } module.exports = { reduce: reduce, transformer: transformer, Reduced: Reduced, isReduced: isReduced, iterator: iterator, push: push, merge: merge, transduce: transduce, seq: seq, toArray: toArray, toObj: toObj, toIter: toIter, into: into, compose: compose, map: map, filter: filter, remove: remove, cat: cat, mapcat: mapcat, keep: keep, dedupe: dedupe, take: take, takeWhile: takeWhile, takeNth: takeNth, drop: drop, dropWhile: dropWhile, partition: partition, partitionBy: partitionBy, interpose: interpose, repeat: repeat, range: range, LazyTransformer: LazyTransformer }; <MSG> switch coll and f order in APIs, benchmark tweaks <DFF> @@ -106,50 +106,42 @@ function Reduced(val) { this.val = val; } -function reduce(coll, f, init) { +function reduce(coll, xform, init) { if(isArray(coll)) { var result = init; var index = -1; var len = coll.length; while(++index < len) { - result = f(result, coll[index]); + result = xform.step(result, coll[index]); if(result instanceof Reduced) { return result.val; } } - return result; + return xform.result(result); } - else if(fulfillsProtocol(coll, 'iterator')) { + else if(isObject(coll) || fulfillsProtocol(coll, 'iterator')) { var result = init; var iter = iterator(coll); var val = iter.next(); while(!val.done) { - result = f(result, val.value); + result = xform.step(result, val.value); if(result instanceof Reduced) { return result.val; } val = iter.next(); } - return result; + return xform.result(result); } - else if(isObject(coll)) { - return reduce(Object.keys(coll), function(result, k) { - return f(result, [k, coll[k]]); - }, init); - } - throwProtocolError('reduce', coll); + throwProtocolError('iterate', coll); } function transduce(xform, reducer, init, coll) { - reducer = xform(reducer); + xform = xform(reducer); if(!coll) { coll = init; - init = reducer.init(); + init = xform.init(); } - var res = reduce(coll, function(res, input) { - return reducer.step(res, input); - }, init); - return reducer.result(res); + return reduce(coll, xform, init); } function compose() { @@ -199,7 +191,7 @@ function bound(f, ctx, count) { } } -function arrayMap(f, arr, ctx) { +function arrayMap(arr, f, ctx) { var index = -1; var length = arr.length; var result = Array(length); @@ -211,7 +203,7 @@ function arrayMap(f, arr, ctx) { return result; } -function arrayFilter(f, arr, ctx) { +function arrayFilter(arr, f, ctx) { var len = arr.length; var result = []; f = bound(f, ctx, 2); @@ -247,7 +239,7 @@ function map(coll, f, ctx) { if(coll) { if(isArray(coll)) { - return arrayMap(f, coll, ctx); + return arrayMap(coll, f, ctx); } return seq(coll, map(f)); } @@ -283,7 +275,7 @@ function filter(coll, f, ctx) { if(coll) { if(isArray(coll)) { - return arrayFilter(f, coll, ctx); + return arrayFilter(coll, f, ctx); } return seq(coll, filter(f)); } @@ -486,10 +478,20 @@ Cat.prototype.result = function(v) { Cat.prototype.step = function(result, input) { var xform = this.xform; + var newxform = { + init: function() { + return xform.init(); + }, + result: function(v) { + return v; + }, + step: function(result, input) { + var val = xform.step(result, input); + return (val instanceof Reduced) ? new Reduced(val) : val; + } + } - return reduce(input, function(res, input) { - return xform.step(res, input) - }, result); + return reduce(input, newxform, result); }; function cat(xform) { @@ -559,14 +561,14 @@ function getReducer(coll) { function array(coll, xform) { if(!xform) { - return reduce(coll, push, []); + return reduce(coll, arrayReducer, []); } return transduce(xform, arrayReducer, [], coll); } function obj(coll, xform) { if(!xform) { - return reduce(coll, merge, {}); + return reduce(coll, objReducer, {}); } return transduce(xform, objReducer, {}, coll); }
    29
    switch coll and f order in APIs, benchmark tweaks
    27
    .js
    js
    bsd-2-clause
    jlongster/transducers.js
    10072133
    <NME> index.ngdoc <BEF> ADDFILE <MSG> chore(dgeni): Added content and assets for index page <DFF> @@ -0,0 +1,5 @@ +@ngdoc overview +@name Semantic-UI-Angular API Reference +@description + +Welcome to the Semantic-UI-Angular API docs page! \ No newline at end of file
    5
    chore(dgeni): Added content and assets for index page
    0
    .ngdoc
    ngdoc
    mit
    Semantic-Org/Semantic-UI-Angular
    10072134
    <NME> index.ngdoc <BEF> ADDFILE <MSG> chore(dgeni): Added content and assets for index page <DFF> @@ -0,0 +1,5 @@ +@ngdoc overview +@name Semantic-UI-Angular API Reference +@description + +Welcome to the Semantic-UI-Angular API docs page! \ No newline at end of file
    5
    chore(dgeni): Added content and assets for index page
    0
    .ngdoc
    ngdoc
    mit
    Semantic-Org/Semantic-UI-Angular
    10072135
    <NME> index.ngdoc <BEF> ADDFILE <MSG> chore(dgeni): Added content and assets for index page <DFF> @@ -0,0 +1,5 @@ +@ngdoc overview +@name Semantic-UI-Angular API Reference +@description + +Welcome to the Semantic-UI-Angular API docs page! \ No newline at end of file
    5
    chore(dgeni): Added content and assets for index page
    0
    .ngdoc
    ngdoc
    mit
    Semantic-Org/Semantic-UI-Angular
    10072136
    <NME> dual_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::DualAdapter do let(:context) { "some context" } let(:logged_in_adapter_instance) { double } let(:logged_in_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } } end let(:logged_out_adapter_instance) { double } let(:logged_out_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end context 'when logged in' do subject do described_class.with_config( logged_in: lambda { |context| true }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect_any_instance_of(logged_out_adapter).not_to receive(:[]) expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end context 'when logged out' do subject do described_class.with_config( logged_in: lambda { |context| false }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]) expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end describe "when errors in config" do before { described_class.config.clear } let(:some_proc) { -> { } } it "when no logged in adapter" do expect { described_class.with_config( logged_in: some_proc, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in_adapter/) end it "when no logged out adapter" do expect { described_class.with_config( logged_in: some_proc, logged_in_adapter: logged_in_adapter ).new(context) }.to raise_error(StandardError, /:logged_out_adapter/) end it "when no logged in detector" do expect { described_class.with_config( logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in$/) end end end <MSG> Add a flag to use the new behavior of the DualAdapter <DFF> @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end - context 'when logged in' do - subject do - described_class.with_config( - logged_in: lambda { |context| true }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect_any_instance_of(logged_out_adapter).not_to receive(:[]) - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is false' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect_any_instance_of(logged_out_adapter).not_to receive(:[]=) + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:delete) + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect_any_instance_of(logged_out_adapter).not_to receive(:keys) + expect(subject.keys).to eq(['my_value']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect_any_instance_of(logged_in_adapter).not_to receive(:delete) + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect_any_instance_of(logged_in_adapter).not_to receive(:keys) + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end - context 'when logged out' do - subject do - described_class.with_config( - logged_in: lambda { |context| false }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]) - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is true' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end
    136
    Add a flag to use the new behavior of the DualAdapter
    60
    .rb
    rb
    mit
    splitrb/split
    10072137
    <NME> dual_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::DualAdapter do let(:context) { "some context" } let(:logged_in_adapter_instance) { double } let(:logged_in_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } } end let(:logged_out_adapter_instance) { double } let(:logged_out_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end context 'when logged in' do subject do described_class.with_config( logged_in: lambda { |context| true }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect_any_instance_of(logged_out_adapter).not_to receive(:[]) expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end context 'when logged out' do subject do described_class.with_config( logged_in: lambda { |context| false }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]) expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end describe "when errors in config" do before { described_class.config.clear } let(:some_proc) { -> { } } it "when no logged in adapter" do expect { described_class.with_config( logged_in: some_proc, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in_adapter/) end it "when no logged out adapter" do expect { described_class.with_config( logged_in: some_proc, logged_in_adapter: logged_in_adapter ).new(context) }.to raise_error(StandardError, /:logged_out_adapter/) end it "when no logged in detector" do expect { described_class.with_config( logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in$/) end end end <MSG> Add a flag to use the new behavior of the DualAdapter <DFF> @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end - context 'when logged in' do - subject do - described_class.with_config( - logged_in: lambda { |context| true }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect_any_instance_of(logged_out_adapter).not_to receive(:[]) - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is false' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect_any_instance_of(logged_out_adapter).not_to receive(:[]=) + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:delete) + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect_any_instance_of(logged_out_adapter).not_to receive(:keys) + expect(subject.keys).to eq(['my_value']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect_any_instance_of(logged_in_adapter).not_to receive(:delete) + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect_any_instance_of(logged_in_adapter).not_to receive(:keys) + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end - context 'when logged out' do - subject do - described_class.with_config( - logged_in: lambda { |context| false }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]) - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is true' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end
    136
    Add a flag to use the new behavior of the DualAdapter
    60
    .rb
    rb
    mit
    splitrb/split
    10072138
    <NME> dual_adapter_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" describe Split::Persistence::DualAdapter do let(:context) { "some context" } let(:logged_in_adapter_instance) { double } let(:logged_in_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_in_adapter_instance } } end let(:logged_out_adapter_instance) { double } let(:logged_out_adapter) do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end context 'when logged in' do subject do described_class.with_config( logged_in: lambda { |context| true }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect_any_instance_of(logged_out_adapter).not_to receive(:[]) expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end context 'when logged out' do subject do described_class.with_config( logged_in: lambda { |context| false }, logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) end it '#[]=' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } subject['my_key'] = 'my_value' end it '#[]' do expect_any_instance_of(logged_in_adapter).not_to receive(:[]) expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } expect(subject['my_key']).to eq('my_value') end it '#delete' do expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } expect(subject.delete('my_key')).to eq('my_value') end it '#keys' do expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } expect(subject.keys).to eq(['my_value', 'my_value2']) end end describe "when errors in config" do before { described_class.config.clear } let(:some_proc) { -> { } } it "when no logged in adapter" do expect { described_class.with_config( logged_in: some_proc, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in_adapter/) end it "when no logged out adapter" do expect { described_class.with_config( logged_in: some_proc, logged_in_adapter: logged_in_adapter ).new(context) }.to raise_error(StandardError, /:logged_out_adapter/) end it "when no logged in detector" do expect { described_class.with_config( logged_in_adapter: logged_in_adapter, logged_out_adapter: logged_out_adapter ).new(context) }.to raise_error(StandardError, /:logged_in$/) end end end <MSG> Add a flag to use the new behavior of the DualAdapter <DFF> @@ -14,73 +14,149 @@ describe Split::Persistence::DualAdapter do Class.new.tap { |c| allow(c).to receive(:new) { logged_out_adapter_instance } } end - context 'when logged in' do - subject do - described_class.with_config( - logged_in: lambda { |context| true }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect_any_instance_of(logged_out_adapter).not_to receive(:[]) - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is false' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect_any_instance_of(logged_out_adapter).not_to receive(:[]=) + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:delete) + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect_any_instance_of(logged_out_adapter).not_to receive(:keys) + expect(subject.keys).to eq(['my_value']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: false + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect_any_instance_of(logged_in_adapter).not_to receive(:delete) + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect_any_instance_of(logged_in_adapter).not_to receive(:keys) + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end - context 'when logged out' do - subject do - described_class.with_config( - logged_in: lambda { |context| false }, - logged_in_adapter: logged_in_adapter, - logged_out_adapter: logged_out_adapter - ).new(context) - end - - it '#[]=' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) - expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } - subject['my_key'] = 'my_value' - end - - it '#[]' do - expect_any_instance_of(logged_in_adapter).not_to receive(:[]) - expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } - expect(subject['my_key']).to eq('my_value') - end - - it '#delete' do - expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } - expect(subject.delete('my_key')).to eq('my_value') + context 'when fallback_to_logged_out_adapter is true' do + context 'when logged in' do + subject do + described_class.with_config( + logged_in: lambda { |context| true }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect(logged_in_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect(logged_in_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect_any_instance_of(logged_out_adapter).not_to receive(:[]) + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end - it '#keys' do - expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } - expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } - expect(subject.keys).to eq(['my_value', 'my_value2']) + context 'when logged out' do + subject do + described_class.with_config( + logged_in: lambda { |context| false }, + logged_in_adapter: logged_in_adapter, + logged_out_adapter: logged_out_adapter, + fallback_to_logged_out_adapter: true + ).new(context) + end + + it '#[]=' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]=) + expect(logged_out_adapter_instance).to receive(:[]=).with('my_key', 'my_value') + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { nil } + subject['my_key'] = 'my_value' + end + + it '#[]' do + expect_any_instance_of(logged_in_adapter).not_to receive(:[]) + expect(logged_out_adapter_instance).to receive(:[]).with('my_key') { 'my_value' } + expect(subject['my_key']).to eq('my_value') + end + + it '#delete' do + expect(logged_in_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(logged_out_adapter_instance).to receive(:delete).with('my_key') { 'my_value' } + expect(subject.delete('my_key')).to eq('my_value') + end + + it '#keys' do + expect(logged_in_adapter_instance).to receive(:keys) { ['my_value'] } + expect(logged_out_adapter_instance).to receive(:keys) { ['my_value', 'my_value2'] } + expect(subject.keys).to eq(['my_value', 'my_value2']) + end end end
    136
    Add a flag to use the new behavior of the DualAdapter
    60
    .rb
    rb
    mit
    splitrb/split
    10072139
    <NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end describe "control" do it "should be the first alternative" do experiment.save expect(experiment.control.name).to eq("Basket") end end end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end experiment.next_alternative.name.should eql('green') end end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives <DFF> @@ -122,5 +122,17 @@ describe Split::Experiment do experiment.next_alternative.name.should eql('green') end end -end + describe 'changing an existing experiment' do + it "should reset an experiment if it is loaded with different alternatives" do + experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green') + blue = Split::Alternative.find('blue', 'link_color') + blue.participant_count = 5 + blue.save + same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange') + same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange']) + new_blue = Split::Alternative.find('blue', 'link_color') + new_blue.participant_count.should eql(0) + end + end +end \ No newline at end of file
    13
    If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
    1
    .rb
    rb
    mit
    splitrb/split
    10072140
    <NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end describe "control" do it "should be the first alternative" do experiment.save expect(experiment.control.name).to eq("Basket") end end end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end experiment.next_alternative.name.should eql('green') end end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives <DFF> @@ -122,5 +122,17 @@ describe Split::Experiment do experiment.next_alternative.name.should eql('green') end end -end + describe 'changing an existing experiment' do + it "should reset an experiment if it is loaded with different alternatives" do + experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green') + blue = Split::Alternative.find('blue', 'link_color') + blue.participant_count = 5 + blue.save + same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange') + same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange']) + new_blue = Split::Alternative.find('blue', 'link_color') + new_blue.participant_count.should eql(0) + end + end +end \ No newline at end of file
    13
    If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
    1
    .rb
    rb
    mit
    splitrb/split
    10072141
    <NME> experiment_spec.rb <BEF> # frozen_string_literal: true require "spec_helper" require "time" describe Split::Experiment do def new_experiment(goals = []) Split::Experiment.new("link_color", alternatives: ["blue", "red", "green"], goals: goals) end def alternative(color) Split::Alternative.new(color, "link_color") end let(:experiment) { new_experiment } let(:blue) { alternative("blue") } let(:green) { alternative("green") } context "with an experiment" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"]) } it "should have a name" do expect(experiment.name).to eq("basket_text") end it "should have alternatives" do expect(experiment.alternatives.length).to be 2 end it "should have alternatives with correct names" do expect(experiment.alternatives.collect { |a| a.name }).to eq(["Basket", "Cart"]) end it "should be resettable by default" do expect(experiment.resettable).to be_truthy end it "should save to redis" do experiment.save expect(Split.redis.exists?("basket_text")).to be true end it "should save the start time to redis" do experiment_start_time = Time.at(1372167761) expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should not save the start time to redis when start_manually is enabled" do expect(Split.configuration).to receive(:start_manually).and_return(true) experiment.save expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should save the selected algorithm to redis" do experiment_algorithm = Split::Algorithms::Whiplash experiment.algorithm = experiment_algorithm experiment.save expect(Split::ExperimentCatalog.find("basket_text").algorithm).to eq(experiment_algorithm) end it "should handle having a start time stored as a string" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).twice.and_return(experiment_start_time) experiment.save Split.redis.hset(:experiment_start_times, experiment.name, experiment_start_time.to_s) expect(Split::ExperimentCatalog.find("basket_text").start_time).to eq(experiment_start_time) end it "should handle not having a start time" do experiment_start_time = Time.parse("Sat Mar 03 14:01:03") expect(Time).to receive(:now).and_return(experiment_start_time) experiment.save Split.redis.hdel(:experiment_start_times, experiment.name) expect(Split::ExperimentCatalog.find("basket_text").start_time).to be_nil end it "should not create duplicates when saving multiple times" do experiment.save experiment.save expect(Split.redis.exists?("basket_text")).to be true expect(Split.redis.lrange("basket_text", 0, -1)).to eq(['{"Basket":1}', '{"Cart":1}']) end describe "new record?" do it "should know if it hasn't been saved yet" do expect(experiment.new_record?).to be_truthy end it "should know if it has been saved yet" do experiment.save expect(experiment.new_record?).to be_falsey end end describe "control" do it "should be the first alternative" do experiment.save expect(experiment.control.name).to eq("Basket") end end end describe "initialization" do it "should set the algorithm when passed as an option to the initializer" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end it "should be possible to make an experiment not resettable" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) expect(experiment.resettable).to be_falsey end experiment.next_alternative.name.should eql('green') end end end end describe "persistent configuration" do it "should persist resettable in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], resettable: false) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.resettable).to be_falsey end describe "#metadata" do let(:experiment) { Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash, metadata: meta) } let(:meta) { { a: "b" } } before do experiment.save end it "should delete the key when metadata is removed" do experiment.metadata = nil experiment.save expect(Split.redis.exists?(experiment.metadata_key)).to be_falsey end context "simple hash" do let(:meta) { { "basket" => "a", "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end context "nested hash" do let(:meta) { { "basket" => { "one" => "two" }, "cart" => "b" } } it "should persist metadata in redis" do e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.metadata).to eq(meta) end end end it "should persist algorithm in redis" do experiment = Split::Experiment.new("basket_text", alternatives: ["Basket", "Cart"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("basket_text") expect(e).to eq(experiment) expect(e.algorithm).to eq(Split::Algorithms::Whiplash) end it "should persist a new experiment in redis, that does not exist in the configuration file" do experiment = Split::Experiment.new("foobar", alternatives: ["tra", "la"], algorithm: Split::Algorithms::Whiplash) experiment.save e = Split::ExperimentCatalog.find("foobar") expect(e).to eq(experiment) expect(e.alternatives.collect { |a| a.name }).to eq(["tra", "la"]) end end describe "deleting" do it "should delete itself" do experiment = Split::Experiment.new("basket_text", alternatives: [ "Basket", "Cart"]) experiment.save experiment.delete expect(Split.redis.exists?("link_color")).to be false expect(Split::ExperimentCatalog.find("link_color")).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.delete expect(experiment.version).to eq(1) end it "should call the on_experiment_delete hook" do expect(Split.configuration.on_experiment_delete).to receive(:call) experiment.delete end it "should call the on_before_experiment_delete hook" do expect(Split.configuration.on_before_experiment_delete).to receive(:call) experiment.delete end it "should reset the start time if the experiment should be manually started" do Split.configuration.start_manually = true experiment.start experiment.delete expect(experiment.start_time).to be_nil end it "should default cohorting back to false" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq(true) experiment.delete expect(experiment.cohorting_disabled?).to eq(false) end end describe "winner" do it "should have no winner initially" do expect(experiment.winner).to be_nil end end describe "winner=" do it "should allow you to specify a winner" do experiment.save experiment.winner = "red" expect(experiment.winner.name).to eq("red") end it "should call the on_experiment_winner_choose hook" do expect(Split.configuration.on_experiment_winner_choose).to receive(:call) experiment.winner = "green" end context "when has_winner state is memoized" do before { expect(experiment).to_not have_winner } it "should keep has_winner state consistent" do experiment.winner = "red" expect(experiment).to have_winner end end end describe "reset_winner" do before { experiment.winner = "green" } it "should reset the winner" do experiment.reset_winner expect(experiment.winner).to be_nil end context "when has_winner state is memoized" do before { expect(experiment).to have_winner } it "should keep has_winner state consistent" do experiment.reset_winner expect(experiment).to_not have_winner end end end describe "has_winner?" do context "with winner" do before { experiment.winner = "red" } it "returns true" do expect(experiment).to have_winner end end context "without winner" do it "returns false" do expect(experiment).to_not have_winner end end it "memoizes has_winner state" do expect(experiment).to receive(:winner).once expect(experiment).to_not have_winner expect(experiment).to_not have_winner end end describe "reset" do let(:reset_manually) { false } before do allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) experiment.save green.increment_participation green.increment_participation end it "should reset all alternatives" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end it "should reset the winner" do experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation experiment.reset expect(experiment.winner).to be_nil end it "should increment the version" do expect(experiment.version).to eq(0) experiment.reset expect(experiment.version).to eq(1) end it "should call the on_experiment_reset hook" do expect(Split.configuration.on_experiment_reset).to receive(:call) experiment.reset end it "should call the on_before_experiment_reset hook" do expect(Split.configuration.on_before_experiment_reset).to receive(:call) experiment.reset end end describe "algorithm" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } it "should use the default algorithm if none is specified" do expect(experiment.algorithm).to eq(Split.configuration.algorithm) end it "should use the user specified algorithm for this experiment if specified" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to eq(Split::Algorithms::Whiplash) end end describe "#next_alternative" do context "with multiple alternatives" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue", "red", "green") } context "with winner" do it "should always return the winner" do green = Split::Alternative.new("green", "link_color") experiment.winner = "green" expect(experiment.next_alternative.name).to eq("green") green.increment_participation expect(experiment.next_alternative.name).to eq("green") end end context "without winner" do it "should use the specified algorithm" do experiment.algorithm = Split::Algorithms::Whiplash expect(experiment.algorithm).to receive(:choose_alternative).and_return(Split::Alternative.new("green", "link_color")) expect(experiment.next_alternative.name).to eq("green") end end end context "with single alternative" do let(:experiment) { Split::ExperimentCatalog.find_or_create("link_color", "blue") } it "should always return the only alternative" do expect(experiment.next_alternative.name).to eq("blue") expect(experiment.next_alternative.name).to eq("blue") end end end describe "#cohorting_disabled?" do it "returns false when nothing has been configured" do expect(experiment.cohorting_disabled?).to eq false end it "returns true when enable_cohorting is performed" do experiment.enable_cohorting expect(experiment.cohorting_disabled?).to eq false end it "returns false when nothing has been configured" do experiment.disable_cohorting expect(experiment.cohorting_disabled?).to eq true end end describe "changing an existing experiment" do def same_but_different_alternative Split::ExperimentCatalog.find_or_create("link_color", "blue", "yellow", "orange") end it "should reset an experiment if it is loaded with different alternatives" do experiment.save blue.participant_count = 5 same_experiment = same_but_different_alternative expect(same_experiment.alternatives.map(&:name)).to eq(["blue", "yellow", "orange"]) expect(blue.participant_count).to eq(0) end it "should only reset once" do experiment.save expect(experiment.version).to eq(0) same_experiment = same_but_different_alternative expect(same_experiment.version).to eq(1) same_experiment_again = same_but_different_alternative expect(same_experiment_again.version).to eq(1) end context "when metadata is changed" do it "should increase version" do experiment.save experiment.metadata = { "foo" => "bar" } expect { experiment.save }.to change { experiment.version }.by(1) end it "does not increase version" do experiment.metadata = nil experiment.save expect { experiment.save }.to change { experiment.version }.by(0) end end context "when experiment configuration is changed" do let(:reset_manually) { false } before do experiment.save allow(Split.configuration).to receive(:reset_manually).and_return(reset_manually) green.increment_participation green.increment_participation experiment.set_alternatives_and_options(alternatives: %w(blue red green zip), goals: %w(purchase)) experiment.save end it "resets all alternatives" do expect(green.participant_count).to eq(0) expect(green.completed_count).to eq(0) end context "when reset_manually is set" do let(:reset_manually) { true } it "does not reset alternatives" do expect(green.participant_count).to eq(2) expect(green.completed_count).to eq(0) end end end end describe "alternatives passed as non-strings" do it "should throw an exception if an alternative is passed that is not a string" do expect { Split::ExperimentCatalog.find_or_create("link_color", :blue, :red) }.to raise_error(ArgumentError) expect { Split::ExperimentCatalog.find_or_create("link_enabled", true, false) }.to raise_error(ArgumentError) end end describe "specifying weights" do let(:experiment_with_weight) { Split::ExperimentCatalog.find_or_create("link_color", { "blue" => 1 }, { "red" => 2 }) } it "should work for a new experiment" do expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end it "should work for an existing experiment" do experiment.save expect(experiment_with_weight.alternatives.map(&:weight)).to eq([1, 2]) end end describe "specifying goals" do let(:experiment) { new_experiment(["purchase"]) } context "saving experiment" do let(:same_but_different_goals) { Split::ExperimentCatalog.find_or_create({ "link_color" => ["purchase", "refund"] }, "blue", "red", "green") } before { experiment.save } it "can find existing experiment" do expect(Split::ExperimentCatalog.find("link_color").name).to eq("link_color") end it "should reset an experiment if it is loaded with different goals" do same_but_different_goals expect(Split::ExperimentCatalog.find("link_color").goals).to eq(["purchase", "refund"]) end end it "should have goals" do expect(experiment.goals).to eq(["purchase"]) end context "find or create experiment" do it "should have correct goals" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.goals).to eq(["purchase", "refund"]) experiment = Split::ExperimentCatalog.find_or_create("link_color3", "blue", "red", "green") expect(experiment.goals).to eq([]) end end end describe "beta probability calculation" do it "should return a hash with the probability of each alternative being the best" do experiment = Split::ExperimentCatalog.find_or_create("mathematicians", "bernoulli", "poisson", "lagrange") experiment.calc_winning_alternatives expect(experiment.alternative_probabilities).not_to be_nil end it "should return between 46% and 54% probability for an experiment with 2 alternatives and no data" do experiment = Split::ExperimentCatalog.find_or_create("scientists", "einstein", "bohr") experiment.calc_winning_alternatives expect(experiment.alternatives[0].p_winner).to be_within(0.04).of(0.50) end it "should calculate the probability of being the winning alternative separately for each goal", skip: true do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") goal1 = experiment.goals[0] goal2 = experiment.goals[1] experiment.alternatives.each do |alternative| alternative.participant_count = 50 alternative.set_completed_count(10, goal1) alternative.set_completed_count(15+rand(30), goal2) end experiment.calc_winning_alternatives alt = experiment.alternatives[0] p_goal1 = alt.p_winner(goal1) p_goal2 = alt.p_winner(goal2) expect(p_goal1).not_to be_within(0.04).of(p_goal2) end it "should return nil and not re-calculate probabilities if they have already been calculated today" do experiment = Split::ExperimentCatalog.find_or_create({ "link_color3" => ["purchase", "refund"] }, "blue", "red", "green") expect(experiment.calc_winning_alternatives).not_to be nil expect(experiment.calc_winning_alternatives).to be nil end end end <MSG> If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives <DFF> @@ -122,5 +122,17 @@ describe Split::Experiment do experiment.next_alternative.name.should eql('green') end end -end + describe 'changing an existing experiment' do + it "should reset an experiment if it is loaded with different alternatives" do + experiment = Split::Experiment.find_or_create('link_color', 'blue', 'red', 'green') + blue = Split::Alternative.find('blue', 'link_color') + blue.participant_count = 5 + blue.save + same_experiment = Split::Experiment.find_or_create('link_color', 'blue', 'yellow', 'orange') + same_experiment.alternatives.map(&:name).should eql(['blue', 'yellow', 'orange']) + new_blue = Split::Alternative.find('blue', 'link_color') + new_blue.participant_count.should eql(0) + end + end +end \ No newline at end of file
    13
    If the alternatives of an experiment are changed it resets the experiment and uses the new alternatives
    1
    .rb
    rb
    mit
    splitrb/split
    10072142
    <NME> AUTHORS <BEF> Ask Solem <[email protected]> Rune Halvorsen <[email protected]> Russell Sim <[email protected]> Brian Rosner <[email protected]> Sverre Johansen <[email protected]> Bo Shi <[email protected]> Carl Meyer <[email protected]> Vinícius das Chagas Silva <[email protected]> Vanderson Mota dos Santos <[email protected]> Stefan Foulis <[email protected]> Michael Richardson <[email protected]> Halldór Rúnarsson <[email protected]> Brent Tubbs <[email protected]> David Cramer <[email protected]> <MSG> Added Hugo Lopes Tavares (hugobr) to AUTHORS <DFF> @@ -2,3 +2,4 @@ Ask Solem <[email protected]> Rune Halvorsen <[email protected]> Russell Sim <[email protected]> Brian Rosner <[email protected]> +Hugo Lopes Tavares <[email protected]>
    1
    Added Hugo Lopes Tavares (hugobr) to AUTHORS
    0
    AUTHORS
    bsd-3-clause
    ask/chishop
    10072143
    <NME> tokenizer.ts <BEF> import { deepEqual } from 'assert'; import tokenize from '../src/tokenizer'; describe('Tokenizer', () => { it('numeric values', () => { deepEqual(tokenize('p10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p-10-'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 } ]); deepEqual(tokenize('p-10-20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p-10--20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 } ]); deepEqual(tokenize('p-10-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 8, end: 11 } ]); deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, { type: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, { type: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); }); it('float values', () => { deepEqual(tokenize('p.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.5, rawValue: '.5', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -0.5, rawValue: '-.5', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p.1.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 3, end: 5 }, { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p.1-.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 4, end: 6 }, { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p.1--.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: -0.2, rawValue: '-.2', unit: '', start: 4, end: 7 }, { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 7, end: 9 } ]); deepEqual(tokenize('10'), [ { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 }, ]); // NB: now dot should be a part of literal // throws(() => tokenize('.foo'), /Unexpected character at 1/); }); it('color values', () => { deepEqual(tokenize('c#'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '', start: 1, end: 2 } ]); deepEqual(tokenize('c#1'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 1, raw: '1', start: 1, end: 3 } ]); deepEqual(tokenize('c#.'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '.', start: 1, end: 3 } ]); deepEqual(tokenize('c#f'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 255, b: 255, a: 1, raw: 'f', start: 1, end: 3 } ]); deepEqual(tokenize('c#a#b#c'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 170, g: 170, b: 170, a: 1, raw: 'a', start: 1, end: 3 }, { type: 'ColorValue', r: 187, g: 187, b: 187, a: 1, raw: 'b', start: 3, end: 5 }, { type: 'ColorValue', r: 204, g: 204, b: 204, a: 1, raw: 'c', start: 5, end: 7 } ]); deepEqual(tokenize('c#af'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 175, g: 175, b: 175, a: 1, raw: 'af', start: 1, end: 4 } ]); deepEqual(tokenize('c#fc0'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 1, end: 5 } ]); deepEqual(tokenize('c#11.5'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 0.5, raw: '11.5', start: 1, end: 6 } ]); deepEqual(tokenize('c#.99'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0.99, raw: '.99', start: 1, end: 5 } ]); deepEqual(tokenize('c#t'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0, raw: 't', start: 1, end: 3 } ]); deepEqual(tokenize('c#${fff}'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'Literal', value: '#', start: 1, end: 2 }, { type: 'Field', index: undefined, name: 'fff', start: 2, end: 8 } ]); }); it('keywords', () => { deepEqual(tokenize('m:a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: ':', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 } ]); deepEqual(tokenize('m-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 } ]); deepEqual(tokenize('m-abc'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'abc', start: 2, end: 5 } ]); deepEqual(tokenize('m-a0'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } ]); }); it('arguments', () => { deepEqual(tokenize('lg(top, "red, black", rgb(0, 0, 0) 10%)'), [ { type: 'Literal', value: 'lg', start: 0, end: 2 }, { type: 'Bracket', open: true, start: 2, end: 3 }, { type: 'Literal', value: 'top', start: 3, end: 6 }, { type: 'Operator', operator: ',', start: 6, end: 7 }, { type: 'WhiteSpace', start: 7, end: 8 }, { type: 'StringValue', value: 'red, black', quote: 'double', start: 8, end: 20 }, { type: 'Operator', operator: ',', start: 20, end: 21 }, { type: 'WhiteSpace', start: 21, end: 22 }, { type: 'Literal', value: 'rgb', start: 22, end: 25 }, { type: 'Bracket', open: true, start: 25, end: 26 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 26, end: 27 }, { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } ]); }); it('important', () => { deepEqual(tokenize('!'), [ { type: 'Operator', operator: '!', start: 0, end: 1 } ]); deepEqual(tokenize('p!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'Operator', operator: '!', start: 1, end: 2 } ]); deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } deepEqual(tokenize('bd#fc0-1'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } ]); deepEqual(tokenize('bd#fc0-1'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'Operator', operator: '-', start: 6, end: 7 }, { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '+', start: 2, end: 3 }, { type: 'Literal', value: 'm', start: 3, end: 4 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 4, end: 5 } ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); deepEqual(tokenize('${2:0}%'), [ { type: 'Field', index: 2, name: '0', start: 0, end: 6 }, { type: 'Literal', value: '%', start: 6, end: 7 } ]); deepEqual(tokenize('.${1:5}'), [ { type: 'Literal', value: '.', start: 0, end: 1 }, { type: 'Field', index: 1, name: '5', start: 1, end: 7 }, ]); }); it('embedded variables', () => { deepEqual(tokenize('foo$bar'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 } ]); deepEqual(tokenize('foo$bar-2'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar-2', start: 3, end: 9 } ]); deepEqual(tokenize('foo$bar@bam'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 }, { type: 'Literal', value: '@bam', start: 7, end: 11 } ]); deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 } ]); }); }); <MSG> Working implementation of CSS parser <DFF> @@ -45,8 +45,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, - { type: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); @@ -54,8 +53,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, - { type: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); @@ -246,7 +244,8 @@ describe('Tokenizer', () => { deepEqual(tokenize('bd#fc0-1'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, - { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } + { type: 'Operator', operator: '-', start: 6, end: 7 }, + { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [
    4
    Working implementation of CSS parser
    5
    .ts
    ts
    mit
    emmetio/emmet
    10072144
    <NME> tokenizer.ts <BEF> import { deepEqual } from 'assert'; import tokenize from '../src/tokenizer'; describe('Tokenizer', () => { it('numeric values', () => { deepEqual(tokenize('p10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-10'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p-10-'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 } ]); deepEqual(tokenize('p-10-20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p-10--20'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: -20, rawValue: '-20', unit: '', start: 5, end: 8 } ]); deepEqual(tokenize('p-10-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, rawValue: '-10', unit: '', start: 1, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'NumberValue', value: 20, rawValue: '20', unit: '', start: 5, end: 7 }, { type: 'Operator', operator: '-', start: 7, end: 8 }, { type: 'NumberValue', value: -30, rawValue: '-30', unit: '', start: 8, end: 11 } ]); deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, { type: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, { type: 'Operator', operator: '-', start: 5, end: 6 }, { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); }); it('float values', () => { deepEqual(tokenize('p.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.5, rawValue: '.5', unit: '', start: 1, end: 3 } ]); deepEqual(tokenize('p-.5'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -0.5, rawValue: '-.5', unit: '', start: 1, end: 4 } ]); deepEqual(tokenize('p.1.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 3, end: 5 }, { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 5, end: 7 } ]); deepEqual(tokenize('p.1-.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: 0.2, rawValue: '.2', unit: '', start: 4, end: 6 }, { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p.1--.2.3'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '-', start: 3, end: 4 }, { type: 'NumberValue', value: -0.2, rawValue: '-.2', unit: '', start: 4, end: 7 }, { type: 'NumberValue', value: 0.3, rawValue: '.3', unit: '', start: 7, end: 9 } ]); deepEqual(tokenize('10'), [ { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 0, end: 2 }, ]); deepEqual(tokenize('.1'), [ { type: 'NumberValue', value: 0.1, rawValue: '.1', unit: '', start: 0, end: 2 }, ]); // NB: now dot should be a part of literal // throws(() => tokenize('.foo'), /Unexpected character at 1/); }); it('color values', () => { deepEqual(tokenize('c#'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '', start: 1, end: 2 } ]); deepEqual(tokenize('c#1'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 1, raw: '1', start: 1, end: 3 } ]); deepEqual(tokenize('c#.'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 1, raw: '.', start: 1, end: 3 } ]); deepEqual(tokenize('c#f'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 255, b: 255, a: 1, raw: 'f', start: 1, end: 3 } ]); deepEqual(tokenize('c#a#b#c'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 170, g: 170, b: 170, a: 1, raw: 'a', start: 1, end: 3 }, { type: 'ColorValue', r: 187, g: 187, b: 187, a: 1, raw: 'b', start: 3, end: 5 }, { type: 'ColorValue', r: 204, g: 204, b: 204, a: 1, raw: 'c', start: 5, end: 7 } ]); deepEqual(tokenize('c#af'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 175, g: 175, b: 175, a: 1, raw: 'af', start: 1, end: 4 } ]); deepEqual(tokenize('c#fc0'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 1, end: 5 } ]); deepEqual(tokenize('c#11.5'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 17, g: 17, b: 17, a: 0.5, raw: '11.5', start: 1, end: 6 } ]); deepEqual(tokenize('c#.99'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0.99, raw: '.99', start: 1, end: 5 } ]); deepEqual(tokenize('c#t'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'ColorValue', r: 0, g: 0, b: 0, a: 0, raw: 't', start: 1, end: 3 } ]); deepEqual(tokenize('c#${fff}'), [ { type: 'Literal', value: 'c', start: 0, end: 1 }, { type: 'Literal', value: '#', start: 1, end: 2 }, { type: 'Field', index: undefined, name: 'fff', start: 2, end: 8 } ]); }); it('keywords', () => { deepEqual(tokenize('m:a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: ':', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 } ]); deepEqual(tokenize('m-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 } ]); deepEqual(tokenize('m-abc'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'abc', start: 2, end: 5 } ]); deepEqual(tokenize('m-a0'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 } ]); deepEqual(tokenize('m-a0-a'), [ { type: 'Literal', value: 'm', start: 0, end: 1 }, { type: 'Operator', operator: '-', start: 1, end: 2 }, { type: 'Literal', value: 'a', start: 2, end: 3 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 3, end: 4 }, { type: 'Operator', operator: '-', start: 4, end: 5 }, { type: 'Literal', value: 'a', start: 5, end: 6 } ]); }); it('arguments', () => { deepEqual(tokenize('lg(top, "red, black", rgb(0, 0, 0) 10%)'), [ { type: 'Literal', value: 'lg', start: 0, end: 2 }, { type: 'Bracket', open: true, start: 2, end: 3 }, { type: 'Literal', value: 'top', start: 3, end: 6 }, { type: 'Operator', operator: ',', start: 6, end: 7 }, { type: 'WhiteSpace', start: 7, end: 8 }, { type: 'StringValue', value: 'red, black', quote: 'double', start: 8, end: 20 }, { type: 'Operator', operator: ',', start: 20, end: 21 }, { type: 'WhiteSpace', start: 21, end: 22 }, { type: 'Literal', value: 'rgb', start: 22, end: 25 }, { type: 'Bracket', open: true, start: 25, end: 26 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 26, end: 27 }, { type: 'Operator', operator: ',', start: 27, end: 28 }, { type: 'WhiteSpace', start: 28, end: 29 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 29, end: 30 }, { type: 'Operator', operator: ',', start: 30, end: 31 }, { type: 'WhiteSpace', start: 31, end: 32 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 32, end: 33 }, { type: 'Bracket', open: false, start: 33, end: 34 }, { type: 'WhiteSpace', start: 34, end: 35 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '%', start: 35, end: 38 }, { type: 'Bracket', open: false, start: 38, end: 39 } ]); }); it('important', () => { deepEqual(tokenize('!'), [ { type: 'Operator', operator: '!', start: 0, end: 1 } ]); deepEqual(tokenize('p!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'Operator', operator: '!', start: 1, end: 2 } ]); deepEqual(tokenize('p10!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 1, end: 3 }, { type: 'Operator', operator: '!', start: 3, end: 4 } deepEqual(tokenize('bd#fc0-1'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 's', start: 4, end: 5 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 5, end: 9 } ]); deepEqual(tokenize('bd#fc0-1'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, { type: 'Operator', operator: '-', start: 6, end: 7 }, { type: 'NumberValue', value: 1, rawValue: '1', unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '+', start: 2, end: 3 }, { type: 'Literal', value: 'm', start: 3, end: 4 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 4, end: 5 } ]); deepEqual(tokenize('p0!+m0!'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 1, end: 2 }, { type: 'Operator', operator: '!', start: 2, end: 3 }, { type: 'Operator', operator: '+', start: 3, end: 4 }, { type: 'Literal', value: 'm', start: 4, end: 5 }, { type: 'NumberValue', value: 0, rawValue: '0', unit: '', start: 5, end: 6 }, { type: 'Operator', operator: '!', start: 6, end: 7 } ]); deepEqual(tokenize('${2:0}%'), [ { type: 'Field', index: 2, name: '0', start: 0, end: 6 }, { type: 'Literal', value: '%', start: 6, end: 7 } ]); deepEqual(tokenize('.${1:5}'), [ { type: 'Literal', value: '.', start: 0, end: 1 }, { type: 'Field', index: 1, name: '5', start: 1, end: 7 }, ]); }); it('embedded variables', () => { deepEqual(tokenize('foo$bar'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 } ]); deepEqual(tokenize('foo$bar-2'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar-2', start: 3, end: 9 } ]); deepEqual(tokenize('foo$bar@bam'), [ { type: 'Literal', value: 'foo', start: 0, end: 3 }, { type: 'Literal', value: '$bar', start: 3, end: 7 }, { type: 'Literal', value: '@bam', start: 7, end: 11 } ]); deepEqual(tokenize('@k10'), [ { type: 'Literal', value: '@k', start: 0, end: 2 }, { type: 'NumberValue', value: 10, rawValue: '10', unit: '', start: 2, end: 4 } ]); }); }); <MSG> Working implementation of CSS parser <DFF> @@ -45,8 +45,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p-10p-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: 'p', start: 1, end: 5 }, - { type: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); @@ -54,8 +53,7 @@ describe('Tokenizer', () => { deepEqual(tokenize('p-10%-20--30'), [ { type: 'Literal', value: 'p', start: 0, end: 1 }, { type: 'NumberValue', value: -10, unit: '%', start: 1, end: 5 }, - { type: 'Operator', operator: '-', start: 5, end: 6 }, - { type: 'NumberValue', value: 20, unit: '', start: 6, end: 8 }, + { type: 'NumberValue', value: -20, unit: '', start: 5, end: 8 }, { type: 'Operator', operator: '-', start: 8, end: 9 }, { type: 'NumberValue', value: -30, unit: '', start: 9, end: 12 } ]); @@ -246,7 +244,8 @@ describe('Tokenizer', () => { deepEqual(tokenize('bd#fc0-1'), [ { type: 'Literal', value: 'bd', start: 0, end: 2 }, { type: 'ColorValue', r: 255, g: 204, b: 0, a: 1, raw: 'fc0', start: 2, end: 6 }, - { type: 'NumberValue', value: -1, unit: '', start: 6, end: 8 } + { type: 'Operator', operator: '-', start: 6, end: 7 }, + { type: 'NumberValue', value: 1, unit: '', start: 7, end: 8 } ]); deepEqual(tokenize('p0+m0'), [
    4
    Working implementation of CSS parser
    5
    .ts
    ts
    mit
    emmetio/emmet
    10072145
    <NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% end %> <div class="dashboard-controls dashboard-controls-bottom"> <form action="<%= url "/initialize_experiment" %>" method='post'> <label>Add unregistered experiment: </label> <select name="experiment" id="experiment-select"> <option selected disabled>experiment</option> <% @unintialized_experiments.sort.each do |experiment_name| %> <option value="<%= experiment_name %>"><%= experiment_name %></option> <% end %> </select> <input type="submit" id="register-experiment-btn" value="register experiment"/> </form> <div> <MSG> More robust conversion rate <DFF> @@ -21,7 +21,7 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %>
    1
    More robust conversion rate
    1
    .erb
    erb
    mit
    splitrb/split
    10072146
    <NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% end %> <div class="dashboard-controls dashboard-controls-bottom"> <form action="<%= url "/initialize_experiment" %>" method='post'> <label>Add unregistered experiment: </label> <select name="experiment" id="experiment-select"> <option selected disabled>experiment</option> <% @unintialized_experiments.sort.each do |experiment_name| %> <option value="<%= experiment_name %>"><%= experiment_name %></option> <% end %> </select> <input type="submit" id="register-experiment-btn" value="register experiment"/> </form> <div> <MSG> More robust conversion rate <DFF> @@ -21,7 +21,7 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %>
    1
    More robust conversion rate
    1
    .erb
    erb
    mit
    splitrb/split
    10072147
    <NME> index.erb <BEF> <% if @experiments.any? %> <p class="intro">The list below contains all the registered experiments along with the number of test participants, completed and conversion rate currently in the system.</p> <div class="dashboard-controls"> <input type="text" placeholder="Begin typing to filter" id="filter" /> <input type="button" id="toggle-completed" value="Hide completed" /> <input type="button" id="toggle-active" value="Hide active" /> <input type="button" id="clear-filter" value="Clear filters" /> </div> <% paginated(@experiments).each do |experiment| %> <% if experiment.goals.empty? %> <%= erb :_experiment, :locals => {:goal => nil, :experiment => experiment} %> <% else %> <%= erb :_experiment_with_goal_header, :locals => {:experiment => experiment} %> <% experiment.goals.each do |g| %> <%= erb :_experiment, :locals => {:goal => g, :experiment => experiment} %> <% end %> <% end %> <% end %> <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %> <% end %> <div class="dashboard-controls dashboard-controls-bottom"> <form action="<%= url "/initialize_experiment" %>" method='post'> <label>Add unregistered experiment: </label> <select name="experiment" id="experiment-select"> <option selected disabled>experiment</option> <% @unintialized_experiments.sort.each do |experiment_name| %> <option value="<%= experiment_name %>"><%= experiment_name %></option> <% end %> </select> <input type="submit" id="register-experiment-btn" value="register experiment"/> </form> <div> <MSG> More robust conversion rate <DFF> @@ -21,7 +21,7 @@ <td><%= alternative.participant_count %></td> <td><%= alternative.participant_count - alternative.completed_count %></td> <td><%= alternative.completed_count %></td> - <td><%= (alternative.conversion_rate * 100).round(2) %>%</td> + <td><%= number_to_percentage(alternative.conversion_rate) %>%</td> <td><%= alternative.z_score %></td> <td> <% if experiment.winner %>
    1
    More robust conversion rate
    1
    .erb
    erb
    mit
    splitrb/split
    10072148
    <NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>'); equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); it('limit unroll', () => { // Limit amount of repeated elements equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> Fix wrap around anchor elements with classes (#656) <DFF> @@ -21,6 +21,8 @@ describe('Convert token abbreviations', () => { equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); + equal(parse('html.one.two'), '<html class="one", class="two"></html>'); + equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); @@ -69,6 +71,10 @@ describe('Convert token abbreviations', () => { equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); + equal(parse('a[class=here]', { href: true, text: '[email protected]' }), '<a class="here", href="mailto:[email protected]">[email protected]</a>'); + equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); + equal(parse('a[class=here]', { href: true, text: 'test here [email protected]' }), '<a class="here", href="">test here [email protected]</a>'); + equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>');
    6
    Fix wrap around anchor elements with classes (#656)
    0
    .ts
    ts
    mit
    emmetio/emmet
    10072149
    <NME> convert.ts <BEF> import { equal } from 'assert'; import parser, { ParserOptions } from '../src'; import stringify from './assets/stringify-node'; function parse(abbr: string, options?: ParserOptions) { return stringify(parser(abbr, options)); } describe('Convert token abbreviations', () => { it('basic', () => { equal(parse('input[value="text$"]*2'), '<input*2@0 value="text1"></input><input*2@1 value="text2"></input>'); equal(parse('ul>li.item$*3'), '<ul><li*3@0 class="item1"></li><li*3@1 class="item2"></li><li*3@2 class="item3"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="item1">foo$</li><li*2@1 class="item2">bar$</li></ul>'); equal(parse('ul>li[class=$#]{item $}*', { text: ['foo$', 'bar$'] }), '<ul><li*2@0 class="foo$">item 1</li><li*2@1 class="bar$">item 2</li></ul>'); equal(parse('ul>li.item$*'), '<ul><li*1@0 class="item1"></li></ul>'); equal(parse('ul>li.item$*', { text: ['foo.bar', 'hello.world'] }), '<ul><li*2@0 class="item1">foo.bar</li><li*2@1 class="item2">hello.world</li></ul>'); equal(parse('p{hi}', { text: ['hello'] }), '<p>hihello</p>'); equal(parse('p*{hi}', { text: ['1', '2'] }), '<p*2@0>hi1</p><p*2@1>hi2</p>'); equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); it('unroll', () => { equal(parse('a>(b>c)+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('(a>b)+(c>d)'), '<a><b></b></a><c><d></d></c>'); equal(parse('a>((b>c)(d>e))f'), '<a><b><c></c></b><d><e></e></d><f></f></a>'); equal(parse('a>((((b>c))))+d'), '<a><b><c></c></b><d></d></a>'); equal(parse('a>(((b>c))*4)+d'), '<a><b*4@0><c></c></b><b*4@1><c></c></b><b*4@2><c></c></b><b*4@3><c></c></b><d></d></a>'); equal(parse('(div>dl>(dt+dd)*2)'), '<div><dl><dt*2@0></dt><dd*2@0></dd><dt*2@1></dt><dd*2@1></dd></dl></div>'); equal(parse('a*2>b*3'), '<a*2@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*2@1><b*3@0></b><b*3@1></b><b*3@2></b></a>'); equal(parse('a>(b+c)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c></a>'); equal(parse('a>(b+c)*2+(d+e)*2'), '<a><b*2@0></b><c*2@0></c><b*2@1></b><c*2@1></c><d*2@0></d><e*2@0></e><d*2@1></d><e*2@1></e></a>'); // Should move `<div>` as sibling of `{foo}` equal(parse('p>{foo}>div'), '<p><?>foo</?><div></div></p>'); equal(parse('p>{foo ${0}}>div'), '<p><?>foo ${0}<div></div></?></p>'); }); it('limit unroll', () => { // Limit amount of repeated elements equal(parse('a*10', { maxRepeat: 5 }), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a>'); equal(parse('a*10'), '<a*10@0></a><a*10@1></a><a*10@2></a><a*10@3></a><a*10@4></a><a*10@5></a><a*10@6></a><a*10@7></a><a*10@8></a><a*10@9></a>'); equal(parse('a*3>b*3', { maxRepeat: 5 }), '<a*3@0><b*3@0></b><b*3@1></b><b*3@2></b></a><a*3@1><b*3@0></b></a>'); }); it('parent repeater', () => { equal(parse('a$*2>b$*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b1*3@0 /><b2*3@1 /><b3*3@2 /></a2>'); equal(parse('a$*2>b$@^*3/'), '<a1*2@0><b1*3@0 /><b2*3@1 /><b3*3@2 /></a1><a2*2@1><b4*3@0 /><b5*3@1 /><b6*3@2 /></a2>'); }); it('href', () => { equal(parse('a', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href=]', { href: true, text: 'https://www.google.it' }), '<a href="https://www.google.it">https://www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'www.google.it' }), '<a href="http://www.google.it">www.google.it</a>'); equal(parse('a[href=]', { href: true, text: 'google.it' }), '<a href="">google.it</a>'); equal(parse('a[href=]', { href: true, text: 'test here' }), '<a href="">test here</a>'); equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>'); }); it('wrap basic', () => { equal(parse('p', { text: 'test' }), '<p>test</p>'); equal(parse('p', { text: ['test'] }), '<p>test</p>'); equal(parse('p', { text: ['test1', 'test2'] }), '<p>test1\ntest2</p>'); equal(parse('p', { text: ['test1', '', 'test2'] }), '<p>test1\n\ntest2</p>'); equal(parse('p*', { text: ['test1', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); equal(parse('p*', { text: ['test1', '', 'test2'] }), '<p*2@0>test1</p><p*2@1>test2</p>'); }) }); <MSG> Fix wrap around anchor elements with classes (#656) <DFF> @@ -21,6 +21,8 @@ describe('Convert token abbreviations', () => { equal(parse('div>p+p{hi}', { text: ['hello'] }), '<div><p></p><p>hihello</p></div>'); equal(parse('html[lang=${lang}]'), '<html lang="lang"></html>'); + equal(parse('html.one.two'), '<html class="one", class="two"></html>'); + equal(parse('html.one[two=three]'), '<html class="one", two="three"></html>'); equal(parse('div{[}+a{}'), '<div>[</div><a></a>'); }); @@ -69,6 +71,10 @@ describe('Convert token abbreviations', () => { equal(parse('a[href=]', { href: true, text: '[email protected]' }), '<a href="mailto:[email protected]">[email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here [email protected]' }), '<a href="">test here [email protected]</a>'); equal(parse('a[href=]', { href: true, text: 'test here www.domain.com' }), '<a href="">test here www.domain.com</a>'); + equal(parse('a[class=here]', { href: true, text: '[email protected]' }), '<a class="here", href="mailto:[email protected]">[email protected]</a>'); + equal(parse('a.here', { href: true, text: 'www.domain.com' }), '<a class="here", href="http://www.domain.com">www.domain.com</a>'); + equal(parse('a[class=here]', { href: true, text: 'test here [email protected]' }), '<a class="here", href="">test here [email protected]</a>'); + equal(parse('a.here', { href: true, text: 'test here www.domain.com' }), '<a class="here", href="">test here www.domain.com</a>'); equal(parse('a[href="www.google.it"]', { href: false, text: 'test' }), '<a href="www.google.it">test</a>'); equal(parse('a[href="www.example.com"]', { href: true, text: 'www.google.it' }), '<a href="www.example.com">www.google.it</a>');
    6
    Fix wrap around anchor elements with classes (#656)
    0
    .ts
    ts
    mit
    emmetio/emmet