{ // 获取包含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 !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO 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 !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; 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, 'PDF TO 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+\n+ expect_html = \"\"\"\n+ \n+ Title\n+ \n+ \n+

Yes!

\n+ \n+ \"\"\"\n+\n+ p = Premailer(html, remove_classes=True)\n+ result_html = p.transform()\n+\n+ compare_html(expect_html, result_html)\n+\n def test_basic_html_shortcut_function(self):\n \"\"\"test the plain transform function\"\"\"\n html = \"\"\"\n@@ -1088,7 +1119,7 @@ b\n \n \n \n-
\n+
\n \n \"\"\"\n \n@@ -1118,7 +1149,7 @@ b\n \n \n \n-
\n+
\n \n \"\"\"\n \n@@ -1148,7 +1179,7 @@ b\n \n \n \n-
\n+
\n \n \"\"\"\n \n@@ -1178,7 +1209,7 @@ b\n \n \n \n-
\n+
\n \n \"\"\"\n \n@@ -1195,7 +1226,7 @@ b\n color: blue !important;\n font-size: 12px;\n }\n- #identified {\n+ #id {\n color: green;\n font-size: 22px;\n }\n@@ -1205,17 +1236,17 @@ b\n \n \n \n-
\n+
\n \n \"\"\"\n \n expect_html = \"\"\"\n- \n- \n- \n-
\n- \n- \"\"\"\n+\n+\n+\n+
\n+\n+\"\"\"\n \n p = Premailer(html)\n result_html = p.transform()\n@@ -1285,7 +1316,7 @@ ration:none\">Yes!

\n Title\n \n \n-

Hi!

\n+

Hi!

\n \n \"\"\"\n \n@@ -2395,7 +2426,7 @@ sheet\" type=\"text/css\">\n \n \n \n-
\n+
\n \n \"\"\"\n \n@@ -2453,22 +2484,22 @@ sheet\" type=\"text/css\">\n \n \n

text\n- text\n+ text\n text\n \n \"\"\"\n \n expect_html = \"\"\"\n- \n- Title\n- \n- \n-

text\n- text\n- text\n-

\n- \n- \"\"\"\n+\n+Title\n+\n+\n+

text\n+ text\n+ text\n+

\n+\n+\"\"\"\n \n p = Premailer(html, align_floating_images=True)\n result_html = p.transform()\n@@ -2498,7 +2529,8 @@ sheet\" type=\"text/css\">\n \n \n \n-
\n+
\n+
\n \n \"\"\"\n \n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"merge_commit\",\n \"failed_lite_validators\": [\n \"has_many_modified_files\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 2,\n \"test_score\": 1\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"unknown"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"nose\",\n \"mock\",\n \"coverage\",\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements/base.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\ncertifi==2021.5.30\ncharset-normalizer==2.0.12\ncoverage==6.2\ncssselect==1.1.0\ncssutils==2.3.1\nidna==3.10\nimportlib-metadata==4.8.3\niniconfig==1.1.1\nlxml==5.3.1\nmock==5.2.0\nnose==1.3.7\npackaging==21.3\npluggy==1.0.0\n-e git+https://github.com/peterbe/premailer.git@cc18022e334d5336e48f75bd4e0a73c98cc5942a#egg=premailer\npy==1.11.0\npyparsing==3.1.4\npytest==7.0.1\nrequests==2.27.1\ntomli==1.2.3\ntyping_extensions==4.1.1\nurllib3==1.26.20\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: premailer\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - charset-normalizer==2.0.12\n - coverage==6.2\n - cssselect==1.1.0\n - cssutils==2.3.1\n - idna==3.10\n - importlib-metadata==4.8.3\n - iniconfig==1.1.1\n - lxml==5.3.1\n - mock==5.2.0\n - nose==1.3.7\n - packaging==21.3\n - pluggy==1.0.0\n - py==1.11.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - requests==2.27.1\n - tomli==1.2.3\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - zipp==3.6.0\nprefix: /opt/conda/envs/premailer\n"},"FAIL_TO_PASS":{"kind":"list like","value":["premailer/tests/test_premailer.py::Tests::test_align_float_images","premailer/tests/test_premailer.py::Tests::test_favour_rule_with_class_over_generic","premailer/tests/test_premailer.py::Tests::test_favour_rule_with_element_over_generic","premailer/tests/test_premailer.py::Tests::test_favour_rule_with_id_over_others","premailer/tests/test_premailer.py::Tests::test_favour_rule_with_important_over_others","premailer/tests/test_premailer.py::Tests::test_prefer_inline_to_class","premailer/tests/test_premailer.py::Tests::test_remove_unset_properties","premailer/tests/test_premailer.py::Tests::test_style_attribute_specificity","premailer/tests/test_premailer.py::Tests::test_turnoff_cache_works_as_expected"],"string":"[\n \"premailer/tests/test_premailer.py::Tests::test_align_float_images\",\n \"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_class_over_generic\",\n \"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_element_over_generic\",\n \"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_id_over_others\",\n \"premailer/tests/test_premailer.py::Tests::test_favour_rule_with_important_over_others\",\n \"premailer/tests/test_premailer.py::Tests::test_prefer_inline_to_class\",\n \"premailer/tests/test_premailer.py::Tests::test_remove_unset_properties\",\n \"premailer/tests/test_premailer.py::Tests::test_style_attribute_specificity\",\n \"premailer/tests/test_premailer.py::Tests::test_turnoff_cache_works_as_expected\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["premailer/tests/test_premailer.py::Tests::test_3_digit_color_expand","premailer/tests/test_premailer.py::Tests::test_apple_newsletter_example","premailer/tests/test_premailer.py::Tests::test_base_url_fixer","premailer/tests/test_premailer.py::Tests::test_base_url_with_path","premailer/tests/test_premailer.py::Tests::test_basic_html","premailer/tests/test_premailer.py::Tests::test_basic_html_shortcut_function","premailer/tests/test_premailer.py::Tests::test_basic_html_with_pseudo_selector","premailer/tests/test_premailer.py::Tests::test_basic_xml","premailer/tests/test_premailer.py::Tests::test_broken_xml","premailer/tests/test_premailer.py::Tests::test_capture_cssutils_logging","premailer/tests/test_premailer.py::Tests::test_child_selector","premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_argument","premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_stdin","premailer/tests/test_premailer.py::Tests::test_command_line_preserve_style_tags","premailer/tests/test_premailer.py::Tests::test_comments_in_media_queries","premailer/tests/test_premailer.py::Tests::test_css_disable_basic_html_attributes","premailer/tests/test_premailer.py::Tests::test_css_disable_leftover_css","premailer/tests/test_premailer.py::Tests::test_css_text","premailer/tests/test_premailer.py::Tests::test_css_text_with_only_body_present","premailer/tests/test_premailer.py::Tests::test_css_with_html_attributes","premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_excluded","premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_included","premailer/tests/test_premailer.py::Tests::test_disabled_validator","premailer/tests/test_premailer.py::Tests::test_doctype","premailer/tests/test_premailer.py::Tests::test_empty_style_tag","premailer/tests/test_premailer.py::Tests::test_external_links","premailer/tests/test_premailer.py::Tests::test_external_links_unfindable","premailer/tests/test_premailer.py::Tests::test_external_styles_and_links","premailer/tests/test_premailer.py::Tests::test_external_styles_on_http","premailer/tests/test_premailer.py::Tests::test_external_styles_on_https","premailer/tests/test_premailer.py::Tests::test_external_styles_with_base_url","premailer/tests/test_premailer.py::Tests::test_fontface_selectors_with_no_selectortext","premailer/tests/test_premailer.py::Tests::test_ignore_some_external_stylesheets","premailer/tests/test_premailer.py::Tests::test_ignore_some_incorrectly","premailer/tests/test_premailer.py::Tests::test_ignore_some_inline_stylesheets","premailer/tests/test_premailer.py::Tests::test_ignore_style_elements_with_media_attribute","premailer/tests/test_premailer.py::Tests::test_include_star_selector","premailer/tests/test_premailer.py::Tests::test_inline_important","premailer/tests/test_premailer.py::Tests::test_inline_wins_over_external","premailer/tests/test_premailer.py::Tests::test_keyframe_selectors","premailer/tests/test_premailer.py::Tests::test_last_child","premailer/tests/test_premailer.py::Tests::test_last_child_exclude_pseudo","premailer/tests/test_premailer.py::Tests::test_leftover_important","premailer/tests/test_premailer.py::Tests::test_links_without_protocol","premailer/tests/test_premailer.py::Tests::test_load_external_url","premailer/tests/test_premailer.py::Tests::test_mailto_url","premailer/tests/test_premailer.py::Tests::test_mediaquery","premailer/tests/test_premailer.py::Tests::test_merge_styles_basic","premailer/tests/test_premailer.py::Tests::test_merge_styles_non_trivial","premailer/tests/test_premailer.py::Tests::test_merge_styles_with_class","premailer/tests/test_premailer.py::Tests::test_merge_styles_with_unset","premailer/tests/test_premailer.py::Tests::test_mixed_pseudo_selectors","premailer/tests/test_premailer.py::Tests::test_multiple_style_elements","premailer/tests/test_premailer.py::Tests::test_multithreading","premailer/tests/test_premailer.py::Tests::test_parse_style_rules","premailer/tests/test_premailer.py::Tests::test_precedence_comparison","premailer/tests/test_premailer.py::Tests::test_remove_classes","premailer/tests/test_premailer.py::Tests::test_shortcut_function","premailer/tests/test_premailer.py::Tests::test_six_color","premailer/tests/test_premailer.py::Tests::test_strip_important","premailer/tests/test_premailer.py::Tests::test_style_block_with_external_urls","premailer/tests/test_premailer.py::Tests::test_type_test","premailer/tests/test_premailer.py::Tests::test_uppercase_margin","premailer/tests/test_premailer.py::Tests::test_xml_cdata"],"string":"[\n \"premailer/tests/test_premailer.py::Tests::test_3_digit_color_expand\",\n \"premailer/tests/test_premailer.py::Tests::test_apple_newsletter_example\",\n \"premailer/tests/test_premailer.py::Tests::test_base_url_fixer\",\n \"premailer/tests/test_premailer.py::Tests::test_base_url_with_path\",\n \"premailer/tests/test_premailer.py::Tests::test_basic_html\",\n \"premailer/tests/test_premailer.py::Tests::test_basic_html_shortcut_function\",\n \"premailer/tests/test_premailer.py::Tests::test_basic_html_with_pseudo_selector\",\n \"premailer/tests/test_premailer.py::Tests::test_basic_xml\",\n \"premailer/tests/test_premailer.py::Tests::test_broken_xml\",\n \"premailer/tests/test_premailer.py::Tests::test_capture_cssutils_logging\",\n \"premailer/tests/test_premailer.py::Tests::test_child_selector\",\n \"premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_argument\",\n \"premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_stdin\",\n \"premailer/tests/test_premailer.py::Tests::test_command_line_preserve_style_tags\",\n \"premailer/tests/test_premailer.py::Tests::test_comments_in_media_queries\",\n \"premailer/tests/test_premailer.py::Tests::test_css_disable_basic_html_attributes\",\n \"premailer/tests/test_premailer.py::Tests::test_css_disable_leftover_css\",\n \"premailer/tests/test_premailer.py::Tests::test_css_text\",\n \"premailer/tests/test_premailer.py::Tests::test_css_text_with_only_body_present\",\n \"premailer/tests/test_premailer.py::Tests::test_css_with_html_attributes\",\n \"premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_excluded\",\n \"premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_included\",\n \"premailer/tests/test_premailer.py::Tests::test_disabled_validator\",\n \"premailer/tests/test_premailer.py::Tests::test_doctype\",\n \"premailer/tests/test_premailer.py::Tests::test_empty_style_tag\",\n \"premailer/tests/test_premailer.py::Tests::test_external_links\",\n \"premailer/tests/test_premailer.py::Tests::test_external_links_unfindable\",\n \"premailer/tests/test_premailer.py::Tests::test_external_styles_and_links\",\n \"premailer/tests/test_premailer.py::Tests::test_external_styles_on_http\",\n \"premailer/tests/test_premailer.py::Tests::test_external_styles_on_https\",\n \"premailer/tests/test_premailer.py::Tests::test_external_styles_with_base_url\",\n \"premailer/tests/test_premailer.py::Tests::test_fontface_selectors_with_no_selectortext\",\n \"premailer/tests/test_premailer.py::Tests::test_ignore_some_external_stylesheets\",\n \"premailer/tests/test_premailer.py::Tests::test_ignore_some_incorrectly\",\n \"premailer/tests/test_premailer.py::Tests::test_ignore_some_inline_stylesheets\",\n \"premailer/tests/test_premailer.py::Tests::test_ignore_style_elements_with_media_attribute\",\n \"premailer/tests/test_premailer.py::Tests::test_include_star_selector\",\n \"premailer/tests/test_premailer.py::Tests::test_inline_important\",\n \"premailer/tests/test_premailer.py::Tests::test_inline_wins_over_external\",\n \"premailer/tests/test_premailer.py::Tests::test_keyframe_selectors\",\n \"premailer/tests/test_premailer.py::Tests::test_last_child\",\n \"premailer/tests/test_premailer.py::Tests::test_last_child_exclude_pseudo\",\n \"premailer/tests/test_premailer.py::Tests::test_leftover_important\",\n \"premailer/tests/test_premailer.py::Tests::test_links_without_protocol\",\n \"premailer/tests/test_premailer.py::Tests::test_load_external_url\",\n \"premailer/tests/test_premailer.py::Tests::test_mailto_url\",\n \"premailer/tests/test_premailer.py::Tests::test_mediaquery\",\n \"premailer/tests/test_premailer.py::Tests::test_merge_styles_basic\",\n \"premailer/tests/test_premailer.py::Tests::test_merge_styles_non_trivial\",\n \"premailer/tests/test_premailer.py::Tests::test_merge_styles_with_class\",\n \"premailer/tests/test_premailer.py::Tests::test_merge_styles_with_unset\",\n \"premailer/tests/test_premailer.py::Tests::test_mixed_pseudo_selectors\",\n \"premailer/tests/test_premailer.py::Tests::test_multiple_style_elements\",\n \"premailer/tests/test_premailer.py::Tests::test_multithreading\",\n \"premailer/tests/test_premailer.py::Tests::test_parse_style_rules\",\n \"premailer/tests/test_premailer.py::Tests::test_precedence_comparison\",\n \"premailer/tests/test_premailer.py::Tests::test_remove_classes\",\n \"premailer/tests/test_premailer.py::Tests::test_shortcut_function\",\n \"premailer/tests/test_premailer.py::Tests::test_six_color\",\n \"premailer/tests/test_premailer.py::Tests::test_strip_important\",\n \"premailer/tests/test_premailer.py::Tests::test_style_block_with_external_urls\",\n \"premailer/tests/test_premailer.py::Tests::test_type_test\",\n \"premailer/tests/test_premailer.py::Tests::test_uppercase_margin\",\n \"premailer/tests/test_premailer.py::Tests::test_xml_cdata\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD 3-Clause \"New\" or \"Revised\" License"},"__index_level_0__":{"kind":"number","value":575,"string":"575"}}},{"rowIdx":575,"cells":{"instance_id":{"kind":"string","value":"kytos__python-openflow-56"},"base_commit":{"kind":"string","value":"275103dca4116b8911dc19ddad4b90121936d9f1"},"created_at":{"kind":"string","value":"2016-06-07 17:59:27"},"environment_setup_commit":{"kind":"string","value":"275103dca4116b8911dc19ddad4b90121936d9f1"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/pyof/v0x01/common/flow_match.py b/pyof/v0x01/common/flow_match.py\nindex a900b81..07d103e 100644\n--- a/pyof/v0x01/common/flow_match.py\n+++ b/pyof/v0x01/common/flow_match.py\n@@ -1,6 +1,7 @@\n \"\"\"Defines flow statistics structures and related items\"\"\"\n \n # System imports\n+import enum\n \n # Third-party imports\n \n@@ -8,7 +9,10 @@\n from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n-class FlowWildCards(base.GenericBitMask):\n+# Enums\n+\n+\n+class FlowWildCards(enum.Enum):\n \"\"\"\n Wildcards used to identify flows.\n \ndiff --git a/pyof/v0x01/common/phy_port.py b/pyof/v0x01/common/phy_port.py\nindex 7395fb6..b45777f 100644\n--- a/pyof/v0x01/common/phy_port.py\n+++ b/pyof/v0x01/common/phy_port.py\n@@ -1,6 +1,7 @@\n \"\"\"Defines physical port classes and related items\"\"\"\n \n # System imports\n+import enum\n \n # Third-party imports\n \n@@ -8,20 +9,9 @@\n from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n+# Enums\n+\n class PortConfig(base.GenericBitMask):\n- \"\"\"Flags to indicate behavior of the physical port.\n-\n- These flags are used in OFPPhyPort to describe the current configuration.\n- They are used in the OFPPortMod message to configure the port's behavior.\n-\n- OFPPC_PORT_DOWN # Port is administratively down.\n- OFPPC_NO_STP # Disable 802.1D spanning tree on port.\n- OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree.\n- OFPPC_NO_RECV_STP # Drop received 802.1D STP packets.\n- OFPPC_NO_FLOOD # Do not include this port when flooding.\n- OFPPC_NO_FWD # Drop packets forwarded to port.\n- OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port.\n- \"\"\"\n OFPC_PORT_DOWN = 1 << 0\n OFPPC_NO_STP = 1 << 1\n OFPPC_NO_RECV = 1 << 2\n@@ -31,9 +21,32 @@ class PortConfig(base.GenericBitMask):\n OFPPC_NO_PACKET_IN = 1 << 6\n \n \n-\n-\n-class PortState(base.GenericBitMask):\n+#class PortConfig(enum.Enum):\n+# \"\"\"Flags to indicate behavior of the physical port.\n+#\n+# These flags are used in OFPPhyPort to describe the current configuration.\n+# They are used in the OFPPortMod message to configure the port's behavior.\n+#\n+# Enums:\n+# OFPPC_PORT_DOWN # Port is administratively down.\n+# OFPPC_NO_STP # Disable 802.1D spanning tree on port.\n+# OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree.\n+# OFPPC_NO_RECV_STP # Drop received 802.1D STP packets.\n+# OFPPC_NO_FLOOD # Do not include this port when flooding.\n+# OFPPC_NO_FWD # Drop packets forwarded to port.\n+# OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port.\n+# \"\"\"\n+#\n+# OFPPC_PORT_DOWN = 1 << 0\n+# OFPPC_NO_STP = 1 << 1\n+# OFPPC_NO_RECV = 1 << 2\n+# OFPPC_NO_RECV_STP = 1 << 3\n+# OFPPC_FLOOD = 1 << 4\n+# OFPPC_NO_FWD = 1 << 5\n+# OFPPC_NO_PACKET_IN = 1 << 6\n+\n+\n+class PortState(enum.Enum):\n \"\"\"Current state of the physical port.\n \n These are not configurable from the controller.\n@@ -42,6 +55,7 @@ class PortState(base.GenericBitMask):\n must adjust OFPPC_NO_RECV, OFPPC_NO_FWD, and OFPPC_NO_PACKET_IN\n appropriately to fully implement an 802.1D spanning tree.\n \n+ Enums:\n OFPPS_LINK_DOWN # Not learning or relaying frames.\n OFPPS_STP_LISTEN # Not learning or relaying frames.\n OFPPS_STP_LEARN # Learning but not relaying frames.\n@@ -58,7 +72,7 @@ class PortState(base.GenericBitMask):\n # OFPPS_STP_MASK = 3 << 8 - Refer to ISSUE #7\n \n \n-class Port(base.GenericBitMask):\n+class Port(enum.Enum):\n \"\"\"Port numbering.\n \n Physical ports are numbered starting from 1. Port number 0 is reserved by\n@@ -87,13 +101,14 @@ class Port(base.GenericBitMask):\n OFPP_NONE = 0xffff\n \n \n-class PortFeatures(base.GenericBitMask):\n+class PortFeatures(enum.Enum):\n \"\"\"Physical ports features.\n \n The curr, advertised, supported, and peer fields indicate link modes\n (10M to 10G full and half-duplex), link type (copper/fiber) and\n link features (autone-gotiation and pause).\n \n+ Enums:\n OFPPF_10MB_HD # 10 Mb half-duplex rate support.\n OFPPF_10MB_FD # 10 Mb full-duplex rate support.\n OFPPF_100MB_HD # 100 Mb half-duplex rate support.\ndiff --git a/pyof/v0x01/controller2switch/aggregate_stats_reply.py b/pyof/v0x01/controller2switch/aggregate_stats_reply.py\ndeleted file mode 100644\nindex 339127c..0000000\n--- a/pyof/v0x01/controller2switch/aggregate_stats_reply.py\n+++ /dev/null\n@@ -1,31 +0,0 @@\n-\"\"\"Body of the reply message\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-# Classes\n-\n-\n-class AggregateStatsReply(base.GenericStruct):\n- \"\"\"Body of reply to OFPST_AGGREGATE request.\n-\n- :param packet_count: Number of packets in flows\n- :param byte_count: Number of bytes in flows\n- :param flow_count: Number of flows\n- :param pad: Align to 64 bits\n-\n- \"\"\"\n- packet_count = basic_types.UBInt64()\n- byte_count = basic_types.UBInt64()\n- flow_count = basic_types.UBInt32()\n- pad = basic_types.PAD(4)\n-\n- def __init__(self, packet_count=None, byte_count=None, flow_count=None):\n- self.packet_count = packet_count\n- self.byte_count = byte_count\n- self.flow_count = flow_count\ndiff --git a/pyof/v0x01/controller2switch/aggregate_stats_request.py b/pyof/v0x01/controller2switch/aggregate_stats_request.py\ndeleted file mode 100644\nindex b45f923..0000000\n--- a/pyof/v0x01/controller2switch/aggregate_stats_request.py\n+++ /dev/null\n@@ -1,38 +0,0 @@\n-\"\"\"Aggregate information about multiple flows is requested with the\n-OFPST_AGGREGATE stats request type\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.common import flow_match\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-# Classes\n-\n-\n-class AggregateStatsRequest(base.GenericStruct):\n- \"\"\"\n- Body for ofp_stats_request of type OFPST_AGGREGATE.\n-\n- :param match: Fields to match\n- :param table_id: ID of table to read (from pyof_table_stats) 0xff\n- for all tables or 0xfe for emergency.\n- :param pad: Align to 32 bits\n- :param out_port: Require matching entries to include this as an\n- output port. A value of OFPP_NONE indicates\n- no restriction\n-\n- \"\"\"\n- match = flow_match.Match()\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(1)\n- out_port = basic_types.UBInt16()\n-\n- def __init__(self, match=None, table_id=None, out_port=None):\n- super().__init__()\n- self.match = match\n- self.table_id = table_id\n- self.out_port = out_port\ndiff --git a/pyof/v0x01/controller2switch/common.py b/pyof/v0x01/controller2switch/common.py\nindex c5490dd..bfb9cd3 100644\n--- a/pyof/v0x01/controller2switch/common.py\n+++ b/pyof/v0x01/controller2switch/common.py\n@@ -8,6 +8,7 @@ import enum\n # Local source tree imports\n from pyof.v0x01.common import header as of_header\n from pyof.v0x01.common import action\n+from pyof.v0x01.common import flow_match\n from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n@@ -65,3 +66,313 @@ class ListOfActions(basic_types.FixedTypeList):\n \"\"\"\n def __init__(self, items=None):\n super().__init__(pyof_class=action.ActionHeader, items=items)\n+\n+\n+class AggregateStatsReply(base.GenericStruct):\n+ \"\"\"Body of reply to OFPST_AGGREGATE request.\n+\n+ :param packet_count: Number of packets in flows\n+ :param byte_count: Number of bytes in flows\n+ :param flow_count: Number of flows\n+ :param pad: Align to 64 bits\n+\n+ \"\"\"\n+ packet_count = basic_types.UBInt64()\n+ byte_count = basic_types.UBInt64()\n+ flow_count = basic_types.UBInt32()\n+ pad = basic_types.PAD(4)\n+\n+ def __init__(self, packet_count=None, byte_count=None, flow_count=None):\n+ self.packet_count = packet_count\n+ self.byte_count = byte_count\n+ self.flow_count = flow_count\n+\n+\n+class AggregateStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Body for ofp_stats_request of type OFPST_AGGREGATE.\n+\n+ :param match: Fields to match\n+ :param table_id: ID of table to read (from pyof_table_stats) 0xff\n+ for all tables or 0xfe for emergency.\n+ :param pad: Align to 32 bits\n+ :param out_port: Require matching entries to include this as an\n+ output port. A value of OFPP_NONE indicates\n+ no restriction\n+\n+ \"\"\"\n+ match = flow_match.Match()\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(1)\n+ out_port = basic_types.UBInt16()\n+\n+ def __init__(self, match=None, table_id=None, out_port=None):\n+ super().__init__()\n+ self.match = match\n+ self.table_id = table_id\n+ self.out_port = out_port\n+\n+\n+class DescStats(base.GenericStruct):\n+ \"\"\"\n+ Information about the switch manufacturer, hardware revision, software\n+ revision, serial number, and a description field is avail- able from\n+ the OFPST_DESC stats request.\n+\n+ :param mfr_desc: Manufacturer description\n+ :param hw_desc: Hardware description\n+ :param sw_desc: Software description\n+ :param serial_num: Serial number\n+ :param dp_desc: Human readable description of datapath\n+\n+ \"\"\"\n+ mfr_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+ hw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+ sw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+ serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN)\n+ dp_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+\n+ def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None,\n+ serial_num=None, dp_desc=None):\n+ self.mfr_desc = mfr_desc\n+ self.hw_desc = hw_desc\n+ self.sw_desc = sw_desc\n+ self.serial_num = serial_num\n+ self.dp_desc = dp_desc\n+\n+\n+class FlowStats(base.GenericStruct):\n+ \"\"\"\n+ Body of reply to OFPST_FLOW request.\n+\n+ :param length: Length of this entry\n+ :param table_id: ID of table flow came from\n+ :param pad: Align to 32 bits\n+ :param match: Description of fields\n+ :param duration_sec: Time flow has been alive in seconds\n+ :param duration_nsec: Time flow has been alive in nanoseconds beyond\n+ duration_sec\n+ :param priority: Priority of the entry. Only meaningful when this\n+ is not an exact-match entry\n+ :param idle_timeout: Number of seconds idle before expiration\n+ :param hard_timeout: Number of seconds before expiration\n+ :param pad2: Align to 64-bits\n+ :param cookie: Opaque controller-issued identifier\n+ :param packet_count: Number of packets in flow\n+ :param byte_count: Number of bytes in flow\n+ :param actions: Actions\n+ \"\"\"\n+ length = basic_types.UBInt16()\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(1)\n+ match = flow_match.Match()\n+ duration_sec = basic_types.UBInt32()\n+ duration_nsec = basic_types.UBInt32()\n+ priority = basic_types.UBInt16()\n+ idle_timeout = basic_types.UBInt16()\n+ hard_timeout = basic_types.UBInt16()\n+ pad2 = basic_types.PAD(6)\n+ cookie = basic_types.UBInt64()\n+ packet_count = basic_types.UBInt64()\n+ byte_count = basic_types.UBInt64()\n+ actions = ListOfActions()\n+\n+ def __init__(self, length=None, table_id=None, match=None,\n+ duration_sec=None, duration_nsec=None, priority=None,\n+ idle_timeout=None, hard_timeout=None, cookie=None,\n+ packet_count=None, byte_count=None, actions=None):\n+ self.length = length\n+ self.table_id = table_id\n+ self.match = match\n+ self.duration_sec = duration_sec\n+ self.duration_nsec = duration_nsec\n+ self.prioriry = priority\n+ self.idle_timeout = idle_timeout\n+ self.hard_timeout = hard_timeout\n+ self.cookie = cookie\n+ self.packet_count = packet_count\n+ self.byte_count = byte_count\n+ self.actions = [] if actions is None else actions\n+\n+\n+class FlowStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Body for ofp_stats_request of type OFPST_FLOW.\n+\n+ :param match: Fields to match\n+ :param table_id: ID of table to read (from pyof_table_stats)\n+ 0xff for all tables or 0xfe for emergency\n+ :param pad: Align to 32 bits\n+ :param out_port: Require matching entries to include this as an output\n+ port. A value of OFPP_NONE indicates no restriction.\n+\n+ \"\"\"\n+ match = flow_match.Match()\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(1)\n+ out_port = basic_types.UBInt16()\n+\n+ def __init__(self, match=None, table_id=None, out_port=None):\n+ self.match = match\n+ self.table_id = table_id\n+ self.out_port = out_port\n+\n+\n+class PortStats(base.GenericStruct):\n+ \"\"\"Body of reply to OFPST_PORT request.\n+\n+ If a counter is unsupported, set the field to all ones.\n+\n+ :param port_no: Port number\n+ :param pad: Align to 64-bits\n+ :param rx_packets: Number of received packets\n+ :param tx_packets: Number of transmitted packets\n+ :param rx_bytes: Number of received bytes\n+ :param tx_bytes: Number of transmitted bytes\n+ :param rx_dropped: Number of packets dropped by RX\n+ :param tx_dropped: Number of packets dropped by TX\n+ :param rx_errors: Number of receive errors. This is a super-set\n+ of more specific receive errors and should be\n+ greater than or equal to the sum of all\n+ rx_*_err values\n+ :param tx_errors: Number of transmit errors. This is a super-set\n+ of more specific transmit errors and should be\n+ greater than or equal to the sum of all\n+ tx_*_err values (none currently defined.)\n+ :param rx_frame_err: Number of frame alignment errors\n+ :param rx_over_err: Number of packets with RX overrun\n+ :param rx_crc_err: Number of CRC errors\n+ :param collisions: Number of collisions\n+\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(6)\n+ rx_packets = basic_types.UBInt64()\n+ tx_packets = basic_types.UBInt64()\n+ rx_bytes = basic_types.UBInt64()\n+ tx_bytes = basic_types.UBInt64()\n+ rx_dropped = basic_types.UBInt64()\n+ tx_dropped = basic_types.UBInt64()\n+ rx_errors = basic_types.UBInt64()\n+ tx_errors = basic_types.UBInt64()\n+ rx_frame_err = basic_types.UBInt64()\n+ rx_over_err = basic_types.UBInt64()\n+ rx_crc_err = basic_types.UBInt64()\n+ collisions = basic_types.UBInt64()\n+\n+ def __init__(self, port_no=None, rx_packets=None,\n+ tx_packets=None, rx_bytes=None, tx_bytes=None,\n+ rx_dropped=None, tx_dropped=None, rx_errors=None,\n+ tx_errors=None, rx_frame_err=None, rx_over_err=None,\n+ rx_crc_err=None, collisions=None):\n+ self.port_no = port_no\n+ self.rx_packets = rx_packets\n+ self.tx_packets = tx_packets\n+ self.rx_bytes = rx_bytes\n+ self.tx_bytes = tx_bytes\n+ self.rx_dropped = rx_dropped\n+ self.tx_dropped = tx_dropped\n+ self.rx_errors = rx_errors\n+ self.tx_errors = tx_errors\n+ self.rx_frame_err = rx_frame_err\n+ self.rx_over_err = rx_over_err\n+ self.rx_crc_err = rx_crc_err\n+ self.collisions = collisions\n+\n+\n+class PortStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Body for ofp_stats_request of type OFPST_PORT\n+\n+ :param port_no: OFPST_PORT message must request statistics either\n+ for a single port (specified in port_no) or for\n+ all ports (if port_no == OFPP_NONE).\n+ :param pad:\n+\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(6)\n+\n+ def __init__(self, port_no=None):\n+ self.port_no = port_no\n+\n+\n+class QueueStats(base.GenericStruct):\n+ \"\"\"\n+ Implements the reply body of a port_no\n+\n+ :param port_no: Port Number\n+ :param pad: Align to 32-bits\n+ :param queue_id: Queue ID\n+ :param tx_bytes: Number of transmitted bytes\n+ :param tx_packets: Number of transmitted packets\n+ :param tx_errors: Number of packets dropped due to overrun\n+\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(2)\n+ queue_id = basic_types.UBInt32()\n+ tx_bytes = basic_types.UBInt64()\n+ tx_packets = basic_types.UBInt64()\n+ tx_errors = basic_types.UBInt64()\n+\n+ def __init__(self, port_no=None, queue_id=None, tx_bytes=None,\n+ tx_packets=None, tx_errors=None):\n+ self.port_no = port_no\n+ self.queue_id = queue_id\n+ self.tx_bytes = tx_bytes\n+ self.tx_packets = tx_packets\n+ self.tx_errors = tx_errors\n+\n+\n+class QueueStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Implements the request body of a port_no\n+\n+ :param port_no: All ports if OFPT_ALL\n+ :param pad: Align to 32-bits\n+ :param queue_id: All queues if OFPQ_ALL\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(2)\n+ queue_id = basic_types.UBInt32()\n+\n+ def __init__(self, port_no=None, queue_id=None):\n+ self.port_no = port_no\n+ self.queue_id = queue_id\n+\n+\n+class TableStats(base.GenericStruct):\n+ \"\"\"Body of reply to OFPST_TABLE request.\n+\n+ :param table_id: Identifier of table. Lower numbered tables\n+ are consulted first\n+ :param pad: Align to 32-bits\n+ :param name: Table name\n+ :param wildcards: Bitmap of OFPFW_* wildcards that are supported\n+ by the table\n+ :param max_entries: Max number of entries supported\n+ :param active_count: Number of active entries\n+ :param count_lookup: Number of packets looked up in table\n+ :param count_matched: Number of packets that hit table\n+\n+ \"\"\"\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(3)\n+ name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN)\n+ wildcards = basic_types.UBInt32()\n+ max_entries = basic_types.UBInt32()\n+ active_count = basic_types.UBInt32()\n+ count_lookup = basic_types.UBInt64()\n+ count_matched = basic_types.UBInt64()\n+\n+ def __init__(self, table_id=None, name=None, wildcards=None,\n+ max_entries=None, active_count=None, count_lookup=None,\n+ count_matched=None):\n+ self.table_id = table_id\n+ self.name = name\n+ self.wildcards = wildcards\n+ self.max_entries = max_entries\n+ self.active_count = active_count\n+ self.count_lookup = count_lookup\n+ self.count_matched = count_matched\ndiff --git a/pyof/v0x01/controller2switch/desc_stats.py b/pyof/v0x01/controller2switch/desc_stats.py\ndeleted file mode 100644\nindex bceffb9..0000000\n--- a/pyof/v0x01/controller2switch/desc_stats.py\n+++ /dev/null\n@@ -1,39 +0,0 @@\n-\"\"\"Information about the switch manufactures\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-# Classes\n-\n-\n-class DescStats(base.GenericStruct):\n- \"\"\"\n- Information about the switch manufacturer, hardware revision, software\n- revision, serial number, and a description field is avail- able from\n- the OFPST_DESC stats request.\n-\n- :param mfr_desc: Manufacturer description\n- :param hw_desc: Hardware description\n- :param sw_desc: Software description\n- :param serial_num: Serial number\n- :param dp_desc: Human readable description of datapath\n-\n- \"\"\"\n- mfr_desc = basic_types.Char(length=base.DESC_STR_LEN)\n- hw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n- sw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n- serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN)\n- dp_desc = basic_types.Char(length=base.DESC_STR_LEN)\n-\n- def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None,\n- serial_num=None, dp_desc=None):\n- self.mfr_desc = mfr_desc\n- self.hw_desc = hw_desc\n- self.sw_desc = sw_desc\n- self.serial_num = serial_num\n- self.dp_desc = dp_desc\ndiff --git a/pyof/v0x01/controller2switch/features_reply.py b/pyof/v0x01/controller2switch/features_reply.py\nindex c5f3bca..e02f012 100644\n--- a/pyof/v0x01/controller2switch/features_reply.py\n+++ b/pyof/v0x01/controller2switch/features_reply.py\n@@ -1,6 +1,7 @@\n \"\"\"Defines Features Reply classes and related items\"\"\"\n \n # System imports\n+import enum\n \n # Third-party imports\n \n@@ -11,9 +12,13 @@ from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n \n-class Capabilities(base.GenericBitMask):\n- \"\"\"Capabilities supported by the datapath\n+# Enums\n \n+\n+class Capabilities(enum.Enum):\n+ \"\"\"Enumeration of Capabilities supported by the datapath\n+\n+ Enums:\n OFPC_FLOW_STATS # Flow statistics\n OFPC_TABLE_STATS # Table statistics\n OFPC_PORT_STATS # Port statistics\ndiff --git a/pyof/v0x01/controller2switch/flow_stats.py b/pyof/v0x01/controller2switch/flow_stats.py\ndeleted file mode 100644\nindex efb5edd..0000000\n--- a/pyof/v0x01/controller2switch/flow_stats.py\n+++ /dev/null\n@@ -1,67 +0,0 @@\n-\"\"\"Body of the reply to an OFPST_FLOW\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.common import flow_match\n-from pyof.v0x01.controller2switch import common\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-# Classes\n-\n-\n-class FlowStats(base.GenericStruct):\n- \"\"\"\n- Body of reply to OFPST_FLOW request.\n-\n- :param length: Length of this entry\n- :param table_id: ID of table flow came from\n- :param pad: Align to 32 bits\n- :param match: Description of fields\n- :param duration_sec: Time flow has been alive in seconds\n- :param duration_nsec: Time flow has been alive in nanoseconds beyond\n- duration_sec\n- :param priority: Priority of the entry. Only meaningful when this\n- is not an exact-match entry\n- :param idle_timeout: Number of seconds idle before expiration\n- :param hard_timeout: Number of seconds before expiration\n- :param pad2: Align to 64-bits\n- :param cookie: Opaque controller-issued identifier\n- :param packet_count: Number of packets in flow\n- :param byte_count: Number of bytes in flow\n- :param actions: Actions\n- \"\"\"\n- length = basic_types.UBInt16()\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(1)\n- match = flow_match.Match()\n- duration_sec = basic_types.UBInt32()\n- duration_nsec = basic_types.UBInt32()\n- priority = basic_types.UBInt16()\n- idle_timeout = basic_types.UBInt16()\n- hard_timeout = basic_types.UBInt16()\n- pad2 = basic_types.PAD(6)\n- cookie = basic_types.UBInt64()\n- packet_count = basic_types.UBInt64()\n- byte_count = basic_types.UBInt64()\n- actions = common.ListOfActions()\n-\n- def __init__(self, length=None, table_id=None, match=None,\n- duration_sec=None, duration_nsec=None, priority=None,\n- idle_timeout=None, hard_timeout=None, cookie=None,\n- packet_count=None, byte_count=None, actions=None):\n- self.length = length\n- self.table_id = table_id\n- self.match = match\n- self.duration_sec = duration_sec\n- self.duration_nsec = duration_nsec\n- self.prioriry = priority\n- self.idle_timeout = idle_timeout\n- self.hard_timeout = hard_timeout\n- self.cookie = cookie\n- self.packet_count = packet_count\n- self.byte_count = byte_count\n- self.actions = [] if actions is None else actions\ndiff --git a/pyof/v0x01/controller2switch/flow_stats_request.py b/pyof/v0x01/controller2switch/flow_stats_request.py\ndeleted file mode 100644\nindex 1fc5794..0000000\n--- a/pyof/v0x01/controller2switch/flow_stats_request.py\n+++ /dev/null\n@@ -1,35 +0,0 @@\n-\"\"\"Information about individual flows\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.common import flow_match\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-# Classes\n-\n-\n-class FlowStatsRequest(base.GenericStruct):\n- \"\"\"\n- Body for ofp_stats_request of type OFPST_FLOW.\n-\n- :param match: Fields to match\n- :param table_id: ID of table to read (from pyof_table_stats)\n- 0xff for all tables or 0xfe for emergency\n- :param pad: Align to 32 bits\n- :param out_port: Require matching entries to include this as an output\n- port. A value of OFPP_NONE indicates no restriction.\n-\n- \"\"\"\n- match = flow_match.Match()\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(1)\n- out_port = basic_types.UBInt16()\n-\n- def __init__(self, match=None, table_id=None, out_port=None):\n- self.match = match\n- self.table_id = table_id\n- self.out_port = out_port\ndiff --git a/pyof/v0x01/controller2switch/port_stats.py b/pyof/v0x01/controller2switch/port_stats.py\ndeleted file mode 100644\nindex 474828d..0000000\n--- a/pyof/v0x01/controller2switch/port_stats.py\n+++ /dev/null\n@@ -1,73 +0,0 @@\n-\"\"\"Body of the port stats reply\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-# Classes\n-\n-\n-class PortStats(base.GenericStruct):\n- \"\"\"Body of reply to OFPST_PORT request.\n-\n- If a counter is unsupported, set the field to all ones.\n-\n- :param port_no: Port number\n- :param pad: Align to 64-bits\n- :param rx_packets: Number of received packets\n- :param tx_packets: Number of transmitted packets\n- :param rx_bytes: Number of received bytes\n- :param tx_bytes: Number of transmitted bytes\n- :param rx_dropped: Number of packets dropped by RX\n- :param tx_dropped: Number of packets dropped by TX\n- :param rx_errors: Number of receive errors. This is a super-set\n- of more specific receive errors and should be\n- greater than or equal to the sum of all\n- rx_*_err values\n- :param tx_errors: Number of transmit errors. This is a super-set\n- of more specific transmit errors and should be\n- greater than or equal to the sum of all\n- tx_*_err values (none currently defined.)\n- :param rx_frame_err: Number of frame alignment errors\n- :param rx_over_err: Number of packets with RX overrun\n- :param rx_crc_err: Number of CRC errors\n- :param collisions: Number of collisions\n-\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(6)\n- rx_packets = basic_types.UBInt64()\n- tx_packets = basic_types.UBInt64()\n- rx_bytes = basic_types.UBInt64()\n- tx_bytes = basic_types.UBInt64()\n- rx_dropped = basic_types.UBInt64()\n- tx_dropped = basic_types.UBInt64()\n- rx_errors = basic_types.UBInt64()\n- tx_errors = basic_types.UBInt64()\n- rx_frame_err = basic_types.UBInt64()\n- rx_over_err = basic_types.UBInt64()\n- rx_crc_err = basic_types.UBInt64()\n- collisions = basic_types.UBInt64()\n-\n- def __init__(self, port_no=None, rx_packets=None,\n- tx_packets=None, rx_bytes=None, tx_bytes=None,\n- rx_dropped=None, tx_dropped=None, rx_errors=None,\n- tx_errors=None, rx_frame_err=None, rx_over_err=None,\n- rx_crc_err=None, collisions=None):\n- self.port_no = port_no\n- self.rx_packets = rx_packets\n- self.tx_packets = tx_packets\n- self.rx_bytes = rx_bytes\n- self.tx_bytes = tx_bytes\n- self.rx_dropped = rx_dropped\n- self.tx_dropped = tx_dropped\n- self.rx_errors = rx_errors\n- self.tx_errors = tx_errors\n- self.rx_frame_err = rx_frame_err\n- self.rx_over_err = rx_over_err\n- self.rx_crc_err = rx_crc_err\n- self.collisions = collisions\ndiff --git a/pyof/v0x01/controller2switch/port_stats_request.py b/pyof/v0x01/controller2switch/port_stats_request.py\ndeleted file mode 100644\nindex 8fa4049..0000000\n--- a/pyof/v0x01/controller2switch/port_stats_request.py\n+++ /dev/null\n@@ -1,26 +0,0 @@\n-\"\"\"Information about physical ports is requested with OFPST_PORT\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-\n-class PortStatsRequest(base.GenericStruct):\n- \"\"\"\n- Body for ofp_stats_request of type OFPST_PORT\n-\n- :param port_no: OFPST_PORT message must request statistics either\n- for a single port (specified in port_no) or for\n- all ports (if port_no == OFPP_NONE).\n- :param pad:\n-\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(6)\n-\n- def __init__(self, port_no=None):\n- self.port_no = port_no\ndiff --git a/pyof/v0x01/controller2switch/queue_stats.py b/pyof/v0x01/controller2switch/queue_stats.py\ndeleted file mode 100644\nindex d7df9b3..0000000\n--- a/pyof/v0x01/controller2switch/queue_stats.py\n+++ /dev/null\n@@ -1,38 +0,0 @@\n-\"\"\"The OFPST_QUEUE stats reply message provides queue statistics for one\n-or more ports.\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-\n-class QueueStats(base.GenericStruct):\n- \"\"\"\n- Implements the reply body of a port_no\n-\n- :param port_no: Port Number\n- :param pad: Align to 32-bits\n- :param queue_id: Queue ID\n- :param tx_bytes: Number of transmitted bytes\n- :param tx_packets: Number of transmitted packets\n- :param tx_errors: Number of packets dropped due to overrun\n-\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(2)\n- queue_id = basic_types.UBInt32()\n- tx_bytes = basic_types.UBInt64()\n- tx_packets = basic_types.UBInt64()\n- tx_errors = basic_types.UBInt64()\n-\n- def __init__(self, port_no=None, queue_id=None, tx_bytes=None,\n- tx_packets=None, tx_errors=None):\n- self.port_no = port_no\n- self.queue_id = queue_id\n- self.tx_bytes = tx_bytes\n- self.tx_packets = tx_packets\n- self.tx_errors = tx_errors\ndiff --git a/pyof/v0x01/controller2switch/queue_stats_request.py b/pyof/v0x01/controller2switch/queue_stats_request.py\ndeleted file mode 100644\nindex c1b431b..0000000\n--- a/pyof/v0x01/controller2switch/queue_stats_request.py\n+++ /dev/null\n@@ -1,27 +0,0 @@\n-\"\"\"The OFPST_QUEUE stats request message provides queue statistics for one\n-or more ports.\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-\n-class QueueStatsRequest(base.GenericStruct):\n- \"\"\"\n- Implements the request body of a port_no\n-\n- :param port_no: All ports if OFPT_ALL\n- :param pad: Align to 32-bits\n- :param queue_id: All queues if OFPQ_ALL\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(2)\n- queue_id = basic_types.UBInt32()\n-\n- def __init__(self, port_no=None, queue_id=None):\n- self.port_no = port_no\n- self.queue_id = queue_id\ndiff --git a/pyof/v0x01/controller2switch/table_stats.py b/pyof/v0x01/controller2switch/table_stats.py\ndeleted file mode 100644\nindex bf2e42f..0000000\n--- a/pyof/v0x01/controller2switch/table_stats.py\n+++ /dev/null\n@@ -1,45 +0,0 @@\n-\"\"\"Information about tables is requested with OFPST_TABLE stats request type\"\"\"\n-\n-# System imports\n-\n-# Third-party imports\n-\n-# Local source tree imports\n-from pyof.v0x01.foundation import base\n-from pyof.v0x01.foundation import basic_types\n-\n-\n-class TableStats(base.GenericStruct):\n- \"\"\"Body of reply to OFPST_TABLE request.\n-\n- :param table_id: Identifier of table. Lower numbered tables\n- are consulted first\n- :param pad: Align to 32-bits\n- :param name: Table name\n- :param wildcards: Bitmap of OFPFW_* wildcards that are supported\n- by the table\n- :param max_entries: Max number of entries supported\n- :param active_count: Number of active entries\n- :param count_lookup: Number of packets looked up in table\n- :param count_matched: Number of packets that hit table\n-\n- \"\"\"\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(3)\n- name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN)\n- wildcards = basic_types.UBInt32()\n- max_entries = basic_types.UBInt32()\n- active_count = basic_types.UBInt32()\n- count_lookup = basic_types.UBInt64()\n- count_matched = basic_types.UBInt64()\n-\n- def __init__(self, table_id=None, name=None, wildcards=None,\n- max_entries=None, active_count=None, count_lookup=None,\n- count_matched=None):\n- self.table_id = table_id\n- self.name = name\n- self.wildcards = wildcards\n- self.max_entries = max_entries\n- self.active_count = active_count\n- self.count_lookup = count_lookup\n- self.count_matched = count_matched\n"},"problem_statement":{"kind":"string","value":"Move all non-messages classes to other files\nSome classes (structs) does not define messages, but only structures that will be used on messages (such as \"desc_stats\").\r\n\r\nAs defined, only \"messages\" will have a \"file\" (submodule) for itself.\r\n\r\nNo, the files that does not hold a message should have its content splitted into other files."},"repo":{"kind":"string","value":"kytos/python-openflow"},"test_patch":{"kind":"string","value":"diff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py\nindex 3fc3326..1c699dd 100644\n--- a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py\n+++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch import aggregate_stats_reply\n+from pyof.v0x01.controller2switch.common import AggregateStatsReply\n \n \n class TestAggregateStatsReply(unittest.TestCase):\n \n def setUp(self):\n- self.message = aggregate_stats_reply.AggregateStatsReply()\n+ self.message = AggregateStatsReply()\n self.message.packet_count = 5\n self.message.byte_count = 1\n self.message.flow_count = 8\ndiff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py\nindex ca563fe..8e4be10 100644\n--- a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py\n@@ -2,13 +2,13 @@ import unittest\n \n from pyof.v0x01.common import flow_match\n from pyof.v0x01.common import phy_port\n-from pyof.v0x01.controller2switch import aggregate_stats_request\n+from pyof.v0x01.controller2switch.common import AggregateStatsRequest\n \n \n class TestAggregateStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = aggregate_stats_request.AggregateStatsRequest()\n+ self.message = AggregateStatsRequest()\n self.message.match = flow_match.Match()\n self.message.table_id = 1\n self.message.out_port = phy_port.Port.OFPP_NONE\ndiff --git a/tests/v0x01/test_controller2switch/test_desc_stats.py b/tests/v0x01/test_controller2switch/test_desc_stats.py\nindex 5ea6422..4f13f97 100644\n--- a/tests/v0x01/test_controller2switch/test_desc_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_desc_stats.py\n@@ -1,6 +1,6 @@\n import unittest\n \n-from pyof.v0x01.controller2switch import desc_stats\n+from pyof.v0x01.controller2switch.common import DescStats\n from pyof.v0x01.foundation import base\n \n \n@@ -8,7 +8,7 @@ class TestDescStats(unittest.TestCase):\n \n def setUp(self):\n content = bytes('A' * base.DESC_STR_LEN, 'utf-8')\n- self.message = desc_stats.DescStats()\n+ self.message = DescStats()\n self.message.mfr_desc = content\n self.message.hw_desc = content\n self.message.sw_desc = content\ndiff --git a/tests/v0x01/test_controller2switch/test_flow_stats.py b/tests/v0x01/test_controller2switch/test_flow_stats.py\nindex 1de34ab..2a04c07 100644\n--- a/tests/v0x01/test_controller2switch/test_flow_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_flow_stats.py\n@@ -1,13 +1,13 @@\n import unittest\n \n from pyof.v0x01.common import flow_match\n-from pyof.v0x01.controller2switch import flow_stats\n+from pyof.v0x01.controller2switch.common import FlowStats\n \n \n class TestFlowStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = flow_stats.FlowStats()\n+ self.message = FlowStats()\n self.message.length = 160\n self.message.table_id = 1\n self.message.match = flow_match.Match()\ndiff --git a/tests/v0x01/test_controller2switch/test_flow_stats_request.py b/tests/v0x01/test_controller2switch/test_flow_stats_request.py\nindex 85a33bb..2a6f3fb 100644\n--- a/tests/v0x01/test_controller2switch/test_flow_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_flow_stats_request.py\n@@ -1,13 +1,13 @@\n import unittest\n \n from pyof.v0x01.common import flow_match\n-from pyof.v0x01.controller2switch import flow_stats_request\n+from pyof.v0x01.controller2switch.common import FlowStatsRequest\n \n \n class TestFlowStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = flow_stats_request.FlowStatsRequest()\n+ self.message = FlowStatsRequest()\n self.message.match = flow_match.Match()\n self.message.table_id = 1\n self.message.out_port = 80\ndiff --git a/tests/v0x01/test_controller2switch/test_port_stats.py b/tests/v0x01/test_controller2switch/test_port_stats.py\nindex 7a58485..e6f4b55 100644\n--- a/tests/v0x01/test_controller2switch/test_port_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_port_stats.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch import port_stats\n+from pyof.v0x01.controller2switch.common import PortStats\n \n \n class TestPortStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = port_stats.PortStats()\n+ self.message = PortStats()\n self.message.port_no = 80\n self.message.rx_packets = 5\n self.message.tx_packets = 10\ndiff --git a/tests/v0x01/test_controller2switch/test_port_stats_request.py b/tests/v0x01/test_controller2switch/test_port_stats_request.py\nindex e0454dc..8025055 100644\n--- a/tests/v0x01/test_controller2switch/test_port_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_port_stats_request.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch import port_stats_request\n+from pyof.v0x01.controller2switch.common import PortStatsRequest \n \n \n class TestPortStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = port_stats_request.PortStatsRequest()\n+ self.message = PortStatsRequest()\n self.message.port_no = 80\n \n def test_get_size(self):\ndiff --git a/tests/v0x01/test_controller2switch/test_queue_stats.py b/tests/v0x01/test_controller2switch/test_queue_stats.py\nindex fb03ee7..b1f1219 100644\n--- a/tests/v0x01/test_controller2switch/test_queue_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_queue_stats.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch import queue_stats\n+from pyof.v0x01.controller2switch.common import QueueStats\n \n \n class TestQueueStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = queue_stats.QueueStats()\n+ self.message = QueueStats()\n self.message.port_no = 80\n self.message.queue_id = 5\n self.message.tx_bytes = 1\ndiff --git a/tests/v0x01/test_controller2switch/test_queue_stats_request.py b/tests/v0x01/test_controller2switch/test_queue_stats_request.py\nindex 80cad68..2f95381 100644\n--- a/tests/v0x01/test_controller2switch/test_queue_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_queue_stats_request.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch import queue_stats_request\n+from pyof.v0x01.controller2switch.common import QueueStatsRequest\n \n \n class TestQueueStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = queue_stats_request.QueueStatsRequest()\n+ self.message = QueueStatsRequest()\n self.message.port_no = 80\n self.message.queue_id = 5\n \ndiff --git a/tests/v0x01/test_controller2switch/test_table_stats.py b/tests/v0x01/test_controller2switch/test_table_stats.py\nindex 353f6de..39888b5 100644\n--- a/tests/v0x01/test_controller2switch/test_table_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_table_stats.py\n@@ -1,14 +1,14 @@\n import unittest\n \n from pyof.v0x01.common import flow_match\n-from pyof.v0x01.controller2switch import table_stats\n+from pyof.v0x01.controller2switch.common import TableStats\n from pyof.v0x01.foundation import base\n \n \n class TestTableStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = table_stats.TableStats()\n+ self.message = TableStats()\n self.message.table_id = 1\n self.message.name = bytes('X' * base.OFP_MAX_TABLE_NAME_LEN, 'utf-8')\n self.message.wildcards = flow_match.FlowWildCards.OFPFW_TP_DST\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_removed_files\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 1,\n \"test_score\": 3\n },\n \"num_modified_files\": 4\n}"},"version":{"kind":"string","value":"unknown"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio\",\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"coverage==7.8.0\nexceptiongroup==1.2.2\nexecnet==2.1.1\niniconfig==2.1.0\n-e git+https://github.com/kytos/python-openflow.git@275103dca4116b8911dc19ddad4b90121936d9f1#egg=Kytos_OpenFlow_Parser_library\npackaging==24.2\npluggy==1.5.0\npytest==8.3.5\npytest-asyncio==0.26.0\npytest-cov==6.0.0\npytest-mock==3.14.0\npytest-xdist==3.6.1\ntomli==2.2.1\ntyping_extensions==4.13.0\n"},"environment":{"kind":"string","value":"name: python-openflow\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - coverage==7.8.0\n - exceptiongroup==1.2.2\n - execnet==2.1.1\n - iniconfig==2.1.0\n - packaging==24.2\n - pluggy==1.5.0\n - pytest==8.3.5\n - pytest-asyncio==0.26.0\n - pytest-cov==6.0.0\n - pytest-mock==3.14.0\n - pytest-xdist==3.6.1\n - tomli==2.2.1\n - typing-extensions==4.13.0\nprefix: /opt/conda/envs/python-openflow\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py::TestAggregateStatsReply::test_get_size","tests/v0x01/test_controller2switch/test_aggregate_stats_request.py::TestAggregateStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_desc_stats.py::TestDescStats::test_get_size","tests/v0x01/test_controller2switch/test_flow_stats.py::TestFlowStats::test_get_size","tests/v0x01/test_controller2switch/test_flow_stats_request.py::TestFlowStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_port_stats.py::TestPortStats::test_get_size","tests/v0x01/test_controller2switch/test_port_stats_request.py::TestPortStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_queue_stats.py::TestQueueStats::test_get_size","tests/v0x01/test_controller2switch/test_queue_stats_request.py::TestQueueStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_table_stats.py::TestTableStats::test_get_size"],"string":"[\n \"tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py::TestAggregateStatsReply::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_aggregate_stats_request.py::TestAggregateStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_desc_stats.py::TestDescStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_flow_stats.py::TestFlowStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_flow_stats_request.py::TestFlowStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_port_stats.py::TestPortStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_port_stats_request.py::TestPortStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_queue_stats.py::TestQueueStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_queue_stats_request.py::TestQueueStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_table_stats.py::TestTableStats::test_get_size\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":576,"string":"576"}}},{"rowIdx":576,"cells":{"instance_id":{"kind":"string","value":"kytos__python-openflow-58"},"base_commit":{"kind":"string","value":"545ae8a73dcec2e67cf854b21c44e692692f71dc"},"created_at":{"kind":"string","value":"2016-06-07 18:27:19"},"environment_setup_commit":{"kind":"string","value":"545ae8a73dcec2e67cf854b21c44e692692f71dc"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/pyof/v0x01/common/flow_match.py b/pyof/v0x01/common/flow_match.py\nindex a900b81..07d103e 100644\n--- a/pyof/v0x01/common/flow_match.py\n+++ b/pyof/v0x01/common/flow_match.py\n@@ -1,6 +1,7 @@\n \"\"\"Defines flow statistics structures and related items\"\"\"\n \n # System imports\n+import enum\n \n # Third-party imports\n \n@@ -8,7 +9,10 @@\n from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n-class FlowWildCards(base.GenericBitMask):\n+# Enums\n+\n+\n+class FlowWildCards(enum.Enum):\n \"\"\"\n Wildcards used to identify flows.\n \ndiff --git a/pyof/v0x01/common/phy_port.py b/pyof/v0x01/common/phy_port.py\nindex 7395fb6..b45777f 100644\n--- a/pyof/v0x01/common/phy_port.py\n+++ b/pyof/v0x01/common/phy_port.py\n@@ -1,6 +1,7 @@\n \"\"\"Defines physical port classes and related items\"\"\"\n \n # System imports\n+import enum\n \n # Third-party imports\n \n@@ -8,20 +9,9 @@\n from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n+# Enums\n+\n class PortConfig(base.GenericBitMask):\n- \"\"\"Flags to indicate behavior of the physical port.\n-\n- These flags are used in OFPPhyPort to describe the current configuration.\n- They are used in the OFPPortMod message to configure the port's behavior.\n-\n- OFPPC_PORT_DOWN # Port is administratively down.\n- OFPPC_NO_STP # Disable 802.1D spanning tree on port.\n- OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree.\n- OFPPC_NO_RECV_STP # Drop received 802.1D STP packets.\n- OFPPC_NO_FLOOD # Do not include this port when flooding.\n- OFPPC_NO_FWD # Drop packets forwarded to port.\n- OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port.\n- \"\"\"\n OFPC_PORT_DOWN = 1 << 0\n OFPPC_NO_STP = 1 << 1\n OFPPC_NO_RECV = 1 << 2\n@@ -31,9 +21,32 @@ class PortConfig(base.GenericBitMask):\n OFPPC_NO_PACKET_IN = 1 << 6\n \n \n-\n-\n-class PortState(base.GenericBitMask):\n+#class PortConfig(enum.Enum):\n+# \"\"\"Flags to indicate behavior of the physical port.\n+#\n+# These flags are used in OFPPhyPort to describe the current configuration.\n+# They are used in the OFPPortMod message to configure the port's behavior.\n+#\n+# Enums:\n+# OFPPC_PORT_DOWN # Port is administratively down.\n+# OFPPC_NO_STP # Disable 802.1D spanning tree on port.\n+# OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree.\n+# OFPPC_NO_RECV_STP # Drop received 802.1D STP packets.\n+# OFPPC_NO_FLOOD # Do not include this port when flooding.\n+# OFPPC_NO_FWD # Drop packets forwarded to port.\n+# OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port.\n+# \"\"\"\n+#\n+# OFPPC_PORT_DOWN = 1 << 0\n+# OFPPC_NO_STP = 1 << 1\n+# OFPPC_NO_RECV = 1 << 2\n+# OFPPC_NO_RECV_STP = 1 << 3\n+# OFPPC_FLOOD = 1 << 4\n+# OFPPC_NO_FWD = 1 << 5\n+# OFPPC_NO_PACKET_IN = 1 << 6\n+\n+\n+class PortState(enum.Enum):\n \"\"\"Current state of the physical port.\n \n These are not configurable from the controller.\n@@ -42,6 +55,7 @@ class PortState(base.GenericBitMask):\n must adjust OFPPC_NO_RECV, OFPPC_NO_FWD, and OFPPC_NO_PACKET_IN\n appropriately to fully implement an 802.1D spanning tree.\n \n+ Enums:\n OFPPS_LINK_DOWN # Not learning or relaying frames.\n OFPPS_STP_LISTEN # Not learning or relaying frames.\n OFPPS_STP_LEARN # Learning but not relaying frames.\n@@ -58,7 +72,7 @@ class PortState(base.GenericBitMask):\n # OFPPS_STP_MASK = 3 << 8 - Refer to ISSUE #7\n \n \n-class Port(base.GenericBitMask):\n+class Port(enum.Enum):\n \"\"\"Port numbering.\n \n Physical ports are numbered starting from 1. Port number 0 is reserved by\n@@ -87,13 +101,14 @@ class Port(base.GenericBitMask):\n OFPP_NONE = 0xffff\n \n \n-class PortFeatures(base.GenericBitMask):\n+class PortFeatures(enum.Enum):\n \"\"\"Physical ports features.\n \n The curr, advertised, supported, and peer fields indicate link modes\n (10M to 10G full and half-duplex), link type (copper/fiber) and\n link features (autone-gotiation and pause).\n \n+ Enums:\n OFPPF_10MB_HD # 10 Mb half-duplex rate support.\n OFPPF_10MB_FD # 10 Mb full-duplex rate support.\n OFPPF_100MB_HD # 100 Mb half-duplex rate support.\ndiff --git a/pyof/v0x01/controller2switch/aggregate_stats_reply.py b/pyof/v0x01/controller2switch/aggregate_stats_reply.py\nnew file mode 100644\nindex 0000000..339127c\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/aggregate_stats_reply.py\n@@ -0,0 +1,31 @@\n+\"\"\"Body of the reply message\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+# Classes\n+\n+\n+class AggregateStatsReply(base.GenericStruct):\n+ \"\"\"Body of reply to OFPST_AGGREGATE request.\n+\n+ :param packet_count: Number of packets in flows\n+ :param byte_count: Number of bytes in flows\n+ :param flow_count: Number of flows\n+ :param pad: Align to 64 bits\n+\n+ \"\"\"\n+ packet_count = basic_types.UBInt64()\n+ byte_count = basic_types.UBInt64()\n+ flow_count = basic_types.UBInt32()\n+ pad = basic_types.PAD(4)\n+\n+ def __init__(self, packet_count=None, byte_count=None, flow_count=None):\n+ self.packet_count = packet_count\n+ self.byte_count = byte_count\n+ self.flow_count = flow_count\ndiff --git a/pyof/v0x01/controller2switch/aggregate_stats_request.py b/pyof/v0x01/controller2switch/aggregate_stats_request.py\nnew file mode 100644\nindex 0000000..b45f923\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/aggregate_stats_request.py\n@@ -0,0 +1,38 @@\n+\"\"\"Aggregate information about multiple flows is requested with the\n+OFPST_AGGREGATE stats request type\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.common import flow_match\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+# Classes\n+\n+\n+class AggregateStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Body for ofp_stats_request of type OFPST_AGGREGATE.\n+\n+ :param match: Fields to match\n+ :param table_id: ID of table to read (from pyof_table_stats) 0xff\n+ for all tables or 0xfe for emergency.\n+ :param pad: Align to 32 bits\n+ :param out_port: Require matching entries to include this as an\n+ output port. A value of OFPP_NONE indicates\n+ no restriction\n+\n+ \"\"\"\n+ match = flow_match.Match()\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(1)\n+ out_port = basic_types.UBInt16()\n+\n+ def __init__(self, match=None, table_id=None, out_port=None):\n+ super().__init__()\n+ self.match = match\n+ self.table_id = table_id\n+ self.out_port = out_port\ndiff --git a/pyof/v0x01/controller2switch/common.py b/pyof/v0x01/controller2switch/common.py\nindex bfb9cd3..c5490dd 100644\n--- a/pyof/v0x01/controller2switch/common.py\n+++ b/pyof/v0x01/controller2switch/common.py\n@@ -8,7 +8,6 @@ import enum\n # Local source tree imports\n from pyof.v0x01.common import header as of_header\n from pyof.v0x01.common import action\n-from pyof.v0x01.common import flow_match\n from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n@@ -66,313 +65,3 @@ class ListOfActions(basic_types.FixedTypeList):\n \"\"\"\n def __init__(self, items=None):\n super().__init__(pyof_class=action.ActionHeader, items=items)\n-\n-\n-class AggregateStatsReply(base.GenericStruct):\n- \"\"\"Body of reply to OFPST_AGGREGATE request.\n-\n- :param packet_count: Number of packets in flows\n- :param byte_count: Number of bytes in flows\n- :param flow_count: Number of flows\n- :param pad: Align to 64 bits\n-\n- \"\"\"\n- packet_count = basic_types.UBInt64()\n- byte_count = basic_types.UBInt64()\n- flow_count = basic_types.UBInt32()\n- pad = basic_types.PAD(4)\n-\n- def __init__(self, packet_count=None, byte_count=None, flow_count=None):\n- self.packet_count = packet_count\n- self.byte_count = byte_count\n- self.flow_count = flow_count\n-\n-\n-class AggregateStatsRequest(base.GenericStruct):\n- \"\"\"\n- Body for ofp_stats_request of type OFPST_AGGREGATE.\n-\n- :param match: Fields to match\n- :param table_id: ID of table to read (from pyof_table_stats) 0xff\n- for all tables or 0xfe for emergency.\n- :param pad: Align to 32 bits\n- :param out_port: Require matching entries to include this as an\n- output port. A value of OFPP_NONE indicates\n- no restriction\n-\n- \"\"\"\n- match = flow_match.Match()\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(1)\n- out_port = basic_types.UBInt16()\n-\n- def __init__(self, match=None, table_id=None, out_port=None):\n- super().__init__()\n- self.match = match\n- self.table_id = table_id\n- self.out_port = out_port\n-\n-\n-class DescStats(base.GenericStruct):\n- \"\"\"\n- Information about the switch manufacturer, hardware revision, software\n- revision, serial number, and a description field is avail- able from\n- the OFPST_DESC stats request.\n-\n- :param mfr_desc: Manufacturer description\n- :param hw_desc: Hardware description\n- :param sw_desc: Software description\n- :param serial_num: Serial number\n- :param dp_desc: Human readable description of datapath\n-\n- \"\"\"\n- mfr_desc = basic_types.Char(length=base.DESC_STR_LEN)\n- hw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n- sw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n- serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN)\n- dp_desc = basic_types.Char(length=base.DESC_STR_LEN)\n-\n- def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None,\n- serial_num=None, dp_desc=None):\n- self.mfr_desc = mfr_desc\n- self.hw_desc = hw_desc\n- self.sw_desc = sw_desc\n- self.serial_num = serial_num\n- self.dp_desc = dp_desc\n-\n-\n-class FlowStats(base.GenericStruct):\n- \"\"\"\n- Body of reply to OFPST_FLOW request.\n-\n- :param length: Length of this entry\n- :param table_id: ID of table flow came from\n- :param pad: Align to 32 bits\n- :param match: Description of fields\n- :param duration_sec: Time flow has been alive in seconds\n- :param duration_nsec: Time flow has been alive in nanoseconds beyond\n- duration_sec\n- :param priority: Priority of the entry. Only meaningful when this\n- is not an exact-match entry\n- :param idle_timeout: Number of seconds idle before expiration\n- :param hard_timeout: Number of seconds before expiration\n- :param pad2: Align to 64-bits\n- :param cookie: Opaque controller-issued identifier\n- :param packet_count: Number of packets in flow\n- :param byte_count: Number of bytes in flow\n- :param actions: Actions\n- \"\"\"\n- length = basic_types.UBInt16()\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(1)\n- match = flow_match.Match()\n- duration_sec = basic_types.UBInt32()\n- duration_nsec = basic_types.UBInt32()\n- priority = basic_types.UBInt16()\n- idle_timeout = basic_types.UBInt16()\n- hard_timeout = basic_types.UBInt16()\n- pad2 = basic_types.PAD(6)\n- cookie = basic_types.UBInt64()\n- packet_count = basic_types.UBInt64()\n- byte_count = basic_types.UBInt64()\n- actions = ListOfActions()\n-\n- def __init__(self, length=None, table_id=None, match=None,\n- duration_sec=None, duration_nsec=None, priority=None,\n- idle_timeout=None, hard_timeout=None, cookie=None,\n- packet_count=None, byte_count=None, actions=None):\n- self.length = length\n- self.table_id = table_id\n- self.match = match\n- self.duration_sec = duration_sec\n- self.duration_nsec = duration_nsec\n- self.prioriry = priority\n- self.idle_timeout = idle_timeout\n- self.hard_timeout = hard_timeout\n- self.cookie = cookie\n- self.packet_count = packet_count\n- self.byte_count = byte_count\n- self.actions = [] if actions is None else actions\n-\n-\n-class FlowStatsRequest(base.GenericStruct):\n- \"\"\"\n- Body for ofp_stats_request of type OFPST_FLOW.\n-\n- :param match: Fields to match\n- :param table_id: ID of table to read (from pyof_table_stats)\n- 0xff for all tables or 0xfe for emergency\n- :param pad: Align to 32 bits\n- :param out_port: Require matching entries to include this as an output\n- port. A value of OFPP_NONE indicates no restriction.\n-\n- \"\"\"\n- match = flow_match.Match()\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(1)\n- out_port = basic_types.UBInt16()\n-\n- def __init__(self, match=None, table_id=None, out_port=None):\n- self.match = match\n- self.table_id = table_id\n- self.out_port = out_port\n-\n-\n-class PortStats(base.GenericStruct):\n- \"\"\"Body of reply to OFPST_PORT request.\n-\n- If a counter is unsupported, set the field to all ones.\n-\n- :param port_no: Port number\n- :param pad: Align to 64-bits\n- :param rx_packets: Number of received packets\n- :param tx_packets: Number of transmitted packets\n- :param rx_bytes: Number of received bytes\n- :param tx_bytes: Number of transmitted bytes\n- :param rx_dropped: Number of packets dropped by RX\n- :param tx_dropped: Number of packets dropped by TX\n- :param rx_errors: Number of receive errors. This is a super-set\n- of more specific receive errors and should be\n- greater than or equal to the sum of all\n- rx_*_err values\n- :param tx_errors: Number of transmit errors. This is a super-set\n- of more specific transmit errors and should be\n- greater than or equal to the sum of all\n- tx_*_err values (none currently defined.)\n- :param rx_frame_err: Number of frame alignment errors\n- :param rx_over_err: Number of packets with RX overrun\n- :param rx_crc_err: Number of CRC errors\n- :param collisions: Number of collisions\n-\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(6)\n- rx_packets = basic_types.UBInt64()\n- tx_packets = basic_types.UBInt64()\n- rx_bytes = basic_types.UBInt64()\n- tx_bytes = basic_types.UBInt64()\n- rx_dropped = basic_types.UBInt64()\n- tx_dropped = basic_types.UBInt64()\n- rx_errors = basic_types.UBInt64()\n- tx_errors = basic_types.UBInt64()\n- rx_frame_err = basic_types.UBInt64()\n- rx_over_err = basic_types.UBInt64()\n- rx_crc_err = basic_types.UBInt64()\n- collisions = basic_types.UBInt64()\n-\n- def __init__(self, port_no=None, rx_packets=None,\n- tx_packets=None, rx_bytes=None, tx_bytes=None,\n- rx_dropped=None, tx_dropped=None, rx_errors=None,\n- tx_errors=None, rx_frame_err=None, rx_over_err=None,\n- rx_crc_err=None, collisions=None):\n- self.port_no = port_no\n- self.rx_packets = rx_packets\n- self.tx_packets = tx_packets\n- self.rx_bytes = rx_bytes\n- self.tx_bytes = tx_bytes\n- self.rx_dropped = rx_dropped\n- self.tx_dropped = tx_dropped\n- self.rx_errors = rx_errors\n- self.tx_errors = tx_errors\n- self.rx_frame_err = rx_frame_err\n- self.rx_over_err = rx_over_err\n- self.rx_crc_err = rx_crc_err\n- self.collisions = collisions\n-\n-\n-class PortStatsRequest(base.GenericStruct):\n- \"\"\"\n- Body for ofp_stats_request of type OFPST_PORT\n-\n- :param port_no: OFPST_PORT message must request statistics either\n- for a single port (specified in port_no) or for\n- all ports (if port_no == OFPP_NONE).\n- :param pad:\n-\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(6)\n-\n- def __init__(self, port_no=None):\n- self.port_no = port_no\n-\n-\n-class QueueStats(base.GenericStruct):\n- \"\"\"\n- Implements the reply body of a port_no\n-\n- :param port_no: Port Number\n- :param pad: Align to 32-bits\n- :param queue_id: Queue ID\n- :param tx_bytes: Number of transmitted bytes\n- :param tx_packets: Number of transmitted packets\n- :param tx_errors: Number of packets dropped due to overrun\n-\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(2)\n- queue_id = basic_types.UBInt32()\n- tx_bytes = basic_types.UBInt64()\n- tx_packets = basic_types.UBInt64()\n- tx_errors = basic_types.UBInt64()\n-\n- def __init__(self, port_no=None, queue_id=None, tx_bytes=None,\n- tx_packets=None, tx_errors=None):\n- self.port_no = port_no\n- self.queue_id = queue_id\n- self.tx_bytes = tx_bytes\n- self.tx_packets = tx_packets\n- self.tx_errors = tx_errors\n-\n-\n-class QueueStatsRequest(base.GenericStruct):\n- \"\"\"\n- Implements the request body of a port_no\n-\n- :param port_no: All ports if OFPT_ALL\n- :param pad: Align to 32-bits\n- :param queue_id: All queues if OFPQ_ALL\n- \"\"\"\n- port_no = basic_types.UBInt16()\n- pad = basic_types.PAD(2)\n- queue_id = basic_types.UBInt32()\n-\n- def __init__(self, port_no=None, queue_id=None):\n- self.port_no = port_no\n- self.queue_id = queue_id\n-\n-\n-class TableStats(base.GenericStruct):\n- \"\"\"Body of reply to OFPST_TABLE request.\n-\n- :param table_id: Identifier of table. Lower numbered tables\n- are consulted first\n- :param pad: Align to 32-bits\n- :param name: Table name\n- :param wildcards: Bitmap of OFPFW_* wildcards that are supported\n- by the table\n- :param max_entries: Max number of entries supported\n- :param active_count: Number of active entries\n- :param count_lookup: Number of packets looked up in table\n- :param count_matched: Number of packets that hit table\n-\n- \"\"\"\n- table_id = basic_types.UBInt8()\n- pad = basic_types.PAD(3)\n- name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN)\n- wildcards = basic_types.UBInt32()\n- max_entries = basic_types.UBInt32()\n- active_count = basic_types.UBInt32()\n- count_lookup = basic_types.UBInt64()\n- count_matched = basic_types.UBInt64()\n-\n- def __init__(self, table_id=None, name=None, wildcards=None,\n- max_entries=None, active_count=None, count_lookup=None,\n- count_matched=None):\n- self.table_id = table_id\n- self.name = name\n- self.wildcards = wildcards\n- self.max_entries = max_entries\n- self.active_count = active_count\n- self.count_lookup = count_lookup\n- self.count_matched = count_matched\ndiff --git a/pyof/v0x01/controller2switch/desc_stats.py b/pyof/v0x01/controller2switch/desc_stats.py\nnew file mode 100644\nindex 0000000..bceffb9\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/desc_stats.py\n@@ -0,0 +1,39 @@\n+\"\"\"Information about the switch manufactures\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+# Classes\n+\n+\n+class DescStats(base.GenericStruct):\n+ \"\"\"\n+ Information about the switch manufacturer, hardware revision, software\n+ revision, serial number, and a description field is avail- able from\n+ the OFPST_DESC stats request.\n+\n+ :param mfr_desc: Manufacturer description\n+ :param hw_desc: Hardware description\n+ :param sw_desc: Software description\n+ :param serial_num: Serial number\n+ :param dp_desc: Human readable description of datapath\n+\n+ \"\"\"\n+ mfr_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+ hw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+ sw_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+ serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN)\n+ dp_desc = basic_types.Char(length=base.DESC_STR_LEN)\n+\n+ def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None,\n+ serial_num=None, dp_desc=None):\n+ self.mfr_desc = mfr_desc\n+ self.hw_desc = hw_desc\n+ self.sw_desc = sw_desc\n+ self.serial_num = serial_num\n+ self.dp_desc = dp_desc\ndiff --git a/pyof/v0x01/controller2switch/features_reply.py b/pyof/v0x01/controller2switch/features_reply.py\nindex c5f3bca..e02f012 100644\n--- a/pyof/v0x01/controller2switch/features_reply.py\n+++ b/pyof/v0x01/controller2switch/features_reply.py\n@@ -1,6 +1,7 @@\n \"\"\"Defines Features Reply classes and related items\"\"\"\n \n # System imports\n+import enum\n \n # Third-party imports\n \n@@ -11,9 +12,13 @@ from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n \n \n-class Capabilities(base.GenericBitMask):\n- \"\"\"Capabilities supported by the datapath\n+# Enums\n \n+\n+class Capabilities(enum.Enum):\n+ \"\"\"Enumeration of Capabilities supported by the datapath\n+\n+ Enums:\n OFPC_FLOW_STATS # Flow statistics\n OFPC_TABLE_STATS # Table statistics\n OFPC_PORT_STATS # Port statistics\ndiff --git a/pyof/v0x01/controller2switch/flow_stats.py b/pyof/v0x01/controller2switch/flow_stats.py\nnew file mode 100644\nindex 0000000..efb5edd\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/flow_stats.py\n@@ -0,0 +1,67 @@\n+\"\"\"Body of the reply to an OFPST_FLOW\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.common import flow_match\n+from pyof.v0x01.controller2switch import common\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+# Classes\n+\n+\n+class FlowStats(base.GenericStruct):\n+ \"\"\"\n+ Body of reply to OFPST_FLOW request.\n+\n+ :param length: Length of this entry\n+ :param table_id: ID of table flow came from\n+ :param pad: Align to 32 bits\n+ :param match: Description of fields\n+ :param duration_sec: Time flow has been alive in seconds\n+ :param duration_nsec: Time flow has been alive in nanoseconds beyond\n+ duration_sec\n+ :param priority: Priority of the entry. Only meaningful when this\n+ is not an exact-match entry\n+ :param idle_timeout: Number of seconds idle before expiration\n+ :param hard_timeout: Number of seconds before expiration\n+ :param pad2: Align to 64-bits\n+ :param cookie: Opaque controller-issued identifier\n+ :param packet_count: Number of packets in flow\n+ :param byte_count: Number of bytes in flow\n+ :param actions: Actions\n+ \"\"\"\n+ length = basic_types.UBInt16()\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(1)\n+ match = flow_match.Match()\n+ duration_sec = basic_types.UBInt32()\n+ duration_nsec = basic_types.UBInt32()\n+ priority = basic_types.UBInt16()\n+ idle_timeout = basic_types.UBInt16()\n+ hard_timeout = basic_types.UBInt16()\n+ pad2 = basic_types.PAD(6)\n+ cookie = basic_types.UBInt64()\n+ packet_count = basic_types.UBInt64()\n+ byte_count = basic_types.UBInt64()\n+ actions = common.ListOfActions()\n+\n+ def __init__(self, length=None, table_id=None, match=None,\n+ duration_sec=None, duration_nsec=None, priority=None,\n+ idle_timeout=None, hard_timeout=None, cookie=None,\n+ packet_count=None, byte_count=None, actions=None):\n+ self.length = length\n+ self.table_id = table_id\n+ self.match = match\n+ self.duration_sec = duration_sec\n+ self.duration_nsec = duration_nsec\n+ self.prioriry = priority\n+ self.idle_timeout = idle_timeout\n+ self.hard_timeout = hard_timeout\n+ self.cookie = cookie\n+ self.packet_count = packet_count\n+ self.byte_count = byte_count\n+ self.actions = [] if actions is None else actions\ndiff --git a/pyof/v0x01/controller2switch/flow_stats_request.py b/pyof/v0x01/controller2switch/flow_stats_request.py\nnew file mode 100644\nindex 0000000..1fc5794\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/flow_stats_request.py\n@@ -0,0 +1,35 @@\n+\"\"\"Information about individual flows\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.common import flow_match\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+# Classes\n+\n+\n+class FlowStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Body for ofp_stats_request of type OFPST_FLOW.\n+\n+ :param match: Fields to match\n+ :param table_id: ID of table to read (from pyof_table_stats)\n+ 0xff for all tables or 0xfe for emergency\n+ :param pad: Align to 32 bits\n+ :param out_port: Require matching entries to include this as an output\n+ port. A value of OFPP_NONE indicates no restriction.\n+\n+ \"\"\"\n+ match = flow_match.Match()\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(1)\n+ out_port = basic_types.UBInt16()\n+\n+ def __init__(self, match=None, table_id=None, out_port=None):\n+ self.match = match\n+ self.table_id = table_id\n+ self.out_port = out_port\ndiff --git a/pyof/v0x01/controller2switch/port_stats.py b/pyof/v0x01/controller2switch/port_stats.py\nnew file mode 100644\nindex 0000000..474828d\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/port_stats.py\n@@ -0,0 +1,73 @@\n+\"\"\"Body of the port stats reply\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+# Classes\n+\n+\n+class PortStats(base.GenericStruct):\n+ \"\"\"Body of reply to OFPST_PORT request.\n+\n+ If a counter is unsupported, set the field to all ones.\n+\n+ :param port_no: Port number\n+ :param pad: Align to 64-bits\n+ :param rx_packets: Number of received packets\n+ :param tx_packets: Number of transmitted packets\n+ :param rx_bytes: Number of received bytes\n+ :param tx_bytes: Number of transmitted bytes\n+ :param rx_dropped: Number of packets dropped by RX\n+ :param tx_dropped: Number of packets dropped by TX\n+ :param rx_errors: Number of receive errors. This is a super-set\n+ of more specific receive errors and should be\n+ greater than or equal to the sum of all\n+ rx_*_err values\n+ :param tx_errors: Number of transmit errors. This is a super-set\n+ of more specific transmit errors and should be\n+ greater than or equal to the sum of all\n+ tx_*_err values (none currently defined.)\n+ :param rx_frame_err: Number of frame alignment errors\n+ :param rx_over_err: Number of packets with RX overrun\n+ :param rx_crc_err: Number of CRC errors\n+ :param collisions: Number of collisions\n+\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(6)\n+ rx_packets = basic_types.UBInt64()\n+ tx_packets = basic_types.UBInt64()\n+ rx_bytes = basic_types.UBInt64()\n+ tx_bytes = basic_types.UBInt64()\n+ rx_dropped = basic_types.UBInt64()\n+ tx_dropped = basic_types.UBInt64()\n+ rx_errors = basic_types.UBInt64()\n+ tx_errors = basic_types.UBInt64()\n+ rx_frame_err = basic_types.UBInt64()\n+ rx_over_err = basic_types.UBInt64()\n+ rx_crc_err = basic_types.UBInt64()\n+ collisions = basic_types.UBInt64()\n+\n+ def __init__(self, port_no=None, rx_packets=None,\n+ tx_packets=None, rx_bytes=None, tx_bytes=None,\n+ rx_dropped=None, tx_dropped=None, rx_errors=None,\n+ tx_errors=None, rx_frame_err=None, rx_over_err=None,\n+ rx_crc_err=None, collisions=None):\n+ self.port_no = port_no\n+ self.rx_packets = rx_packets\n+ self.tx_packets = tx_packets\n+ self.rx_bytes = rx_bytes\n+ self.tx_bytes = tx_bytes\n+ self.rx_dropped = rx_dropped\n+ self.tx_dropped = tx_dropped\n+ self.rx_errors = rx_errors\n+ self.tx_errors = tx_errors\n+ self.rx_frame_err = rx_frame_err\n+ self.rx_over_err = rx_over_err\n+ self.rx_crc_err = rx_crc_err\n+ self.collisions = collisions\ndiff --git a/pyof/v0x01/controller2switch/port_stats_request.py b/pyof/v0x01/controller2switch/port_stats_request.py\nnew file mode 100644\nindex 0000000..8fa4049\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/port_stats_request.py\n@@ -0,0 +1,26 @@\n+\"\"\"Information about physical ports is requested with OFPST_PORT\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+\n+class PortStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Body for ofp_stats_request of type OFPST_PORT\n+\n+ :param port_no: OFPST_PORT message must request statistics either\n+ for a single port (specified in port_no) or for\n+ all ports (if port_no == OFPP_NONE).\n+ :param pad:\n+\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(6)\n+\n+ def __init__(self, port_no=None):\n+ self.port_no = port_no\ndiff --git a/pyof/v0x01/controller2switch/queue_stats.py b/pyof/v0x01/controller2switch/queue_stats.py\nnew file mode 100644\nindex 0000000..d7df9b3\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/queue_stats.py\n@@ -0,0 +1,38 @@\n+\"\"\"The OFPST_QUEUE stats reply message provides queue statistics for one\n+or more ports.\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+\n+class QueueStats(base.GenericStruct):\n+ \"\"\"\n+ Implements the reply body of a port_no\n+\n+ :param port_no: Port Number\n+ :param pad: Align to 32-bits\n+ :param queue_id: Queue ID\n+ :param tx_bytes: Number of transmitted bytes\n+ :param tx_packets: Number of transmitted packets\n+ :param tx_errors: Number of packets dropped due to overrun\n+\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(2)\n+ queue_id = basic_types.UBInt32()\n+ tx_bytes = basic_types.UBInt64()\n+ tx_packets = basic_types.UBInt64()\n+ tx_errors = basic_types.UBInt64()\n+\n+ def __init__(self, port_no=None, queue_id=None, tx_bytes=None,\n+ tx_packets=None, tx_errors=None):\n+ self.port_no = port_no\n+ self.queue_id = queue_id\n+ self.tx_bytes = tx_bytes\n+ self.tx_packets = tx_packets\n+ self.tx_errors = tx_errors\ndiff --git a/pyof/v0x01/controller2switch/queue_stats_request.py b/pyof/v0x01/controller2switch/queue_stats_request.py\nnew file mode 100644\nindex 0000000..c1b431b\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/queue_stats_request.py\n@@ -0,0 +1,27 @@\n+\"\"\"The OFPST_QUEUE stats request message provides queue statistics for one\n+or more ports.\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+\n+class QueueStatsRequest(base.GenericStruct):\n+ \"\"\"\n+ Implements the request body of a port_no\n+\n+ :param port_no: All ports if OFPT_ALL\n+ :param pad: Align to 32-bits\n+ :param queue_id: All queues if OFPQ_ALL\n+ \"\"\"\n+ port_no = basic_types.UBInt16()\n+ pad = basic_types.PAD(2)\n+ queue_id = basic_types.UBInt32()\n+\n+ def __init__(self, port_no=None, queue_id=None):\n+ self.port_no = port_no\n+ self.queue_id = queue_id\ndiff --git a/pyof/v0x01/controller2switch/table_stats.py b/pyof/v0x01/controller2switch/table_stats.py\nnew file mode 100644\nindex 0000000..bf2e42f\n--- /dev/null\n+++ b/pyof/v0x01/controller2switch/table_stats.py\n@@ -0,0 +1,45 @@\n+\"\"\"Information about tables is requested with OFPST_TABLE stats request type\"\"\"\n+\n+# System imports\n+\n+# Third-party imports\n+\n+# Local source tree imports\n+from pyof.v0x01.foundation import base\n+from pyof.v0x01.foundation import basic_types\n+\n+\n+class TableStats(base.GenericStruct):\n+ \"\"\"Body of reply to OFPST_TABLE request.\n+\n+ :param table_id: Identifier of table. Lower numbered tables\n+ are consulted first\n+ :param pad: Align to 32-bits\n+ :param name: Table name\n+ :param wildcards: Bitmap of OFPFW_* wildcards that are supported\n+ by the table\n+ :param max_entries: Max number of entries supported\n+ :param active_count: Number of active entries\n+ :param count_lookup: Number of packets looked up in table\n+ :param count_matched: Number of packets that hit table\n+\n+ \"\"\"\n+ table_id = basic_types.UBInt8()\n+ pad = basic_types.PAD(3)\n+ name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN)\n+ wildcards = basic_types.UBInt32()\n+ max_entries = basic_types.UBInt32()\n+ active_count = basic_types.UBInt32()\n+ count_lookup = basic_types.UBInt64()\n+ count_matched = basic_types.UBInt64()\n+\n+ def __init__(self, table_id=None, name=None, wildcards=None,\n+ max_entries=None, active_count=None, count_lookup=None,\n+ count_matched=None):\n+ self.table_id = table_id\n+ self.name = name\n+ self.wildcards = wildcards\n+ self.max_entries = max_entries\n+ self.active_count = active_count\n+ self.count_lookup = count_lookup\n+ self.count_matched = count_matched\ndiff --git a/pyof/v0x01/foundation/base.py b/pyof/v0x01/foundation/base.py\nindex 7c07b3e..a146a48 100644\n--- a/pyof/v0x01/foundation/base.py\n+++ b/pyof/v0x01/foundation/base.py\n@@ -60,17 +60,16 @@ class GenericType(object):\n \"\"\"This is a foundation class for all custom attributes.\n \n Attributes like `UBInt8`, `UBInt16`, `HWAddress` amoung others uses this\n- class as base.\n- \"\"\"\n+ class as base.\"\"\"\n def __init__(self, value=None, enum_ref=None):\n self._value = value\n self._enum_ref = enum_ref\n \n def __repr__(self):\n- return \"{}({})\".format(self.__class__.__name__, self._value)\n+ return \"{}({})\".format(type(self).__name__, self._value)\n \n def __str__(self):\n- return '<{}: {}>'.format(self.__class__.__name__, str(self._value))\n+ return '{}'.format(str(self._value))\n \n def __eq__(self, other):\n return self._value == other\n@@ -105,7 +104,7 @@ class GenericType(object):\n return struct.pack(self._fmt, value)\n except struct.error as err:\n message = \"Value out of the possible range to basic type \"\n- message = message + self.__class__.__name__ + \". \"\n+ message = message + type(self).__name__ + \". \"\n message = message + str(err)\n raise exceptions.BadValueException(message)\n \n@@ -154,7 +153,6 @@ class GenericType(object):\n \n class MetaStruct(type):\n \"\"\"MetaClass used to force ordered attributes.\"\"\"\n-\n @classmethod\n def __prepare__(self, name, bases):\n return _OD()\n@@ -177,7 +175,6 @@ class GenericStruct(object, metaclass=MetaStruct):\n has a list of attributes and theses attributes can be of struct\n type too.\n \"\"\"\n-\n def __init__(self, *args, **kwargs):\n for _attr in self.__ordered__:\n if not callable(getattr(self, _attr)):\n@@ -186,29 +183,6 @@ class GenericStruct(object, metaclass=MetaStruct):\n except KeyError:\n pass\n \n- def __repr__(self):\n- message = self.__class__.__name__\n- message += '('\n- for _attr in self.__ordered__:\n- message += repr(getattr(self, _attr))\n- message += \", \"\n- # Removing a comma and a space from the end of the string\n- message = message[:-2]\n- message += ')'\n- return message\n-\n- def __str__(self):\n- message = \"{}:\\n\".format(self.__class__.__name__)\n- for _attr in self.__ordered__:\n- attr = getattr(self, _attr)\n- if not hasattr(attr, '_fmt'):\n- message += \" {}\".format(str(attr).replace('\\n', '\\n '))\n- else:\n- message += \" {}: {}\\n\".format(_attr, str(attr))\n- message.rstrip('\\r')\n- message.rstrip('\\n')\n- return message\n-\n def _attributes(self):\n \"\"\"Returns a generator with each attribute from the current instance.\n \n@@ -282,7 +256,7 @@ class GenericStruct(object, metaclass=MetaStruct):\n if _class.__name__ is 'PAD':\n size += attr.get_size()\n elif _class.__name__ is 'Char':\n- size += getattr(self.__class__, _attr).get_size()\n+ size += getattr(type(self), _attr).get_size()\n elif issubclass(_class, GenericType):\n size += _class().get_size()\n elif isinstance(attr, _class):\n@@ -302,13 +276,13 @@ class GenericStruct(object, metaclass=MetaStruct):\n \"\"\"\n if not self.is_valid():\n error_msg = \"Erro on validation prior to pack() on class \"\n- error_msg += \"{}.\".format(self.__class__.__name__)\n+ error_msg += \"{}.\".format(type(self).__name__)\n raise exceptions.ValidationError(error_msg)\n else:\n message = b''\n for attr_name, attr_class in self.__ordered__.items():\n attr = getattr(self, attr_name)\n- class_attr = getattr(self.__class__, attr_name)\n+ class_attr = getattr(type(self), attr_name)\n if isinstance(attr, attr_class):\n message += attr.pack()\n elif class_attr.is_enum():\n@@ -469,10 +443,10 @@ class GenericBitMask(object, metaclass=MetaBitMask):\n self.bitmask = bitmask\n \n def __str__(self):\n- return \"<%s: %s>\" % (self.__class__.__name__, self.names)\n+ return \"{}\".format(self.bitmask)\n \n def __repr__(self):\n- return \"<%s(%s)>\" % (self.__class__.__name__, self.bitmask)\n+ return \"{}({})\".format(type(self).__name__, self.bitmask)\n \n @property\n def names(self):\ndiff --git a/pyof/v0x01/foundation/basic_types.py b/pyof/v0x01/foundation/basic_types.py\nindex 417d7f1..ba26316 100644\n--- a/pyof/v0x01/foundation/basic_types.py\n+++ b/pyof/v0x01/foundation/basic_types.py\n@@ -27,10 +27,10 @@ class PAD(base.GenericType):\n self._length = length\n \n def __repr__(self):\n- return \"{}({})\".format(self.__class__.__name__, self._length)\n+ return \"{}({})\".format(type(self).__name__, self._length)\n \n def __str__(self):\n- return str(self._length)\n+ return self.pack()\n \n def get_size(self):\n \"\"\" Return the size of type in bytes. \"\"\"\n@@ -131,7 +131,6 @@ class BinaryData(base.GenericType):\n Both the 'pack' and 'unpack' methods will return the binary data itself.\n get_size method will return the size of the instance using python 'len'\n \"\"\"\n-\n def __init__(self, value=b''):\n super().__init__(value)\n \n@@ -144,7 +143,7 @@ class BinaryData(base.GenericType):\n else:\n raise exceptions.NotBinarydata()\n \n- def unpack(self, buff):\n+ def unpack(self, buff, offset):\n self._value = buff\n \n def get_size(self):\n@@ -163,18 +162,9 @@ class FixedTypeList(list, base.GenericStruct):\n elif items:\n self.append(items)\n \n- def __repr__(self):\n- \"\"\"Unique representantion of the object.\n-\n- This can be used to generate an object that has the\n- same content of the current object\"\"\"\n- return \"{}({},{})\".format(self.__class__.__name__,\n- self._pyof_class,\n- self)\n-\n def __str__(self):\n \"\"\"Human-readable object representantion\"\"\"\n- return \"{}\".format([item for item in self])\n+ return \"{}\".format([str(item) for item in self])\n \n def append(self, item):\n if type(item) is list:\n@@ -243,17 +233,9 @@ class ConstantTypeList(list, base.GenericStruct):\n elif items:\n self.append(items)\n \n- def __repr__(self):\n- \"\"\"Unique representantion of the object.\n-\n- This can be used to generate an object that has the\n- same content of the current object\"\"\"\n- return \"{}({})\".format(self.__class__.__name__,\n- self)\n-\n def __str__(self):\n \"\"\"Human-readable object representantion\"\"\"\n- return \"{}\".format([item for item in self])\n+ return \"{}\".format([str(item) for item in self])\n \n def append(self, item):\n if type(item) is list:\n"},"problem_statement":{"kind":"string","value":"Review all __str__ and __repr__ methods\nWe need to make sure that all `__str__` and `__repr__` are correct.\r\n\r\nFor instance, look how strange is `common.phy_port.PhyPort`:\r\n\r\n```\r\nPhyPort(None, None, None, None, None)\r\n```"},"repo":{"kind":"string","value":"kytos/python-openflow"},"test_patch":{"kind":"string","value":"diff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py\nindex 1c699dd..3fc3326 100644\n--- a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py\n+++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch.common import AggregateStatsReply\n+from pyof.v0x01.controller2switch import aggregate_stats_reply\n \n \n class TestAggregateStatsReply(unittest.TestCase):\n \n def setUp(self):\n- self.message = AggregateStatsReply()\n+ self.message = aggregate_stats_reply.AggregateStatsReply()\n self.message.packet_count = 5\n self.message.byte_count = 1\n self.message.flow_count = 8\ndiff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py\nindex 8e4be10..ca563fe 100644\n--- a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py\n@@ -2,13 +2,13 @@ import unittest\n \n from pyof.v0x01.common import flow_match\n from pyof.v0x01.common import phy_port\n-from pyof.v0x01.controller2switch.common import AggregateStatsRequest\n+from pyof.v0x01.controller2switch import aggregate_stats_request\n \n \n class TestAggregateStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = AggregateStatsRequest()\n+ self.message = aggregate_stats_request.AggregateStatsRequest()\n self.message.match = flow_match.Match()\n self.message.table_id = 1\n self.message.out_port = phy_port.Port.OFPP_NONE\ndiff --git a/tests/v0x01/test_controller2switch/test_desc_stats.py b/tests/v0x01/test_controller2switch/test_desc_stats.py\nindex 4f13f97..5ea6422 100644\n--- a/tests/v0x01/test_controller2switch/test_desc_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_desc_stats.py\n@@ -1,6 +1,6 @@\n import unittest\n \n-from pyof.v0x01.controller2switch.common import DescStats\n+from pyof.v0x01.controller2switch import desc_stats\n from pyof.v0x01.foundation import base\n \n \n@@ -8,7 +8,7 @@ class TestDescStats(unittest.TestCase):\n \n def setUp(self):\n content = bytes('A' * base.DESC_STR_LEN, 'utf-8')\n- self.message = DescStats()\n+ self.message = desc_stats.DescStats()\n self.message.mfr_desc = content\n self.message.hw_desc = content\n self.message.sw_desc = content\ndiff --git a/tests/v0x01/test_controller2switch/test_flow_stats.py b/tests/v0x01/test_controller2switch/test_flow_stats.py\nindex 2a04c07..1de34ab 100644\n--- a/tests/v0x01/test_controller2switch/test_flow_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_flow_stats.py\n@@ -1,13 +1,13 @@\n import unittest\n \n from pyof.v0x01.common import flow_match\n-from pyof.v0x01.controller2switch.common import FlowStats\n+from pyof.v0x01.controller2switch import flow_stats\n \n \n class TestFlowStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = FlowStats()\n+ self.message = flow_stats.FlowStats()\n self.message.length = 160\n self.message.table_id = 1\n self.message.match = flow_match.Match()\ndiff --git a/tests/v0x01/test_controller2switch/test_flow_stats_request.py b/tests/v0x01/test_controller2switch/test_flow_stats_request.py\nindex 2a6f3fb..85a33bb 100644\n--- a/tests/v0x01/test_controller2switch/test_flow_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_flow_stats_request.py\n@@ -1,13 +1,13 @@\n import unittest\n \n from pyof.v0x01.common import flow_match\n-from pyof.v0x01.controller2switch.common import FlowStatsRequest\n+from pyof.v0x01.controller2switch import flow_stats_request\n \n \n class TestFlowStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = FlowStatsRequest()\n+ self.message = flow_stats_request.FlowStatsRequest()\n self.message.match = flow_match.Match()\n self.message.table_id = 1\n self.message.out_port = 80\ndiff --git a/tests/v0x01/test_controller2switch/test_port_stats.py b/tests/v0x01/test_controller2switch/test_port_stats.py\nindex e6f4b55..7a58485 100644\n--- a/tests/v0x01/test_controller2switch/test_port_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_port_stats.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch.common import PortStats\n+from pyof.v0x01.controller2switch import port_stats\n \n \n class TestPortStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = PortStats()\n+ self.message = port_stats.PortStats()\n self.message.port_no = 80\n self.message.rx_packets = 5\n self.message.tx_packets = 10\ndiff --git a/tests/v0x01/test_controller2switch/test_port_stats_request.py b/tests/v0x01/test_controller2switch/test_port_stats_request.py\nindex 8025055..e0454dc 100644\n--- a/tests/v0x01/test_controller2switch/test_port_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_port_stats_request.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch.common import PortStatsRequest \n+from pyof.v0x01.controller2switch import port_stats_request\n \n \n class TestPortStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = PortStatsRequest()\n+ self.message = port_stats_request.PortStatsRequest()\n self.message.port_no = 80\n \n def test_get_size(self):\ndiff --git a/tests/v0x01/test_controller2switch/test_queue_stats.py b/tests/v0x01/test_controller2switch/test_queue_stats.py\nindex b1f1219..fb03ee7 100644\n--- a/tests/v0x01/test_controller2switch/test_queue_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_queue_stats.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch.common import QueueStats\n+from pyof.v0x01.controller2switch import queue_stats\n \n \n class TestQueueStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = QueueStats()\n+ self.message = queue_stats.QueueStats()\n self.message.port_no = 80\n self.message.queue_id = 5\n self.message.tx_bytes = 1\ndiff --git a/tests/v0x01/test_controller2switch/test_queue_stats_request.py b/tests/v0x01/test_controller2switch/test_queue_stats_request.py\nindex 2f95381..80cad68 100644\n--- a/tests/v0x01/test_controller2switch/test_queue_stats_request.py\n+++ b/tests/v0x01/test_controller2switch/test_queue_stats_request.py\n@@ -1,12 +1,12 @@\n import unittest\n \n-from pyof.v0x01.controller2switch.common import QueueStatsRequest\n+from pyof.v0x01.controller2switch import queue_stats_request\n \n \n class TestQueueStatsRequest(unittest.TestCase):\n \n def setUp(self):\n- self.message = QueueStatsRequest()\n+ self.message = queue_stats_request.QueueStatsRequest()\n self.message.port_no = 80\n self.message.queue_id = 5\n \ndiff --git a/tests/v0x01/test_controller2switch/test_table_stats.py b/tests/v0x01/test_controller2switch/test_table_stats.py\nindex 39888b5..353f6de 100644\n--- a/tests/v0x01/test_controller2switch/test_table_stats.py\n+++ b/tests/v0x01/test_controller2switch/test_table_stats.py\n@@ -1,14 +1,14 @@\n import unittest\n \n from pyof.v0x01.common import flow_match\n-from pyof.v0x01.controller2switch.common import TableStats\n+from pyof.v0x01.controller2switch import table_stats\n from pyof.v0x01.foundation import base\n \n \n class TestTableStats(unittest.TestCase):\n \n def setUp(self):\n- self.message = TableStats()\n+ self.message = table_stats.TableStats()\n self.message.table_id = 1\n self.message.name = bytes('X' * base.OFP_MAX_TABLE_NAME_LEN, 'utf-8')\n self.message.wildcards = flow_match.FlowWildCards.OFPFW_TP_DST\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_added_files\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 3,\n \"issue_text_score\": 2,\n \"test_score\": 2\n },\n \"num_modified_files\": 6\n}"},"version":{"kind":"string","value":"unknown"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"pytest\",\n \"pip_packages\": [\n \"coverage\",\n \"pytest\",\n \"pytest-cov\",\n \"pytest-xdist\",\n \"pytest-mock\",\n \"pytest-asyncio\"\n ],\n \"pre_install\": null,\n \"python\": \"3.9\",\n \"reqs_path\": null,\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"coverage==7.8.0\nexceptiongroup @ file:///croot/exceptiongroup_1706031385326/work\nexecnet==2.1.1\niniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work\n-e git+https://github.com/kytos/python-openflow.git@545ae8a73dcec2e67cf854b21c44e692692f71dc#egg=Kytos_OpenFlow_Parser_library\npackaging @ file:///croot/packaging_1734472117206/work\npluggy @ file:///croot/pluggy_1733169602837/work\npytest @ file:///croot/pytest_1738938843180/work\npytest-asyncio==0.26.0\npytest-cov==6.0.0\npytest-mock==3.14.0\npytest-xdist==3.6.1\ntomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work\ntyping_extensions==4.13.0\n"},"environment":{"kind":"string","value":"name: python-openflow\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - exceptiongroup=1.2.0=py39h06a4308_0\n - iniconfig=1.1.1=pyhd3eb1b0_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - packaging=24.2=py39h06a4308_0\n - pip=25.0=py39h06a4308_0\n - pluggy=1.5.0=py39h06a4308_0\n - pytest=8.3.4=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tomli=2.0.1=py39h06a4308_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - coverage==7.8.0\n - execnet==2.1.1\n - pytest-asyncio==0.26.0\n - pytest-cov==6.0.0\n - pytest-mock==3.14.0\n - pytest-xdist==3.6.1\n - typing-extensions==4.13.0\nprefix: /opt/conda/envs/python-openflow\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py::TestAggregateStatsReply::test_get_size","tests/v0x01/test_controller2switch/test_aggregate_stats_request.py::TestAggregateStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_desc_stats.py::TestDescStats::test_get_size","tests/v0x01/test_controller2switch/test_flow_stats.py::TestFlowStats::test_get_size","tests/v0x01/test_controller2switch/test_flow_stats_request.py::TestFlowStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_port_stats.py::TestPortStats::test_get_size","tests/v0x01/test_controller2switch/test_port_stats_request.py::TestPortStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_queue_stats.py::TestQueueStats::test_get_size","tests/v0x01/test_controller2switch/test_queue_stats_request.py::TestQueueStatsRequest::test_get_size","tests/v0x01/test_controller2switch/test_table_stats.py::TestTableStats::test_get_size"],"string":"[\n \"tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py::TestAggregateStatsReply::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_aggregate_stats_request.py::TestAggregateStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_desc_stats.py::TestDescStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_flow_stats.py::TestFlowStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_flow_stats_request.py::TestFlowStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_port_stats.py::TestPortStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_port_stats_request.py::TestPortStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_queue_stats.py::TestQueueStats::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_queue_stats_request.py::TestQueueStatsRequest::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_table_stats.py::TestTableStats::test_get_size\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":577,"string":"577"}}},{"rowIdx":577,"cells":{"instance_id":{"kind":"string","value":"falconry__falcon-820"},"base_commit":{"kind":"string","value":"50b1759ee7f7b54a872c01c85152f8648e350399"},"created_at":{"kind":"string","value":"2016-06-07 21:07:32"},"environment_setup_commit":{"kind":"string","value":"67d61029847cbf59e4053c8a424df4f9f87ad36f"},"hints_text":{"kind":"string","value":"kgriffs: Looks like we accidentally had some overlap in effort between #729 and #811. I attempted to combine the two into a new PR with a few tweeks to param naming and docstrings. Everyone please take a look and provide feedback. Thanks!\ncodecov-io: ## [Current coverage][cc-pull] is **100%**\n> Merging [#820][cc-pull] into [master][cc-base-branch] will not change coverage\n\n```diff\n@@ master #820 diff @@\n==========================================\n Files 29 29 \n Lines 1789 1799 +10 \n Methods 0 0 \n Messages 0 0 \n Branches 299 303 +4 \n==========================================\n+ Hits 1789 1799 +10 \n Misses 0 0 \n Partials 0 0 \n```\n\n> Powered by [Codecov](https://codecov.io?src=pr). Last updated by [cf3cb50...d4e630a][cc-compare]\n[cc-base-branch]: https://codecov.io/gh/falconry/falcon/branch/master?src=pr\n[cc-compare]: https://codecov.io/gh/falconry/falcon/compare/cf3cb5029a51d4b7c980c7851328a02046db9b3e...d4e630a70cd1774519851a78a1d1fb80a83e8b7e\n[cc-pull]: https://codecov.io/gh/falconry/falcon/pull/820?src=pr\norcsly: Looks good, thanks!\njmvrbanac: :+1: \nqwesda: The parameter name `csv` for the `parse_query_string` could have a more descriptive name. `parse_qs_csv` sounds logical to me, since the option general option is called `auto_parse_qs_csv`.\r\n\r\nOne evaluation in `parse_query_string` can be short-circuited:\r\n[https://github.com/falconry/falcon/pull/820/files#diff-7d2a078ae72702ba816f18a9aa1c48b9R319](https://github.com/falconry/falcon/pull/820/files#diff-7d2a078ae72702ba816f18a9aa1c48b9R319)\r\n\r\nOtherwise it looks good.\nkgriffs: @qwesda since the method name already implies we are working with parsing query strings, is it necessary to also include that in the name of the kwarg?\nqwesda: @kgriffs: I just thought something more explicit would be more in line with `keep_blank_qs_values`, which is pretty verbose. Having one verbose param and one very non-verbose seemed weird. \nkgriffs: @qwesda, ah, good point! I'll switch to `parse_qs_csv` and we can see how that looks.\nkgriffs: @qwesda @jmvrbanac @orcsly I think this is ready for final review.\nqwesda: @kgriffs looks ok\norcsly: Yup looks good. Thanks!"},"patch":{"kind":"string","value":"diff --git a/falcon/request.py b/falcon/request.py\nindex 597ac80..7359991 100644\n--- a/falcon/request.py\n+++ b/falcon/request.py\n@@ -284,6 +284,7 @@ class Request(object):\n self._params = parse_query_string(\n self.query_string,\n keep_blank_qs_values=self.options.keep_blank_qs_values,\n+ parse_qs_csv=self.options.auto_parse_qs_csv,\n )\n \n else:\n@@ -1153,6 +1154,7 @@ class Request(object):\n extra_params = parse_query_string(\n body,\n keep_blank_qs_values=self.options.keep_blank_qs_values,\n+ parse_qs_csv=self.options.auto_parse_qs_csv,\n )\n \n self._params.update(extra_params)\n@@ -1190,8 +1192,11 @@ class RequestOptions(object):\n \"\"\"This class is a container for ``Request`` options.\n \n Attributes:\n- keep_blank_qs_values (bool): Set to ``True`` in order to retain\n- blank values in query string parameters (default ``False``).\n+ keep_blank_qs_values (bool): Set to ``True`` to keep query string\n+ fields even if they do not have a value (default ``False``).\n+ For comma-separated values, this option also determines\n+ whether or not empty elements in the parsed list are\n+ retained.\n auto_parse_form_urlencoded: Set to ``True`` in order to\n automatically consume the request stream and merge the\n results into the request's query string params when the\n@@ -1202,18 +1207,29 @@ class RequestOptions(object):\n Note:\n The character encoding for fields, before\n percent-encoding non-ASCII bytes, is assumed to be\n- UTF-8. The special `_charset_` field is ignored if present.\n+ UTF-8. The special `_charset_` field is ignored if\n+ present.\n \n Falcon expects form-encoded request bodies to be\n encoded according to the standard W3C algorithm (see\n also http://goo.gl/6rlcux).\n \n+ auto_parse_qs_csv: Set to ``False`` to treat commas in a query\n+ string value as literal characters, rather than as a comma-\n+ separated list (default ``True``). When this option is\n+ enabled, the value will be split on any non-percent-encoded\n+ commas. Disable this option when encoding lists as multiple\n+ occurrences of the same parameter, and when values may be\n+ encoded in alternative formats in which the comma character\n+ is significant.\n \"\"\"\n __slots__ = (\n 'keep_blank_qs_values',\n 'auto_parse_form_urlencoded',\n+ 'auto_parse_qs_csv',\n )\n \n def __init__(self):\n self.keep_blank_qs_values = False\n self.auto_parse_form_urlencoded = False\n+ self.auto_parse_qs_csv = True\ndiff --git a/falcon/util/misc.py b/falcon/util/misc.py\nindex 5b02f05..12eb481 100644\n--- a/falcon/util/misc.py\n+++ b/falcon/util/misc.py\n@@ -148,7 +148,7 @@ def http_date_to_dt(http_date, obs_date=False):\n raise ValueError('time data %r does not match known formats' % http_date)\n \n \n-def to_query_str(params):\n+def to_query_str(params, comma_delimited_lists=True):\n \"\"\"Converts a dictionary of params to a query string.\n \n Args:\n@@ -157,6 +157,10 @@ def to_query_str(params):\n something that can be converted into a ``str``. If `params`\n is a ``list``, it will be converted to a comma-delimited string\n of values (e.g., 'thing=1,2,3')\n+ comma_delimited_lists (bool, default ``True``):\n+ If set to ``False`` encode lists by specifying multiple instances\n+ of the parameter (e.g., 'thing=1&thing=2&thing=3')\n+\n \n Returns:\n str: A URI query string including the '?' prefix, or an empty string\n@@ -175,7 +179,20 @@ def to_query_str(params):\n elif v is False:\n v = 'false'\n elif isinstance(v, list):\n- v = ','.join(map(str, v))\n+ if comma_delimited_lists:\n+ v = ','.join(map(str, v))\n+ else:\n+ for list_value in v:\n+ if list_value is True:\n+ list_value = 'true'\n+ elif list_value is False:\n+ list_value = 'false'\n+ else:\n+ list_value = str(list_value)\n+\n+ query_str += k + '=' + list_value + '&'\n+\n+ continue\n else:\n v = str(v)\n \ndiff --git a/falcon/util/uri.py b/falcon/util/uri.py\nindex 2f68ec9..63ca45e 100644\n--- a/falcon/util/uri.py\n+++ b/falcon/util/uri.py\n@@ -246,11 +246,12 @@ else:\n return decoded_uri.decode('utf-8', 'replace')\n \n \n-def parse_query_string(query_string, keep_blank_qs_values=False):\n+def parse_query_string(query_string, keep_blank_qs_values=False,\n+ parse_qs_csv=True):\n \"\"\"Parse a query string into a dict.\n \n Query string parameters are assumed to use standard form-encoding. Only\n- parameters with values are parsed. for example, given 'foo=bar&flag',\n+ parameters with values are returned. For example, given 'foo=bar&flag',\n this function would ignore 'flag' unless the `keep_blank_qs_values` option\n is set.\n \n@@ -269,8 +270,16 @@ def parse_query_string(query_string, keep_blank_qs_values=False):\n \n Args:\n query_string (str): The query string to parse.\n- keep_blank_qs_values (bool): If set to ``True``, preserves boolean\n- fields and fields with no content as blank strings.\n+ keep_blank_qs_values (bool): Set to ``True`` to return fields even if\n+ they do not have a value (default ``False``). For comma-separated\n+ values, this option also determines whether or not empty elements\n+ in the parsed list are retained.\n+ parse_qs_csv: Set to ``False`` in order to disable splitting query\n+ parameters on ``,`` (default ``True``). Depending on the user agent,\n+ encoding lists as multiple occurrences of the same parameter might\n+ be preferable. In this case, setting `parse_qs_csv` to ``False``\n+ will cause the framework to treat commas as literal characters in\n+ each occurring parameter value.\n \n Returns:\n dict: A dictionary of (*name*, *value*) pairs, one per query\n@@ -309,7 +318,7 @@ def parse_query_string(query_string, keep_blank_qs_values=False):\n params[k] = [old_value, decode(v)]\n \n else:\n- if ',' in v:\n+ if parse_qs_csv and ',' in v:\n # NOTE(kgriffs): Falcon supports a more compact form of\n # lists, in which the elements are comma-separated and\n # assigned to a single param instance. If it turns out that\n"},"problem_statement":{"kind":"string","value":"Add option to opt-out from comma separated value parsing\nI'm porting a project to Falcon and I stumbled upon an issue regarding its parsing of CSV values inside URIs. Let's say I have filtering engine that accepts queries such as this:\r\n\r\n http://great.dude/api/cars?query=added:yesterday,today+spoilers:red\r\n\r\nI obviously want to make `req.get_param('query')` return `'added:yesterday,today spoilers:red'`, and not `['added:yesterday', 'today spoilers:red']`.\r\n\r\nRight now this [isn't really configurable](https://github.com/falconry/falcon/blob/35987b2be85456f431bbda509e884a8b0b20ed11/falcon/util/uri.py#L312-L328) and I need to check if `get_param()` returns a `list` and then join it back if needed, which looks sort of silly. Fortunately, the ability to use custom request classes alleviates the issue to some extent.\r\n\r\nI see a few ways to improve things upstream:\r\n\r\n1. Offer explicit `get_param_as_string` that will possibly do `','.join(...)` under the hood.\r\n2. Add an option to disable this mechanism as an additional option to `Api`.\r\n3. Add an option to disable this mechanism as an additional option to `add_route()`.\r\n4. Change `get_param` to always return string.\r\n\r\nOption 4 makes the most sense to me, but it breaks BC. If option 4 is not feasible, I'd went with option 1."},"repo":{"kind":"string","value":"falconry/falcon"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_options.py b/tests/test_options.py\nindex b3d9812..a3b8b72 100644\n--- a/tests/test_options.py\n+++ b/tests/test_options.py\n@@ -1,16 +1,32 @@\n+import ddt\n+\n from falcon.request import RequestOptions\n import falcon.testing as testing\n \n \n+@ddt.ddt\n class TestRequestOptions(testing.TestBase):\n \n- def test_correct_options(self):\n+ def test_option_defaults(self):\n options = RequestOptions()\n+\n self.assertFalse(options.keep_blank_qs_values)\n- options.keep_blank_qs_values = True\n- self.assertTrue(options.keep_blank_qs_values)\n- options.keep_blank_qs_values = False\n- self.assertFalse(options.keep_blank_qs_values)\n+ self.assertFalse(options.auto_parse_form_urlencoded)\n+ self.assertTrue(options.auto_parse_qs_csv)\n+\n+ @ddt.data(\n+ 'keep_blank_qs_values',\n+ 'auto_parse_form_urlencoded',\n+ 'auto_parse_qs_csv',\n+ )\n+ def test_options_toggle(self, option_name):\n+ options = RequestOptions()\n+\n+ setattr(options, option_name, True)\n+ self.assertTrue(getattr(options, option_name))\n+\n+ setattr(options, option_name, False)\n+ self.assertFalse(getattr(options, option_name))\n \n def test_incorrect_options(self):\n options = RequestOptions()\ndiff --git a/tests/test_query_params.py b/tests/test_query_params.py\nindex c588f23..62c906d 100644\n--- a/tests/test_query_params.py\n+++ b/tests/test_query_params.py\n@@ -65,6 +65,60 @@ class _TestQueryParams(testing.TestBase):\n self.assertEqual(req.get_param_as_list('id', int), [23, 42])\n self.assertEqual(req.get_param('q'), u'\\u8c46 \\u74e3')\n \n+ def test_option_auto_parse_qs_csv_simple_false(self):\n+ self.api.req_options.auto_parse_qs_csv = False\n+\n+ query_string = 'id=23,42,,&id=2'\n+ self.simulate_request('/', query_string=query_string)\n+\n+ req = self.resource.req\n+\n+ self.assertEqual(req.params['id'], [u'23,42,,', u'2'])\n+ self.assertIn(req.get_param('id'), [u'23,42,,', u'2'])\n+ self.assertEqual(req.get_param_as_list('id'), [u'23,42,,', u'2'])\n+\n+ def test_option_auto_parse_qs_csv_simple_true(self):\n+ self.api.req_options.auto_parse_qs_csv = True\n+\n+ query_string = 'id=23,42,,&id=2'\n+ self.simulate_request('/', query_string=query_string)\n+\n+ req = self.resource.req\n+\n+ self.assertEqual(req.params['id'], [u'23', u'42', u'2'])\n+ self.assertIn(req.get_param('id'), [u'23', u'42', u'2'])\n+ self.assertEqual(req.get_param_as_list('id', int), [23, 42, 2])\n+\n+ def test_option_auto_parse_qs_csv_complex_false(self):\n+ self.api.req_options.auto_parse_qs_csv = False\n+\n+ encoded_json = '%7B%22msg%22:%22Testing%201,2,3...%22,%22code%22:857%7D'\n+ decoded_json = '{\"msg\":\"Testing 1,2,3...\",\"code\":857}'\n+\n+ query_string = ('colors=red,green,blue&limit=1'\n+ '&list-ish1=f,,x&list-ish2=,0&list-ish3=a,,,b'\n+ '&empty1=&empty2=,&empty3=,,'\n+ '&thing=' + encoded_json)\n+\n+ self.simulate_request('/', query_string=query_string)\n+\n+ req = self.resource.req\n+\n+ self.assertIn(req.get_param('colors'), 'red,green,blue')\n+ self.assertEqual(req.get_param_as_list('colors'), [u'red,green,blue'])\n+\n+ self.assertEqual(req.get_param_as_list('limit'), ['1'])\n+\n+ self.assertEqual(req.get_param_as_list('empty1'), None)\n+ self.assertEqual(req.get_param_as_list('empty2'), [u','])\n+ self.assertEqual(req.get_param_as_list('empty3'), [u',,'])\n+\n+ self.assertEqual(req.get_param_as_list('list-ish1'), [u'f,,x'])\n+ self.assertEqual(req.get_param_as_list('list-ish2'), [u',0'])\n+ self.assertEqual(req.get_param_as_list('list-ish3'), [u'a,,,b'])\n+\n+ self.assertEqual(req.get_param('thing'), decoded_json)\n+\n def test_bad_percentage(self):\n query_string = 'x=%%20%+%&y=peregrine&z=%a%z%zz%1%20e'\n self.simulate_request('/', query_string=query_string)\ndiff --git a/tests/test_utils.py b/tests/test_utils.py\nindex 957a959..6b5f75d 100644\n--- a/tests/test_utils.py\n+++ b/tests/test_utils.py\n@@ -128,6 +128,16 @@ class TestFalconUtils(testtools.TestCase):\n falcon.to_query_str({'things': ['a', 'b']}),\n '?things=a,b')\n \n+ expected = ('?things=a&things=b&things=&things=None'\n+ '&things=true&things=false&things=0')\n+\n+ actual = falcon.to_query_str(\n+ {'things': ['a', 'b', '', None, True, False, 0]},\n+ comma_delimited_lists=False\n+ )\n+\n+ self.assertEqual(actual, expected)\n+\n def test_pack_query_params_several(self):\n garbage_in = {\n 'limit': 17,\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"merge_commit\",\n \"failed_lite_validators\": [\n \"has_hyperlinks\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 1,\n \"test_score\": 2\n },\n \"num_modified_files\": 3\n}"},"version":{"kind":"string","value":"1.0"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"nose\",\n \"ddt\",\n \"testtools\",\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"tools/test-requires\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\ncertifi==2021.5.30\ncharset-normalizer==2.0.12\ncoverage==6.2\nddt==1.7.2\n-e git+https://github.com/falconry/falcon.git@50b1759ee7f7b54a872c01c85152f8648e350399#egg=falcon\nfixtures==4.0.1\nidna==3.10\nimportlib-metadata==4.8.3\niniconfig==1.1.1\nnose==1.3.7\npackaging==21.3\npbr==6.1.1\npluggy==1.0.0\npy==1.11.0\npyparsing==3.1.4\npytest==7.0.1\npython-mimeparse==1.6.0\nPyYAML==6.0.1\nrequests==2.27.1\nsix==1.17.0\ntesttools==2.6.0\ntomli==1.2.3\ntyping_extensions==4.1.1\nurllib3==1.26.20\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: falcon\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - charset-normalizer==2.0.12\n - coverage==6.2\n - ddt==1.7.2\n - fixtures==4.0.1\n - idna==3.10\n - importlib-metadata==4.8.3\n - iniconfig==1.1.1\n - nose==1.3.7\n - packaging==21.3\n - pbr==6.1.1\n - pluggy==1.0.0\n - py==1.11.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - python-mimeparse==1.6.0\n - pyyaml==6.0.1\n - requests==2.27.1\n - six==1.17.0\n - testtools==2.6.0\n - tomli==1.2.3\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - zipp==3.6.0\nprefix: /opt/conda/envs/falcon\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_options.py::TestRequestOptions::test_option_defaults","tests/test_options.py::TestRequestOptions::test_options_toggle_3_auto_parse_qs_csv","tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_complex_false","tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_simple_false","tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_simple_true","tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_complex_false","tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_simple_false","tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_simple_true","tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_complex_false","tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_simple_false","tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_simple_true","tests/test_utils.py::TestFalconUtils::test_pack_query_params_one"],"string":"[\n \"tests/test_options.py::TestRequestOptions::test_option_defaults\",\n \"tests/test_options.py::TestRequestOptions::test_options_toggle_3_auto_parse_qs_csv\",\n \"tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_complex_false\",\n \"tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_simple_false\",\n \"tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_simple_true\",\n \"tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_complex_false\",\n \"tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_simple_false\",\n \"tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_simple_true\",\n \"tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_complex_false\",\n \"tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_simple_false\",\n \"tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_simple_true\",\n \"tests/test_utils.py::TestFalconUtils::test_pack_query_params_one\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":["tests/test_utils.py::TestFalconUtils::test_deprecated_decorator"],"string":"[\n \"tests/test_utils.py::TestFalconUtils::test_deprecated_decorator\"\n]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_options.py::TestRequestOptions::test_incorrect_options","tests/test_options.py::TestRequestOptions::test_options_toggle_1_keep_blank_qs_values","tests/test_options.py::TestRequestOptions::test_options_toggle_2_auto_parse_form_urlencoded","tests/test_query_params.py::_TestQueryParams::test_allowed_names","tests/test_query_params.py::_TestQueryParams::test_bad_percentage","tests/test_query_params.py::_TestQueryParams::test_blank","tests/test_query_params.py::_TestQueryParams::test_boolean","tests/test_query_params.py::_TestQueryParams::test_boolean_blank","tests/test_query_params.py::_TestQueryParams::test_get_date_invalid","tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param","tests/test_query_params.py::_TestQueryParams::test_get_date_store","tests/test_query_params.py::_TestQueryParams::test_get_date_valid","tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format","tests/test_query_params.py::_TestQueryParams::test_get_dict_invalid","tests/test_query_params.py::_TestQueryParams::test_get_dict_missing_param","tests/test_query_params.py::_TestQueryParams::test_get_dict_store","tests/test_query_params.py::_TestQueryParams::test_get_dict_valid","tests/test_query_params.py::_TestQueryParams::test_int","tests/test_query_params.py::_TestQueryParams::test_int_neg","tests/test_query_params.py::_TestQueryParams::test_list_transformer","tests/test_query_params.py::_TestQueryParams::test_list_type","tests/test_query_params.py::_TestQueryParams::test_list_type_blank","tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys","tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list","tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool","tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int","tests/test_query_params.py::_TestQueryParams::test_none","tests/test_query_params.py::_TestQueryParams::test_param_property","tests/test_query_params.py::_TestQueryParams::test_percent_encoded","tests/test_query_params.py::_TestQueryParams::test_required_1_get_param","tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int","tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool","tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list","tests/test_query_params.py::_TestQueryParams::test_simple","tests/test_query_params.py::PostQueryParams::test_allowed_names","tests/test_query_params.py::PostQueryParams::test_bad_percentage","tests/test_query_params.py::PostQueryParams::test_blank","tests/test_query_params.py::PostQueryParams::test_boolean","tests/test_query_params.py::PostQueryParams::test_boolean_blank","tests/test_query_params.py::PostQueryParams::test_explicitly_disable_auto_parse","tests/test_query_params.py::PostQueryParams::test_get_date_invalid","tests/test_query_params.py::PostQueryParams::test_get_date_missing_param","tests/test_query_params.py::PostQueryParams::test_get_date_store","tests/test_query_params.py::PostQueryParams::test_get_date_valid","tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format","tests/test_query_params.py::PostQueryParams::test_get_dict_invalid","tests/test_query_params.py::PostQueryParams::test_get_dict_missing_param","tests/test_query_params.py::PostQueryParams::test_get_dict_store","tests/test_query_params.py::PostQueryParams::test_get_dict_valid","tests/test_query_params.py::PostQueryParams::test_int","tests/test_query_params.py::PostQueryParams::test_int_neg","tests/test_query_params.py::PostQueryParams::test_list_transformer","tests/test_query_params.py::PostQueryParams::test_list_type","tests/test_query_params.py::PostQueryParams::test_list_type_blank","tests/test_query_params.py::PostQueryParams::test_multiple_form_keys","tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list","tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool","tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int","tests/test_query_params.py::PostQueryParams::test_non_ascii","tests/test_query_params.py::PostQueryParams::test_none","tests/test_query_params.py::PostQueryParams::test_param_property","tests/test_query_params.py::PostQueryParams::test_percent_encoded","tests/test_query_params.py::PostQueryParams::test_required_1_get_param","tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int","tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool","tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list","tests/test_query_params.py::PostQueryParams::test_simple","tests/test_query_params.py::GetQueryParams::test_allowed_names","tests/test_query_params.py::GetQueryParams::test_bad_percentage","tests/test_query_params.py::GetQueryParams::test_blank","tests/test_query_params.py::GetQueryParams::test_boolean","tests/test_query_params.py::GetQueryParams::test_boolean_blank","tests/test_query_params.py::GetQueryParams::test_get_date_invalid","tests/test_query_params.py::GetQueryParams::test_get_date_missing_param","tests/test_query_params.py::GetQueryParams::test_get_date_store","tests/test_query_params.py::GetQueryParams::test_get_date_valid","tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format","tests/test_query_params.py::GetQueryParams::test_get_dict_invalid","tests/test_query_params.py::GetQueryParams::test_get_dict_missing_param","tests/test_query_params.py::GetQueryParams::test_get_dict_store","tests/test_query_params.py::GetQueryParams::test_get_dict_valid","tests/test_query_params.py::GetQueryParams::test_int","tests/test_query_params.py::GetQueryParams::test_int_neg","tests/test_query_params.py::GetQueryParams::test_list_transformer","tests/test_query_params.py::GetQueryParams::test_list_type","tests/test_query_params.py::GetQueryParams::test_list_type_blank","tests/test_query_params.py::GetQueryParams::test_multiple_form_keys","tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list","tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool","tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int","tests/test_query_params.py::GetQueryParams::test_none","tests/test_query_params.py::GetQueryParams::test_param_property","tests/test_query_params.py::GetQueryParams::test_percent_encoded","tests/test_query_params.py::GetQueryParams::test_required_1_get_param","tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int","tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool","tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list","tests/test_query_params.py::GetQueryParams::test_simple","tests/test_query_params.py::PostQueryParamsDefaultBehavior::test_dont_auto_parse_by_default","tests/test_utils.py::TestFalconUtils::test_dt_to_http","tests/test_utils.py::TestFalconUtils::test_get_http_status","tests/test_utils.py::TestFalconUtils::test_http_date_to_dt","tests/test_utils.py::TestFalconUtils::test_http_now","tests/test_utils.py::TestFalconUtils::test_pack_query_params_none","tests/test_utils.py::TestFalconUtils::test_pack_query_params_several","tests/test_utils.py::TestFalconUtils::test_parse_host","tests/test_utils.py::TestFalconUtils::test_parse_query_string","tests/test_utils.py::TestFalconUtils::test_prop_uri_decode_models_stdlib_unquote_plus","tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_models_stdlib_quote","tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_value_models_stdlib_quote_safe_tilde","tests/test_utils.py::TestFalconUtils::test_uri_decode","tests/test_utils.py::TestFalconUtils::test_uri_encode","tests/test_utils.py::TestFalconUtils::test_uri_encode_value","tests/test_utils.py::TestFalconTesting::test_decode_empty_result","tests/test_utils.py::TestFalconTesting::test_httpnow_alias_for_backwards_compat","tests/test_utils.py::TestFalconTesting::test_none_header_value_in_create_environ","tests/test_utils.py::TestFalconTesting::test_path_escape_chars_in_create_environ","tests/test_utils.py::TestFalconTestCase::test_cached_text_in_result","tests/test_utils.py::TestFalconTestCase::test_path_must_start_with_slash","tests/test_utils.py::TestFalconTestCase::test_query_string","tests/test_utils.py::TestFalconTestCase::test_query_string_in_path","tests/test_utils.py::TestFalconTestCase::test_query_string_no_question","tests/test_utils.py::TestFalconTestCase::test_simple_resource_body_json_xor","tests/test_utils.py::TestFalconTestCase::test_status","tests/test_utils.py::TestFalconTestCase::test_wsgi_iterable_not_closeable","tests/test_utils.py::FancyTestCase::test_something"],"string":"[\n \"tests/test_options.py::TestRequestOptions::test_incorrect_options\",\n \"tests/test_options.py::TestRequestOptions::test_options_toggle_1_keep_blank_qs_values\",\n \"tests/test_options.py::TestRequestOptions::test_options_toggle_2_auto_parse_form_urlencoded\",\n \"tests/test_query_params.py::_TestQueryParams::test_allowed_names\",\n \"tests/test_query_params.py::_TestQueryParams::test_bad_percentage\",\n \"tests/test_query_params.py::_TestQueryParams::test_blank\",\n \"tests/test_query_params.py::_TestQueryParams::test_boolean\",\n \"tests/test_query_params.py::_TestQueryParams::test_boolean_blank\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_date_invalid\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_date_store\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_date_valid\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_dict_invalid\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_dict_missing_param\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_dict_store\",\n \"tests/test_query_params.py::_TestQueryParams::test_get_dict_valid\",\n \"tests/test_query_params.py::_TestQueryParams::test_int\",\n \"tests/test_query_params.py::_TestQueryParams::test_int_neg\",\n \"tests/test_query_params.py::_TestQueryParams::test_list_transformer\",\n \"tests/test_query_params.py::_TestQueryParams::test_list_type\",\n \"tests/test_query_params.py::_TestQueryParams::test_list_type_blank\",\n \"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys\",\n \"tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list\",\n \"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool\",\n \"tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int\",\n \"tests/test_query_params.py::_TestQueryParams::test_none\",\n \"tests/test_query_params.py::_TestQueryParams::test_param_property\",\n \"tests/test_query_params.py::_TestQueryParams::test_percent_encoded\",\n \"tests/test_query_params.py::_TestQueryParams::test_required_1_get_param\",\n \"tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int\",\n \"tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool\",\n \"tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list\",\n \"tests/test_query_params.py::_TestQueryParams::test_simple\",\n \"tests/test_query_params.py::PostQueryParams::test_allowed_names\",\n \"tests/test_query_params.py::PostQueryParams::test_bad_percentage\",\n \"tests/test_query_params.py::PostQueryParams::test_blank\",\n \"tests/test_query_params.py::PostQueryParams::test_boolean\",\n \"tests/test_query_params.py::PostQueryParams::test_boolean_blank\",\n \"tests/test_query_params.py::PostQueryParams::test_explicitly_disable_auto_parse\",\n \"tests/test_query_params.py::PostQueryParams::test_get_date_invalid\",\n \"tests/test_query_params.py::PostQueryParams::test_get_date_missing_param\",\n \"tests/test_query_params.py::PostQueryParams::test_get_date_store\",\n \"tests/test_query_params.py::PostQueryParams::test_get_date_valid\",\n \"tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format\",\n \"tests/test_query_params.py::PostQueryParams::test_get_dict_invalid\",\n \"tests/test_query_params.py::PostQueryParams::test_get_dict_missing_param\",\n \"tests/test_query_params.py::PostQueryParams::test_get_dict_store\",\n \"tests/test_query_params.py::PostQueryParams::test_get_dict_valid\",\n \"tests/test_query_params.py::PostQueryParams::test_int\",\n \"tests/test_query_params.py::PostQueryParams::test_int_neg\",\n \"tests/test_query_params.py::PostQueryParams::test_list_transformer\",\n \"tests/test_query_params.py::PostQueryParams::test_list_type\",\n \"tests/test_query_params.py::PostQueryParams::test_list_type_blank\",\n \"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys\",\n \"tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list\",\n \"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool\",\n \"tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int\",\n \"tests/test_query_params.py::PostQueryParams::test_non_ascii\",\n \"tests/test_query_params.py::PostQueryParams::test_none\",\n \"tests/test_query_params.py::PostQueryParams::test_param_property\",\n \"tests/test_query_params.py::PostQueryParams::test_percent_encoded\",\n \"tests/test_query_params.py::PostQueryParams::test_required_1_get_param\",\n \"tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int\",\n \"tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool\",\n \"tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list\",\n \"tests/test_query_params.py::PostQueryParams::test_simple\",\n \"tests/test_query_params.py::GetQueryParams::test_allowed_names\",\n \"tests/test_query_params.py::GetQueryParams::test_bad_percentage\",\n \"tests/test_query_params.py::GetQueryParams::test_blank\",\n \"tests/test_query_params.py::GetQueryParams::test_boolean\",\n \"tests/test_query_params.py::GetQueryParams::test_boolean_blank\",\n \"tests/test_query_params.py::GetQueryParams::test_get_date_invalid\",\n \"tests/test_query_params.py::GetQueryParams::test_get_date_missing_param\",\n \"tests/test_query_params.py::GetQueryParams::test_get_date_store\",\n \"tests/test_query_params.py::GetQueryParams::test_get_date_valid\",\n \"tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format\",\n \"tests/test_query_params.py::GetQueryParams::test_get_dict_invalid\",\n \"tests/test_query_params.py::GetQueryParams::test_get_dict_missing_param\",\n \"tests/test_query_params.py::GetQueryParams::test_get_dict_store\",\n \"tests/test_query_params.py::GetQueryParams::test_get_dict_valid\",\n \"tests/test_query_params.py::GetQueryParams::test_int\",\n \"tests/test_query_params.py::GetQueryParams::test_int_neg\",\n \"tests/test_query_params.py::GetQueryParams::test_list_transformer\",\n \"tests/test_query_params.py::GetQueryParams::test_list_type\",\n \"tests/test_query_params.py::GetQueryParams::test_list_type_blank\",\n \"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys\",\n \"tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list\",\n \"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool\",\n \"tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int\",\n \"tests/test_query_params.py::GetQueryParams::test_none\",\n \"tests/test_query_params.py::GetQueryParams::test_param_property\",\n \"tests/test_query_params.py::GetQueryParams::test_percent_encoded\",\n \"tests/test_query_params.py::GetQueryParams::test_required_1_get_param\",\n \"tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int\",\n \"tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool\",\n \"tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list\",\n \"tests/test_query_params.py::GetQueryParams::test_simple\",\n \"tests/test_query_params.py::PostQueryParamsDefaultBehavior::test_dont_auto_parse_by_default\",\n \"tests/test_utils.py::TestFalconUtils::test_dt_to_http\",\n \"tests/test_utils.py::TestFalconUtils::test_get_http_status\",\n \"tests/test_utils.py::TestFalconUtils::test_http_date_to_dt\",\n \"tests/test_utils.py::TestFalconUtils::test_http_now\",\n \"tests/test_utils.py::TestFalconUtils::test_pack_query_params_none\",\n \"tests/test_utils.py::TestFalconUtils::test_pack_query_params_several\",\n \"tests/test_utils.py::TestFalconUtils::test_parse_host\",\n \"tests/test_utils.py::TestFalconUtils::test_parse_query_string\",\n \"tests/test_utils.py::TestFalconUtils::test_prop_uri_decode_models_stdlib_unquote_plus\",\n \"tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_models_stdlib_quote\",\n \"tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_value_models_stdlib_quote_safe_tilde\",\n \"tests/test_utils.py::TestFalconUtils::test_uri_decode\",\n \"tests/test_utils.py::TestFalconUtils::test_uri_encode\",\n \"tests/test_utils.py::TestFalconUtils::test_uri_encode_value\",\n \"tests/test_utils.py::TestFalconTesting::test_decode_empty_result\",\n \"tests/test_utils.py::TestFalconTesting::test_httpnow_alias_for_backwards_compat\",\n \"tests/test_utils.py::TestFalconTesting::test_none_header_value_in_create_environ\",\n \"tests/test_utils.py::TestFalconTesting::test_path_escape_chars_in_create_environ\",\n \"tests/test_utils.py::TestFalconTestCase::test_cached_text_in_result\",\n \"tests/test_utils.py::TestFalconTestCase::test_path_must_start_with_slash\",\n \"tests/test_utils.py::TestFalconTestCase::test_query_string\",\n \"tests/test_utils.py::TestFalconTestCase::test_query_string_in_path\",\n \"tests/test_utils.py::TestFalconTestCase::test_query_string_no_question\",\n \"tests/test_utils.py::TestFalconTestCase::test_simple_resource_body_json_xor\",\n \"tests/test_utils.py::TestFalconTestCase::test_status\",\n \"tests/test_utils.py::TestFalconTestCase::test_wsgi_iterable_not_closeable\",\n \"tests/test_utils.py::FancyTestCase::test_something\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":578,"string":"578"}}},{"rowIdx":578,"cells":{"instance_id":{"kind":"string","value":"scrapy__scrapy-2038"},"base_commit":{"kind":"string","value":"b7925e42202d79d2ba9d00b6aded3a451c92fe81"},"created_at":{"kind":"string","value":"2016-06-08 14:57:23"},"environment_setup_commit":{"kind":"string","value":"a975a50558cd78a1573bee2e957afcb419fd1bd6"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/scrapy/utils/url.py b/scrapy/utils/url.py\nindex c80fc6e70..406eb5843 100644\n--- a/scrapy/utils/url.py\n+++ b/scrapy/utils/url.py\n@@ -41,9 +41,16 @@ def url_has_any_extension(url, extensions):\n \n \n def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'):\n+ # IDNA encoding can fail for too long labels (>63 characters)\n+ # or missing labels (e.g. http://.example.com)\n+ try:\n+ netloc = parts.netloc.encode('idna')\n+ except UnicodeError:\n+ netloc = parts.netloc\n+\n return (\n to_native_str(parts.scheme),\n- to_native_str(parts.netloc.encode('idna')),\n+ to_native_str(netloc),\n \n # default encoding for path component SHOULD be UTF-8\n quote(to_bytes(parts.path, path_encoding), _safe_chars),\n"},"problem_statement":{"kind":"string","value":"Unicode Link Extractor\nWhen using the following to extract all of the links from a response:\r\n```\r\nself.link_extractor = LinkExtractor()\r\n...\r\nlinks = self.link_extractor.extract_links(response)\r\n```\r\n\r\nOn rare occasions, the following error is thrown:\r\n\r\n```\r\n2016-05-25 12:13:55,432 [root] [ERROR] Error on http://detroit.curbed.com/2016/5/5/11605132/tiny-house-designer-show, traceback: Traceback (most recent call last):\r\n File \"/usr/local/lib/python2.7/site-packages/twisted/internet/base.py\", line 1203, in mainLoop\r\n self.runUntilCurrent()\r\n File \"/usr/local/lib/python2.7/site-packages/twisted/internet/base.py\", line 825, in runUntilCurrent\r\n call.func(*call.args, **call.kw)\r\n File \"/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py\", line 393, in callback\r\n self._startRunCallbacks(result)\r\n File \"/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py\", line 501, in _startRunCallbacks\r\n self._runCallbacks()\r\n--- ---\r\n File \"/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py\", line 588, in _runCallbacks\r\n current.result = callback(current.result, *args, **kw)\r\n File \"/var/www/html/DomainCrawler/DomainCrawler/spiders/hybrid_spider.py\", line 223, in parse\r\n items.extend(self._extract_requests(response))\r\n File \"/var/www/html/DomainCrawler/DomainCrawler/spiders/hybrid_spider.py\", line 477, in _extract_requests\r\n links = self.link_extractor.extract_links(response)\r\n File \"/usr/local/lib/python2.7/site-packages/scrapy/linkextractors/lxmlhtml.py\", line 111, in extract_links\r\n all_links.extend(self._process_links(links))\r\n File \"/usr/local/lib/python2.7/site-packages/scrapy/linkextractors/__init__.py\", line 103, in _process_links\r\n link.url = canonicalize_url(urlparse(link.url))\r\n File \"/usr/local/lib/python2.7/site-packages/scrapy/utils/url.py\", line 85, in canonicalize_url\r\n parse_url(url), encoding=encoding)\r\n File \"/usr/local/lib/python2.7/site-packages/scrapy/utils/url.py\", line 46, in _safe_ParseResult\r\n to_native_str(parts.netloc.encode('idna')),\r\n File \"/usr/local/lib/python2.7/encodings/idna.py\", line 164, in encode\r\n result.append(ToASCII(label))\r\n File \"/usr/local/lib/python2.7/encodings/idna.py\", line 73, in ToASCII\r\n raise UnicodeError(\"label empty or too long\")\r\nexceptions.UnicodeError: label empty or too long\r\n```\r\n\r\nI was able to find some information concerning the error from [here](http://stackoverflow.com/questions/25103126/label-empty-or-too-long-python-urllib2).\r\nMy question is: What is the best way to handle this? Even if there is one bad link in the response, I'd want all of the other good links to be extracted."},"repo":{"kind":"string","value":"scrapy/scrapy"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_utils_url.py b/tests/test_utils_url.py\nindex 1fc3a3510..b4819874d 100644\n--- a/tests/test_utils_url.py\n+++ b/tests/test_utils_url.py\n@@ -265,6 +265,20 @@ class CanonicalizeUrlTest(unittest.TestCase):\n # without encoding, already canonicalized URL is canonicalized identically\n self.assertEqual(canonicalize_url(canonicalized), canonicalized)\n \n+ def test_canonicalize_url_idna_exceptions(self):\n+ # missing DNS label\n+ self.assertEqual(\n+ canonicalize_url(u\"http://.example.com/résumé?q=résumé\"),\n+ \"http://.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9\")\n+\n+ # DNS label too long\n+ self.assertEqual(\n+ canonicalize_url(\n+ u\"http://www.{label}.com/résumé?q=résumé\".format(\n+ label=u\"example\"*11)),\n+ \"http://www.{label}.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9\".format(\n+ label=u\"example\"*11))\n+\n \n class AddHttpIfNoScheme(unittest.TestCase):\n \n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_hyperlinks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 2,\n \"test_score\": 0\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"1.1"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev\"\n ],\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\nAutomat==22.10.0\ncertifi==2021.5.30\ncffi==1.15.1\nconstantly==15.1.0\ncryptography==40.0.2\ncssselect==1.1.0\nhyperlink==21.0.0\nidna==3.10\nimportlib-metadata==4.8.3\nincremental==22.10.0\niniconfig==1.1.1\nlxml==5.3.1\npackaging==21.3\nparsel==1.6.0\npluggy==1.0.0\npy==1.11.0\npyasn1==0.5.1\npyasn1-modules==0.3.0\npycparser==2.21\nPyDispatcher==2.0.7\npyOpenSSL==23.2.0\npyparsing==3.1.4\npytest==7.0.1\nqueuelib==1.6.2\n-e git+https://github.com/scrapy/scrapy.git@b7925e42202d79d2ba9d00b6aded3a451c92fe81#egg=Scrapy\nservice-identity==21.1.0\nsix==1.17.0\ntomli==1.2.3\nTwisted==22.4.0\ntyping_extensions==4.1.1\nw3lib==2.0.1\nzipp==3.6.0\nzope.interface==5.5.2\n"},"environment":{"kind":"string","value":"name: scrapy\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - automat==22.10.0\n - cffi==1.15.1\n - constantly==15.1.0\n - cryptography==40.0.2\n - cssselect==1.1.0\n - hyperlink==21.0.0\n - idna==3.10\n - importlib-metadata==4.8.3\n - incremental==22.10.0\n - iniconfig==1.1.1\n - lxml==5.3.1\n - packaging==21.3\n - parsel==1.6.0\n - pluggy==1.0.0\n - py==1.11.0\n - pyasn1==0.5.1\n - pyasn1-modules==0.3.0\n - pycparser==2.21\n - pydispatcher==2.0.7\n - pyopenssl==23.2.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - queuelib==1.6.2\n - service-identity==21.1.0\n - six==1.17.0\n - tomli==1.2.3\n - twisted==22.4.0\n - typing-extensions==4.1.1\n - w3lib==2.0.1\n - zipp==3.6.0\n - zope-interface==5.5.2\nprefix: /opt/conda/envs/scrapy\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions"],"string":"[\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_any_domain","tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider","tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_class_attributes","tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains","tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains_class_attributes","tests/test_utils_url.py::CanonicalizeUrlTest::test_append_missing_path","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_idns","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding","tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed","tests/test_utils_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive","tests/test_utils_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters","tests/test_utils_url.py::CanonicalizeUrlTest::test_keep_blank_values","tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths","tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments","tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths","tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments","tests/test_utils_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign","tests/test_utils_url.py::CanonicalizeUrlTest::test_remove_fragments","tests/test_utils_url.py::CanonicalizeUrlTest::test_return_str","tests/test_utils_url.py::CanonicalizeUrlTest::test_safe_characters_unicode","tests/test_utils_url.py::CanonicalizeUrlTest::test_sorting","tests/test_utils_url.py::CanonicalizeUrlTest::test_spaces","tests/test_utils_url.py::CanonicalizeUrlTest::test_typical_usage","tests/test_utils_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports","tests/test_utils_url.py::AddHttpIfNoScheme::test_add_scheme","tests/test_utils_url.py::AddHttpIfNoScheme::test_complete_url","tests/test_utils_url.py::AddHttpIfNoScheme::test_fragment","tests/test_utils_url.py::AddHttpIfNoScheme::test_path","tests/test_utils_url.py::AddHttpIfNoScheme::test_port","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_ftp","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_complete_url","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_fragment","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_path","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_port","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_query","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_username_password","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_without_subdomain","tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_https","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_complete_url","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_fragment","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_path","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_port","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_query","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_username_password","tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_without_subdomain","tests/test_utils_url.py::AddHttpIfNoScheme::test_query","tests/test_utils_url.py::AddHttpIfNoScheme::test_username_password","tests/test_utils_url.py::AddHttpIfNoScheme::test_without_subdomain","tests/test_utils_url.py::GuessSchemeTest::test_uri_001","tests/test_utils_url.py::GuessSchemeTest::test_uri_002","tests/test_utils_url.py::GuessSchemeTest::test_uri_003","tests/test_utils_url.py::GuessSchemeTest::test_uri_004","tests/test_utils_url.py::GuessSchemeTest::test_uri_005","tests/test_utils_url.py::GuessSchemeTest::test_uri_006","tests/test_utils_url.py::GuessSchemeTest::test_uri_007","tests/test_utils_url.py::GuessSchemeTest::test_uri_008","tests/test_utils_url.py::GuessSchemeTest::test_uri_009","tests/test_utils_url.py::GuessSchemeTest::test_uri_010","tests/test_utils_url.py::GuessSchemeTest::test_uri_011","tests/test_utils_url.py::GuessSchemeTest::test_uri_012","tests/test_utils_url.py::GuessSchemeTest::test_uri_013","tests/test_utils_url.py::GuessSchemeTest::test_uri_014","tests/test_utils_url.py::GuessSchemeTest::test_uri_015","tests/test_utils_url.py::GuessSchemeTest::test_uri_016","tests/test_utils_url.py::GuessSchemeTest::test_uri_017","tests/test_utils_url.py::GuessSchemeTest::test_uri_018","tests/test_utils_url.py::GuessSchemeTest::test_uri_019","tests/test_utils_url.py::GuessSchemeTest::test_uri_020"],"string":"[\n \"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_any_domain\",\n \"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider\",\n \"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_class_attributes\",\n \"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains\",\n \"tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains_class_attributes\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_append_missing_path\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_idns\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_keep_blank_values\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_remove_fragments\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_return_str\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_safe_characters_unicode\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_sorting\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_spaces\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_typical_usage\",\n \"tests/test_utils_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_add_scheme\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_complete_url\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_fragment\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_path\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_port\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_ftp\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_complete_url\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_fragment\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_path\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_port\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_query\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_username_password\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_without_subdomain\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_https\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_complete_url\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_fragment\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_path\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_port\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_query\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_username_password\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_without_subdomain\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_query\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_username_password\",\n \"tests/test_utils_url.py::AddHttpIfNoScheme::test_without_subdomain\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_001\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_002\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_003\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_004\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_005\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_006\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_007\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_008\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_009\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_010\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_011\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_012\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_013\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_014\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_015\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_016\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_017\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_018\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_019\",\n \"tests/test_utils_url.py::GuessSchemeTest::test_uri_020\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD 3-Clause \"New\" or \"Revised\" License"},"__index_level_0__":{"kind":"number","value":579,"string":"579"}}},{"rowIdx":579,"cells":{"instance_id":{"kind":"string","value":"mapbox__mapbox-sdk-py-128"},"base_commit":{"kind":"string","value":"2c11fdee6eee83ea82398cc0756ac7f35aada801"},"created_at":{"kind":"string","value":"2016-06-09 18:19:51"},"environment_setup_commit":{"kind":"string","value":"2c11fdee6eee83ea82398cc0756ac7f35aada801"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/docs/surface.md b/docs/surface.md\nindex 8fcbb77..c6e9676 100644\n--- a/docs/surface.md\n+++ b/docs/surface.md\n@@ -86,7 +86,7 @@ contours).\n ... polyline=True, zoom=12, interpolate=False)\n >>> points = response.geojson()\n >>> [f['properties']['ele'] for f in points['features']]\n-[None, None, None]\n+[2190, 2190, 2160]\n \n ```\n \ndiff --git a/mapbox/encoding.py b/mapbox/encoding.py\nindex 0674d51..6190ea6 100644\n--- a/mapbox/encoding.py\n+++ b/mapbox/encoding.py\n@@ -68,12 +68,13 @@ def encode_waypoints(features, min_limit=None, max_limit=None, precision=6):\n return ';'.join(coords)\n \n \n-def encode_polyline(features, zoom_level=18):\n+def encode_polyline(features):\n \"\"\"Encode and iterable of features as a polyline\n \"\"\"\n points = list(read_points(features))\n+ latlon_points = [(x[1], x[0]) for x in points]\n codec = PolylineCodec()\n- return codec.encode(points)\n+ return codec.encode(latlon_points)\n \n \n def encode_coordinates_json(features):\n"},"problem_statement":{"kind":"string","value":"Encoded polylines in wrong coordinate order\nCurrently, we take the geojson point array and encode the point directly in [lon, lat] order. Polylines should be [lat, lon]."},"repo":{"kind":"string","value":"mapbox/mapbox-sdk-py"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_encoding.py b/tests/test_encoding.py\nindex fa15f14..9326ae6 100644\n--- a/tests/test_encoding.py\n+++ b/tests/test_encoding.py\n@@ -113,7 +113,7 @@ def test_unknown_object():\n \n \n def test_encode_polyline():\n- expected = \"vdatOwp_~EhupD{xiA\"\n+ expected = \"wp_~EvdatO{xiAhupD\"\n assert expected == encode_polyline(gj_point_features)\n assert expected == encode_polyline(gj_multipoint_features)\n assert expected == encode_polyline(gj_line_features)\ndiff --git a/tests/test_surface.py b/tests/test_surface.py\nindex 05bd2c7..2ba08cd 100644\n--- a/tests/test_surface.py\n+++ b/tests/test_surface.py\n@@ -55,7 +55,7 @@ def test_surface_geojson():\n @responses.activate\n def test_surface_params():\n \n- params = \"&encoded_polyline=~kbkTss%60%7BEQeAHu%40&zoom=16&interpolate=false\"\n+ params = \"&encoded_polyline=ss%60%7BE~kbkTeAQu%40H&zoom=16&interpolate=false\"\n responses.add(\n responses.GET,\n 'https://api.mapbox.com/v4/surface/mapbox.mapbox-terrain-v1.json?access_token=pk.test&fields=ele&layer=contour&geojson=true' + params,\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_many_modified_files\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 0,\n \"test_score\": 0\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"0.8"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[test]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\",\n \"pytest-cov\"\n ],\n \"pre_install\": [\n \"pip install -U pip\"\n ],\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements/base.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\nboto3==1.23.10\nbotocore==1.26.10\nCacheControl==0.12.14\ncertifi==2021.5.30\ncharset-normalizer==2.0.12\nclick==8.0.4\nclick-plugins==1.1.1\ncligj==0.7.2\ncoverage==6.2\ncoveralls==3.3.1\ndistlib==0.3.9\ndocopt==0.6.2\nfilelock==3.4.1\nidna==3.10\nimportlib-metadata==4.8.3\nimportlib-resources==5.4.0\niniconfig==1.1.1\niso3166==2.1.1\njmespath==0.10.0\n-e git+https://github.com/mapbox/mapbox-sdk-py.git@2c11fdee6eee83ea82398cc0756ac7f35aada801#egg=mapbox\nmsgpack==1.0.5\npackaging==21.3\nplatformdirs==2.4.0\npluggy==1.0.0\npy==1.11.0\npyparsing==3.1.4\npytest==7.0.1\npytest-cov==4.0.0\npython-dateutil==2.9.0.post0\nrequests==2.27.1\nresponses==0.17.0\ns3transfer==0.5.2\nsix==1.17.0\ntoml==0.10.2\ntomli==1.2.3\ntox==3.28.0\ntyping_extensions==4.1.1\nuritemplate==4.1.1\nuritemplate.py==3.0.2\nurllib3==1.26.20\nvirtualenv==20.17.1\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: mapbox-sdk-py\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - boto3==1.23.10\n - botocore==1.26.10\n - cachecontrol==0.12.14\n - charset-normalizer==2.0.12\n - click==8.0.4\n - click-plugins==1.1.1\n - cligj==0.7.2\n - coverage==6.2\n - coveralls==3.3.1\n - distlib==0.3.9\n - docopt==0.6.2\n - filelock==3.4.1\n - idna==3.10\n - importlib-metadata==4.8.3\n - importlib-resources==5.4.0\n - iniconfig==1.1.1\n - iso3166==2.1.1\n - jmespath==0.10.0\n - msgpack==1.0.5\n - packaging==21.3\n - pip==21.3.1\n - platformdirs==2.4.0\n - pluggy==1.0.0\n - py==1.11.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - pytest-cov==4.0.0\n - python-dateutil==2.9.0.post0\n - requests==2.27.1\n - responses==0.17.0\n - s3transfer==0.5.2\n - six==1.17.0\n - toml==0.10.2\n - tomli==1.2.3\n - tox==3.28.0\n - typing-extensions==4.1.1\n - uritemplate==4.1.1\n - uritemplate-py==3.0.2\n - urllib3==1.26.20\n - virtualenv==20.17.1\n - zipp==3.6.0\nprefix: /opt/conda/envs/mapbox-sdk-py\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_encoding.py::test_encode_polyline","tests/test_surface.py::test_surface_params"],"string":"[\n \"tests/test_encoding.py::test_encode_polyline\",\n \"tests/test_surface.py::test_surface_params\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_encoding.py::test_read_geojson_features","tests/test_encoding.py::test_geo_interface","tests/test_encoding.py::test_encode_waypoints","tests/test_encoding.py::test_encode_limits","tests/test_encoding.py::test_unsupported_geometry","tests/test_encoding.py::test_unknown_object","tests/test_encoding.py::test_encode_coordinates_json","tests/test_surface.py::test_surface","tests/test_surface.py::test_surface_geojson"],"string":"[\n \"tests/test_encoding.py::test_read_geojson_features\",\n \"tests/test_encoding.py::test_geo_interface\",\n \"tests/test_encoding.py::test_encode_waypoints\",\n \"tests/test_encoding.py::test_encode_limits\",\n \"tests/test_encoding.py::test_unsupported_geometry\",\n \"tests/test_encoding.py::test_unknown_object\",\n \"tests/test_encoding.py::test_encode_coordinates_json\",\n \"tests/test_surface.py::test_surface\",\n \"tests/test_surface.py::test_surface_geojson\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":580,"string":"580"}}},{"rowIdx":580,"cells":{"instance_id":{"kind":"string","value":"bigchaindb__cryptoconditions-15"},"base_commit":{"kind":"string","value":"c3156a947ca32e8d1d9c5f7ec8fa0a049f2ba0a6"},"created_at":{"kind":"string","value":"2016-06-10 12:14:28"},"environment_setup_commit":{"kind":"string","value":"c3156a947ca32e8d1d9c5f7ec8fa0a049f2ba0a6"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/README.md b/README.md\nindex 4387e6e..6c963c8 100644\n--- a/README.md\n+++ b/README.md\n@@ -39,6 +39,7 @@ generic authenticated event handlers.\n ## Usage\n \n ```python\n+import json\n import binascii\n import cryptoconditions as cc\n \n@@ -64,7 +65,7 @@ parsed_fulfillment = cc.Fulfillment.from_uri(example_fulfillment_uri)\n print(isinstance(parsed_fulfillment, cc.PreimageSha256Fulfillment))\n # prints True\n \n-# Retrieve the condition of the fulfillment \n+# Retrieve the condition of the fulfillment\n print(parsed_fulfillment.condition_uri)\n # prints 'cc:0:3:47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU:0'\n \n@@ -72,14 +73,13 @@ print(parsed_fulfillment.condition_uri)\n parsed_fulfillment.validate()\n # prints True\n \n-# Export to JSON\n-json_data = parsed_fulfillment.serialize_json()\n+# Serialize fulfillment to JSON\n+json_data = json.dumps(parsed_fulfillment.to_dict())\n print(json_data)\n # prints '{\"bitmask\": 3, \"type_id\": 0, \"type\": \"fulfillment\", \"preimage\": \"\"}'\n \n # Parse fulfillment from JSON\n-import json\n-json_fulfillment = cc.Fulfillment.from_json(json.loads(json_data))\n+json_fulfillment = cc.Fulfillment.from_dict(json.loads(json_data))\n print(json_fulfillment.serialize_uri())\n # prints 'cf:0:'\n ```\n@@ -270,6 +270,7 @@ FULFILLMENT_PAYLOAD =\n ### Usage\n \n ```python\n+import json\n import cryptoconditions as cc\n \n # Parse some fulfillments\n@@ -315,7 +316,7 @@ threshold_fulfillment.threshold = 3 # AND gate\n \n print(threshold_fulfillment.serialize_uri())\n # prints 'cf:2:AQMBAwEBAwAAAAABAWMABGDsFyuTrV5WO_STLHDhJFA0w1Rn7y79TWTr-BloNGfiv7YikfrZQy-PKYucSkiV2-KT9v_aGmja3wzN719HoMchKl_qPNqXo_TAPqny6Kwc7IalHUUhJ6vboJ0bbzMcBwoAAQGBmgACgZYBAQECAQEAJwAEASAg7Bcrk61eVjv0kyxw4SRQNMNUZ-8u_U1k6_gZaDRn4r8BYAEBYwAEYOwXK5OtXlY79JMscOEkUDTDVGfvLv1NZOv4GWg0Z-K_tiKR-tlDL48pi5xKSJXb4pP2_9oaaNrfDM3vX0egxyEqX-o82pej9MA-qfLorBzshqUdRSEnq9ugnRtvMxwHCgAA'\n-threshold_fulfillment.serialize_json()\n+threshold_fulfillment.to_dict()\n ```\n \n ```python\n@@ -416,4 +417,4 @@ timeout_fulfillment valid: False (0s to timeout)\n timeout_fulfillment valid: False (-1s to timeout)\n timeout_fulfillment valid: False (-2s to timeout)\n timeout_fulfillment valid: False (-3s to timeout)\n-```\n\\ No newline at end of file\n+```\ndiff --git a/cryptoconditions/condition.py b/cryptoconditions/condition.py\nindex 4ae9d75..d00427a 100644\n--- a/cryptoconditions/condition.py\n+++ b/cryptoconditions/condition.py\n@@ -1,4 +1,3 @@\n-import json\n import base58\n import base64\n import re\n@@ -117,18 +116,18 @@ class Condition(metaclass=ABCMeta):\n return condition\n \n @staticmethod\n- def from_json(json_data):\n+ def from_dict(data):\n \"\"\"\n- Create a Condition object from a json dict.\n+ Create a Condition object from a dict.\n \n Args:\n- json_data (dict): Dictionary containing the condition payload\n+ data (dict): Dictionary containing the condition payload\n \n Returns:\n Condition: Resulting object\n \"\"\"\n condition = Condition()\n- condition.parse_json(json_data)\n+ condition.parse_dict(data)\n \n return condition\n \n@@ -262,30 +261,34 @@ class Condition(metaclass=ABCMeta):\n self.hash = reader.read_var_octet_string()\n self.max_fulfillment_length = reader.read_var_uint()\n \n- def serialize_json(self):\n- return json.dumps(\n- {\n- 'type': 'condition',\n- 'type_id': self.type_id,\n- 'bitmask': self.bitmask,\n- 'hash': base58.b58encode(self.hash),\n- 'max_fulfillment_length': self.max_fulfillment_length\n- }\n- )\n+ def to_dict(self):\n+ \"\"\"\n+ Generate a dict of the condition\n \n- def parse_json(self, json_data):\n+ Returns:\n+ dict: representing the condition\n+ \"\"\"\n+ return {\n+ 'type': 'condition',\n+ 'type_id': self.type_id,\n+ 'bitmask': self.bitmask,\n+ 'hash': base58.b58encode(self.hash),\n+ 'max_fulfillment_length': self.max_fulfillment_length\n+ }\n+\n+ def parse_dict(self, data):\n \"\"\"\n \n Args:\n- json_data (dict):\n+ data (dict):\n Returns:\n Condition with payload\n \"\"\"\n- self.type_id = json_data['type_id']\n- self.bitmask = json_data['bitmask']\n+ self.type_id = data['type_id']\n+ self.bitmask = data['bitmask']\n \n- self.hash = base58.b58decode(json_data['hash'])\n- self.max_fulfillment_length = json_data['max_fulfillment_length']\n+ self.hash = base58.b58decode(data['hash'])\n+ self.max_fulfillment_length = data['max_fulfillment_length']\n \n def validate(self):\n \"\"\"\ndiff --git a/cryptoconditions/fulfillment.py b/cryptoconditions/fulfillment.py\nindex c07a281..f78e5af 100644\n--- a/cryptoconditions/fulfillment.py\n+++ b/cryptoconditions/fulfillment.py\n@@ -78,12 +78,12 @@ class Fulfillment(metaclass=ABCMeta):\n return fulfillment\n \n @staticmethod\n- def from_json(json_data):\n- cls_type = json_data['type_id']\n+ def from_dict(data):\n+ cls_type = data['type_id']\n cls = TypeRegistry.get_class_from_type_id(cls_type)\n \n fulfillment = cls()\n- fulfillment.parse_json(json_data)\n+ fulfillment.parse_dict(data)\n \n return fulfillment\n \n@@ -249,20 +249,20 @@ class Fulfillment(metaclass=ABCMeta):\n \"\"\"\n \n @abstractmethod\n- def serialize_json(self):\n+ def to_dict(self):\n \"\"\"\n- Generate a JSON object of the fulfillment\n+ Generate a dict of the fulfillment\n \n Returns:\n \"\"\"\n \n @abstractmethod\n- def parse_json(self, json_data):\n+ def parse_dict(self, data):\n \"\"\"\n- Generate fulfillment payload from a json\n+ Generate fulfillment payload from a dict\n \n Args:\n- json_data: json description of the fulfillment\n+ data: dict description of the fulfillment\n \n Returns:\n Fulfillment\ndiff --git a/cryptoconditions/types/ed25519.py b/cryptoconditions/types/ed25519.py\nindex fb8fd32..ddcf8fa 100644\n--- a/cryptoconditions/types/ed25519.py\n+++ b/cryptoconditions/types/ed25519.py\n@@ -1,5 +1,3 @@\n-import json\n-\n import base58\n \n from cryptoconditions.crypto import Ed25519VerifyingKey as VerifyingKey\n@@ -113,34 +111,33 @@ class Ed25519Fulfillment(Fulfillment):\n def calculate_max_fulfillment_length(self):\n return Ed25519Fulfillment.FULFILLMENT_LENGTH\n \n- def serialize_json(self):\n+ def to_dict(self):\n \"\"\"\n- Generate a JSON object of the fulfillment\n+ Generate a dict of the fulfillment\n \n Returns:\n+ dict: representing the fulfillment\n \"\"\"\n- return json.dumps(\n- {\n- 'type': 'fulfillment',\n- 'type_id': self.TYPE_ID,\n- 'bitmask': self.bitmask,\n- 'public_key': self.public_key.to_ascii(encoding='base58').decode(),\n- 'signature': base58.b58encode(self.signature) if self.signature else None\n- }\n- )\n+ return {\n+ 'type': 'fulfillment',\n+ 'type_id': self.TYPE_ID,\n+ 'bitmask': self.bitmask,\n+ 'public_key': self.public_key.to_ascii(encoding='base58').decode(),\n+ 'signature': base58.b58encode(self.signature) if self.signature else None\n+ }\n \n- def parse_json(self, json_data):\n+ def parse_dict(self, data):\n \"\"\"\n- Generate fulfillment payload from a json\n+ Generate fulfillment payload from a dict\n \n Args:\n- json_data: json description of the fulfillment\n+ data (dict): description of the fulfillment\n \n Returns:\n Fulfillment\n \"\"\"\n- self.public_key = VerifyingKey(json_data['public_key'])\n- self.signature = base58.b58decode(json_data['signature']) if json_data['signature'] else None\n+ self.public_key = VerifyingKey(data['public_key'])\n+ self.signature = base58.b58decode(data['signature']) if data['signature'] else None\n \n def validate(self, message=None, **kwargs):\n \"\"\"\ndiff --git a/cryptoconditions/types/sha256.py b/cryptoconditions/types/sha256.py\nindex daa2e00..f36e96a 100644\n--- a/cryptoconditions/types/sha256.py\n+++ b/cryptoconditions/types/sha256.py\n@@ -1,5 +1,3 @@\n-import json\n-\n from cryptoconditions.types.base_sha256 import BaseSha256Fulfillment\n from cryptoconditions.lib import Hasher, Reader, Writer, Predictor\n \n@@ -93,32 +91,31 @@ class PreimageSha256Fulfillment(BaseSha256Fulfillment):\n writer.write(self.preimage)\n return writer\n \n- def serialize_json(self):\n+ def to_dict(self):\n \"\"\"\n- Generate a JSON object of the fulfillment\n+ Generate a dict of the fulfillment\n \n Returns:\n+ dict: representing the fulfillment\n \"\"\"\n- return json.dumps(\n- {\n- 'type': 'fulfillment',\n- 'type_id': self.TYPE_ID,\n- 'bitmask': self.bitmask,\n- 'preimage': self.preimage.decode()\n- }\n- )\n-\n- def parse_json(self, json_data):\n+ return {\n+ 'type': 'fulfillment',\n+ 'type_id': self.TYPE_ID,\n+ 'bitmask': self.bitmask,\n+ 'preimage': self.preimage.decode()\n+ }\n+\n+ def parse_dict(self, data):\n \"\"\"\n- Generate fulfillment payload from a json\n+ Generate fulfillment payload from a dict\n \n Args:\n- json_data: json description of the fulfillment\n+ data (dict): description of the fulfillment\n \n Returns:\n Fulfillment\n \"\"\"\n- self.preimage = json_data['preimage'].encode()\n+ self.preimage = data['preimage'].encode()\n \n def validate(self, *args, **kwargs):\n \"\"\"\ndiff --git a/cryptoconditions/types/threshold_sha256.py b/cryptoconditions/types/threshold_sha256.py\nindex 068e9b2..aae4e02 100644\n--- a/cryptoconditions/types/threshold_sha256.py\n+++ b/cryptoconditions/types/threshold_sha256.py\n@@ -1,5 +1,3 @@\n-import json\n-\n import copy\n from cryptoconditions.condition import Condition\n from cryptoconditions.fulfillment import Fulfillment\n@@ -109,6 +107,7 @@ class ThresholdSha256Fulfillment(BaseSha256Fulfillment):\n elif not isinstance(subfulfillment, Fulfillment):\n raise TypeError('Subfulfillments must be URIs or objects of type Fulfillment')\n if not isinstance(weight, int) or weight < 1:\n+ # TODO: Add a more helpful error message.\n raise ValueError('Invalid weight: {}'.format(weight))\n self.subconditions.append(\n {\n@@ -277,7 +276,7 @@ class ThresholdSha256Fulfillment(BaseSha256Fulfillment):\n \n predictor = Predictor()\n predictor.write_uint16(None) # type\n- predictor.write_var_octet_string(b'0'*fulfillment_len) # payload\n+ predictor.write_var_octet_string(b'0' * fulfillment_len) # payload\n \n return predictor.size\n \n@@ -486,49 +485,48 @@ class ThresholdSha256Fulfillment(BaseSha256Fulfillment):\n buffers_copy.sort(key=lambda item: (len(item), item))\n return buffers_copy\n \n- def serialize_json(self):\n+ def to_dict(self):\n \"\"\"\n- Generate a JSON object of the fulfillment\n+ Generate a dict of the fulfillment\n \n Returns:\n+ dict: representing the fulfillment\n \"\"\"\n- subfulfillments_json = []\n+ subfulfillments = []\n for c in self.subconditions:\n- subcondition = json.loads(c['body'].serialize_json())\n+ subcondition = c['body'].to_dict()\n subcondition.update({'weight': c['weight']})\n- subfulfillments_json.append(subcondition)\n+ subfulfillments.append(subcondition)\n \n- return json.dumps(\n- {\n- 'type': 'fulfillment',\n- 'type_id': self.TYPE_ID,\n- 'bitmask': self.bitmask,\n- 'threshold': self.threshold,\n- 'subfulfillments': subfulfillments_json\n- }\n- )\n+ return {\n+ 'type': 'fulfillment',\n+ 'type_id': self.TYPE_ID,\n+ 'bitmask': self.bitmask,\n+ 'threshold': self.threshold,\n+ 'subfulfillments': subfulfillments\n+ }\n \n- def parse_json(self, json_data):\n+ def parse_dict(self, data):\n \"\"\"\n- Generate fulfillment payload from a json\n+ Generate fulfillment payload from a dict\n \n Args:\n- json_data: json description of the fulfillment\n+ data (dict): description of the fulfillment\n \n Returns:\n Fulfillment\n \"\"\"\n- if not isinstance(json_data, dict):\n+ if not isinstance(data, dict):\n raise TypeError('reader must be a dict instance')\n- self.threshold = json_data['threshold']\n+ self.threshold = data['threshold']\n \n- for subfulfillments_json in json_data['subfulfillments']:\n- weight = subfulfillments_json['weight']\n+ for subfulfillments in data['subfulfillments']:\n+ weight = subfulfillments['weight']\n \n- if subfulfillments_json['type'] == FULFILLMENT:\n- self.add_subfulfillment(Fulfillment.from_json(subfulfillments_json), weight)\n- elif subfulfillments_json['type'] == CONDITION:\n- self.add_subcondition(Condition.from_json(subfulfillments_json), weight)\n+ if subfulfillments['type'] == FULFILLMENT:\n+ self.add_subfulfillment(Fulfillment.from_dict(subfulfillments), weight)\n+ elif subfulfillments['type'] == CONDITION:\n+ self.add_subcondition(Condition.from_dict(subfulfillments), weight)\n else:\n raise TypeError('Subconditions must provide either subcondition or fulfillment.')\n \ndiff --git a/cryptoconditions/types/timeout.py b/cryptoconditions/types/timeout.py\nindex 6b9d2fc..0007c6f 100644\n--- a/cryptoconditions/types/timeout.py\n+++ b/cryptoconditions/types/timeout.py\n@@ -1,4 +1,3 @@\n-import json\n import re\n import time\n \n@@ -32,32 +31,31 @@ class TimeoutFulfillment(PreimageSha256Fulfillment):\n \"\"\"\n return self.preimage\n \n- def serialize_json(self):\n+ def to_dict(self):\n \"\"\"\n- Generate a JSON object of the fulfillment\n+ Generate a dict of the fulfillment\n \n Returns:\n+ dict: representing the fulfillment\n \"\"\"\n- return json.dumps(\n- {\n- 'type': 'fulfillment',\n- 'type_id': self.TYPE_ID,\n- 'bitmask': self.bitmask,\n- 'expire_time': self.expire_time.decode()\n- }\n- )\n-\n- def parse_json(self, json_data):\n+ return {\n+ 'type': 'fulfillment',\n+ 'type_id': self.TYPE_ID,\n+ 'bitmask': self.bitmask,\n+ 'expire_time': self.expire_time.decode()\n+ }\n+\n+ def parse_dict(self, data):\n \"\"\"\n- Generate fulfillment payload from a json\n+ Generate fulfillment payload from a dict\n \n Args:\n- json_data: json description of the fulfillment\n+ data (dict): description of the fulfillment\n \n Returns:\n Fulfillment\n \"\"\"\n- self.preimage = json_data['expire_time'].encode()\n+ self.preimage = data['expire_time'].encode()\n \n def validate(self, message=None, now=None, **kwargs):\n \"\"\"\ndiff --git a/setup.py b/setup.py\nindex c467ce2..d4da1b4 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -69,8 +69,7 @@ setup(\n tests_require=tests_require,\n extras_require={\n 'test': tests_require,\n- 'dev': dev_require + tests_require + docs_require,\n- 'docs': docs_require,\n+ 'dev': dev_require + tests_require + docs_require,\n+ 'docs': docs_require,\n },\n )\n-\n"},"problem_statement":{"kind":"string","value":"Remove json serialization from cryptoconditions\nJust provide functions for serialization to dicts.\r\nUsers should be able to serialize from there on to dicts themselves."},"repo":{"kind":"string","value":"bigchaindb/cryptoconditions"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_fulfillment.py b/tests/test_fulfillment.py\nindex 225c85c..10d75dc 100644\n--- a/tests/test_fulfillment.py\n+++ b/tests/test_fulfillment.py\n@@ -1,5 +1,4 @@\n import binascii\n-import json\n from time import sleep\n \n from math import ceil\n@@ -45,20 +44,13 @@ class TestSha256Fulfillment:\n assert fulfillment.condition.serialize_uri() == fulfillment_sha256['condition_uri']\n assert fulfillment.validate()\n \n- def test_serialize_json(self, fulfillment_sha256):\n+ def test_fulfillment_serialize_to_dict(self, fulfillment_sha256):\n fulfillment = Fulfillment.from_uri(fulfillment_sha256['fulfillment_uri'])\n-\n- assert json.loads(fulfillment.serialize_json()) == \\\n- {'bitmask': 3, 'preimage': '', 'type': 'fulfillment', 'type_id': 0}\n-\n- def test_deserialize_json(self, fulfillment_sha256):\n- fulfillment = Fulfillment.from_uri(fulfillment_sha256['fulfillment_uri'])\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri()\n assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri()\n- assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json()\n+ assert parsed_fulfillment.to_dict() == fulfillment.to_dict()\n \n def test_deserialize_condition_and_validate_fulfillment(self, fulfillment_sha256):\n condition = Condition.from_uri(fulfillment_sha256['condition_uri'])\n@@ -123,10 +115,10 @@ class TestEd25519Sha256Fulfillment:\n assert deserialized_condition.serialize_uri() == fulfillment_ed25519['condition_uri']\n assert binascii.hexlify(deserialized_condition.hash) == fulfillment_ed25519['condition_hash']\n \n- def test_serialize_json_signed(self, fulfillment_ed25519):\n+ def test_serialize_signed_dict_to_fulfillment(self, fulfillment_ed25519):\n fulfillment = Fulfillment.from_uri(fulfillment_ed25519['fulfillment_uri'])\n \n- assert json.loads(fulfillment.serialize_json()) == \\\n+ assert fulfillment.to_dict()== \\\n {'bitmask': 32,\n 'public_key': 'Gtbi6WQDB6wUePiZm8aYs5XZ5pUqx9jMMLvRVHPESTjU',\n 'signature': '4eCt6SFPCzLQSAoQGW7CTu3MHdLj6FezSpjktE7tHsYGJ4pNSUnpHtV9XgdHF2XYd62M9fTJ4WYdhTVck27qNoHj',\n@@ -135,10 +127,10 @@ class TestEd25519Sha256Fulfillment:\n \n assert fulfillment.validate(MESSAGE) == True\n \n- def test_serialize_json_unsigned(self, vk_ilp):\n+ def test_serialize_unsigned_dict_to_fulfillment(self, vk_ilp):\n fulfillment = Ed25519Fulfillment(public_key=vk_ilp['b58'])\n \n- assert json.loads(fulfillment.serialize_json()) == \\\n+ assert fulfillment.to_dict() == \\\n {'bitmask': 32,\n 'public_key': 'Gtbi6WQDB6wUePiZm8aYs5XZ5pUqx9jMMLvRVHPESTjU',\n 'signature': None,\n@@ -146,23 +138,20 @@ class TestEd25519Sha256Fulfillment:\n 'type_id': 4}\n assert fulfillment.validate(MESSAGE) == False\n \n- def test_deserialize_json_signed(self, fulfillment_ed25519):\n+ def test_deserialize_signed_dict_to_fulfillment(self, fulfillment_ed25519):\n fulfillment = Fulfillment.from_uri(fulfillment_ed25519['fulfillment_uri'])\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.serialize_uri() == fulfillment_ed25519['fulfillment_uri']\n assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri()\n- assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json()\n+ assert parsed_fulfillment.to_dict() == fulfillment.to_dict()\n \n- def test_deserialize_json_unsigned(self, vk_ilp):\n+ def test_deserialize_unsigned_dict_to_fulfillment(self, vk_ilp):\n fulfillment = Ed25519Fulfillment(public_key=vk_ilp['b58'])\n-\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri()\n- assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json()\n+ assert parsed_fulfillment.to_dict() == fulfillment.to_dict()\n \n def test_serialize_deserialize_condition(self, vk_ilp):\n vk = VerifyingKey(vk_ilp['b58'])\n@@ -262,10 +251,10 @@ class TestThresholdSha256Fulfillment:\n assert len(fulfillment.subconditions) == num_fulfillments\n assert fulfillment.validate(MESSAGE)\n \n- def test_serialize_json_signed(self, fulfillment_threshold):\n+ def test_serialize_signed_dict_to_fulfillment(self, fulfillment_threshold):\n fulfillment = Fulfillment.from_uri(fulfillment_threshold['fulfillment_uri'])\n \n- assert json.loads(fulfillment.serialize_json()) == \\\n+ assert fulfillment.to_dict() == \\\n {'bitmask': 43,\n 'subfulfillments': [{'bitmask': 3,\n 'preimage': '',\n@@ -282,12 +271,12 @@ class TestThresholdSha256Fulfillment:\n 'type': 'fulfillment',\n 'type_id': 2}\n \n- def test_serialize_json_unsigned(self, vk_ilp):\n+ def test_serialize_unsigned_dict_to_fulfillment(self, vk_ilp):\n fulfillment = ThresholdSha256Fulfillment(threshold=1)\n fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58'])))\n fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58'])))\n \n- assert json.loads(fulfillment.serialize_json()) == \\\n+ assert fulfillment.to_dict() == \\\n {'bitmask': 41,\n 'subfulfillments': [{'bitmask': 32,\n 'public_key': 'Gtbi6WQDB6wUePiZm8aYs5XZ5pUqx9jMMLvRVHPESTjU',\n@@ -305,50 +294,45 @@ class TestThresholdSha256Fulfillment:\n 'type': 'fulfillment',\n 'type_id': 2}\n \n- def test_deserialize_json_signed(self, fulfillment_threshold):\n+ def test_deserialize_signed_dict_to_fulfillment(self, fulfillment_threshold):\n fulfillment = Fulfillment.from_uri(fulfillment_threshold['fulfillment_uri'])\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.serialize_uri() == fulfillment_threshold['fulfillment_uri']\n assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri()\n- assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json()\n+ assert parsed_fulfillment.to_dict() == fulfillment.to_dict()\n \n- def test_deserialize_json_unsigned(self, vk_ilp):\n+ def test_deserialize_unsigned_dict_to_fulfillment(self, vk_ilp):\n fulfillment = ThresholdSha256Fulfillment(threshold=1)\n fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58'])))\n fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58'])))\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri()\n- assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json()\n+ assert parsed_fulfillment.to_dict() == fulfillment.to_dict()\n \n def test_weights(self, fulfillment_ed25519):\n ilp_fulfillment = Fulfillment.from_uri(fulfillment_ed25519['fulfillment_uri'])\n \n fulfillment1 = ThresholdSha256Fulfillment(threshold=2)\n fulfillment1.add_subfulfillment(ilp_fulfillment, weight=2)\n- fulfillment_json = json.loads(fulfillment1.serialize_json())\n- parsed_fulfillment1 = fulfillment1.from_json(fulfillment_json)\n+ parsed_fulfillment1 = fulfillment1.from_dict(fulfillment1.to_dict())\n \n assert parsed_fulfillment1.condition.serialize_uri() == fulfillment1.condition.serialize_uri()\n- assert parsed_fulfillment1.serialize_json() == fulfillment1.serialize_json()\n+ assert parsed_fulfillment1.to_dict() == fulfillment1.to_dict()\n assert parsed_fulfillment1.subconditions[0]['weight'] == 2\n assert parsed_fulfillment1.validate(MESSAGE) is True\n \n fulfillment2 = ThresholdSha256Fulfillment(threshold=3)\n fulfillment2.add_subfulfillment(ilp_fulfillment, weight=2)\n- fulfillment_json = json.loads(fulfillment2.serialize_json())\n- parsed_fulfillment2 = fulfillment1.from_json(fulfillment_json)\n+ parsed_fulfillment2 = fulfillment1.from_dict(fulfillment2.to_dict())\n \n assert parsed_fulfillment2.subconditions[0]['weight'] == 2\n assert parsed_fulfillment2.validate(MESSAGE) is False\n \n fulfillment3 = ThresholdSha256Fulfillment(threshold=3)\n fulfillment3.add_subfulfillment(ilp_fulfillment, weight=3)\n- fulfillment_json = json.loads(fulfillment3.serialize_json())\n- parsed_fulfillment3 = fulfillment1.from_json(fulfillment_json)\n+ parsed_fulfillment3 = fulfillment1.from_dict(fulfillment3.to_dict())\n \n assert parsed_fulfillment3.condition.serialize_uri() == fulfillment3.condition.serialize_uri()\n assert not (fulfillment3.condition.serialize_uri() == fulfillment1.condition.serialize_uri())\n@@ -506,8 +490,7 @@ class TestInvertedThresholdSha256Fulfillment:\n \n fulfillment = InvertedThresholdSha256Fulfillment(threshold=1)\n fulfillment.add_subfulfillment(ilp_fulfillment_ed)\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.condition_uri == fulfillment.condition_uri\n assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri()\n@@ -521,16 +504,14 @@ class TestTimeoutFulfillment:\n def test_serialize_condition_and_validate_fulfillment(self):\n \n fulfillment = TimeoutFulfillment(expire_time=timestamp())\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.condition_uri == fulfillment.condition_uri\n assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri()\n assert parsed_fulfillment.validate(now=timestamp()) is False\n \n- fulfillment = TimeoutFulfillment(expire_time=str(float(timestamp())+1000))\n- fulfillment_json = json.loads(fulfillment.serialize_json())\n- parsed_fulfillment = fulfillment.from_json(fulfillment_json)\n+ fulfillment = TimeoutFulfillment(expire_time=str(float(timestamp()) + 1000))\n+ parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict())\n \n assert parsed_fulfillment.condition_uri == fulfillment.condition_uri\n assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri()\n@@ -573,8 +554,7 @@ class TestEscrow:\n fulfillment_escrow.add_subfulfillment(fulfillment_and_execute)\n fulfillment_escrow.add_subfulfillment(fulfillment_and_abort)\n \n- fulfillment_json = json.loads(fulfillment_escrow.serialize_json())\n- parsed_fulfillment = fulfillment_escrow.from_json(fulfillment_json)\n+ parsed_fulfillment = fulfillment_escrow.from_dict(fulfillment_escrow.to_dict())\n \n assert parsed_fulfillment.condition_uri == fulfillment_escrow.condition_uri\n assert parsed_fulfillment.serialize_uri() == fulfillment_escrow.serialize_uri()\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 1,\n \"test_score\": 2\n },\n \"num_modified_files\": 8\n}"},"version":{"kind":"string","value":"0.3"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\"\n ],\n \"pre_install\": [],\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements/base.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"alabaster==0.7.13\nastroid==2.11.7\nattrs==22.2.0\nBabel==2.11.0\nbackcall==0.2.0\nbase58==0.2.2\ncertifi==2021.5.30\ncharset-normalizer==2.0.12\ncommonmark==0.9.1\ncoverage==6.2\n-e git+https://github.com/bigchaindb/cryptoconditions.git@c3156a947ca32e8d1d9c5f7ec8fa0a049f2ba0a6#egg=cryptoconditions\ndecorator==5.1.1\ndill==0.3.4\ndocutils==0.18.1\ned25519==1.5\nexecnet==1.9.0\nidna==3.10\nimagesize==1.4.1\nimportlib-metadata==4.8.3\niniconfig==1.1.1\nipdb==0.13.13\nipython==7.16.3\nipython-genutils==0.2.0\nisort==5.10.1\njedi==0.17.2\nJinja2==3.0.3\nlazy-object-proxy==1.7.1\nMarkupSafe==2.0.1\nmccabe==0.7.0\npackaging==21.3\nparso==0.7.1\npep8==1.7.1\npexpect==4.9.0\npickleshare==0.7.5\nplatformdirs==2.4.0\npluggy==1.0.0\npockets==0.9.1\nprompt-toolkit==3.0.36\nptyprocess==0.7.0\npy==1.11.0\npyflakes==3.0.1\nPygments==2.14.0\npylint==2.13.9\npyparsing==3.1.4\npytest==7.0.1\npytest-cov==4.0.0\npytest-xdist==3.0.2\npytz==2025.2\nrecommonmark==0.7.1\nrequests==2.27.1\nsix==1.17.0\nsnowballstemmer==2.2.0\nSphinx==5.3.0\nsphinx-rtd-theme==2.0.0\nsphinxcontrib-applehelp==1.0.2\nsphinxcontrib-devhelp==1.0.2\nsphinxcontrib-htmlhelp==2.0.0\nsphinxcontrib-jquery==4.1\nsphinxcontrib-jsmath==1.0.1\nsphinxcontrib-napoleon==0.7\nsphinxcontrib-qthelp==1.0.3\nsphinxcontrib-serializinghtml==1.1.5\ntomli==1.2.3\ntraitlets==4.3.3\ntyped-ast==1.5.5\ntyping_extensions==4.1.1\nurllib3==1.26.20\nwcwidth==0.2.13\nwrapt==1.16.0\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: cryptoconditions\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - alabaster==0.7.13\n - astroid==2.11.7\n - attrs==22.2.0\n - babel==2.11.0\n - backcall==0.2.0\n - base58==0.2.2\n - charset-normalizer==2.0.12\n - commonmark==0.9.1\n - coverage==6.2\n - decorator==5.1.1\n - dill==0.3.4\n - docutils==0.18.1\n - ed25519==1.5\n - execnet==1.9.0\n - idna==3.10\n - imagesize==1.4.1\n - importlib-metadata==4.8.3\n - iniconfig==1.1.1\n - ipdb==0.13.13\n - ipython==7.16.3\n - ipython-genutils==0.2.0\n - isort==5.10.1\n - jedi==0.17.2\n - jinja2==3.0.3\n - lazy-object-proxy==1.7.1\n - markupsafe==2.0.1\n - mccabe==0.7.0\n - packaging==21.3\n - parso==0.7.1\n - pep8==1.7.1\n - pexpect==4.9.0\n - pickleshare==0.7.5\n - platformdirs==2.4.0\n - pluggy==1.0.0\n - pockets==0.9.1\n - prompt-toolkit==3.0.36\n - ptyprocess==0.7.0\n - py==1.11.0\n - pyflakes==3.0.1\n - pygments==2.14.0\n - pylint==2.13.9\n - pyparsing==3.1.4\n - pytest==7.0.1\n - pytest-cov==4.0.0\n - pytest-xdist==3.0.2\n - pytz==2025.2\n - recommonmark==0.7.1\n - requests==2.27.1\n - six==1.17.0\n - snowballstemmer==2.2.0\n - sphinx==5.3.0\n - sphinx-rtd-theme==2.0.0\n - sphinxcontrib-applehelp==1.0.2\n - sphinxcontrib-devhelp==1.0.2\n - sphinxcontrib-htmlhelp==2.0.0\n - sphinxcontrib-jquery==4.1\n - sphinxcontrib-jsmath==1.0.1\n - sphinxcontrib-napoleon==0.7\n - sphinxcontrib-qthelp==1.0.3\n - sphinxcontrib-serializinghtml==1.1.5\n - tomli==1.2.3\n - traitlets==4.3.3\n - typed-ast==1.5.5\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - wcwidth==0.2.13\n - wrapt==1.16.0\n - zipp==3.6.0\nprefix: /opt/conda/envs/cryptoconditions\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_fulfillment.py::TestSha256Fulfillment::test_fulfillment_serialize_to_dict","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_signed_dict_to_fulfillment","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_unsigned_dict_to_fulfillment","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_signed_dict_to_fulfillment","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_unsigned_dict_to_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_signed_dict_to_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_unsigned_dict_to_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_signed_dict_to_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_unsigned_dict_to_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_weights","tests/test_fulfillment.py::TestInvertedThresholdSha256Fulfillment::test_serialize_condition_and_validate_fulfillment","tests/test_fulfillment.py::TestTimeoutFulfillment::test_serialize_condition_and_validate_fulfillment","tests/test_fulfillment.py::TestEscrow::test_serialize_condition_and_validate_fulfillment"],"string":"[\n \"tests/test_fulfillment.py::TestSha256Fulfillment::test_fulfillment_serialize_to_dict\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_signed_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_unsigned_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_signed_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_unsigned_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_signed_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_unsigned_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_signed_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_unsigned_dict_to_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_weights\",\n \"tests/test_fulfillment.py::TestInvertedThresholdSha256Fulfillment::test_serialize_condition_and_validate_fulfillment\",\n \"tests/test_fulfillment.py::TestTimeoutFulfillment::test_serialize_condition_and_validate_fulfillment\",\n \"tests/test_fulfillment.py::TestEscrow::test_serialize_condition_and_validate_fulfillment\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_fulfillment.py::TestSha256Condition::test_deserialize_condition","tests/test_fulfillment.py::TestSha256Condition::test_create_condition","tests/test_fulfillment.py::TestSha256Fulfillment::test_deserialize_and_validate_fulfillment","tests/test_fulfillment.py::TestSha256Fulfillment::test_deserialize_condition_and_validate_fulfillment","tests/test_fulfillment.py::TestSha256Fulfillment::test_condition_from_fulfillment","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_ilp_keys","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_create","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_condition_and_validate_fulfillment","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_condition","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_deserialize_condition","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_fulfillment","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_fulfillment_2","tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_deserialize_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_condition_and_validate_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_deserialize_fulfillment","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_didnt_reach_threshold","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_nested_and_or","tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_nested","tests/test_fulfillment.py::TestEscrow::test_escrow_execute","tests/test_fulfillment.py::TestEscrow::test_escrow_abort","tests/test_fulfillment.py::TestEscrow::test_escrow_execute_abort"],"string":"[\n \"tests/test_fulfillment.py::TestSha256Condition::test_deserialize_condition\",\n \"tests/test_fulfillment.py::TestSha256Condition::test_create_condition\",\n \"tests/test_fulfillment.py::TestSha256Fulfillment::test_deserialize_and_validate_fulfillment\",\n \"tests/test_fulfillment.py::TestSha256Fulfillment::test_deserialize_condition_and_validate_fulfillment\",\n \"tests/test_fulfillment.py::TestSha256Fulfillment::test_condition_from_fulfillment\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_ilp_keys\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_create\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_condition_and_validate_fulfillment\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_condition\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_deserialize_condition\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_fulfillment\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_fulfillment_2\",\n \"tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_deserialize_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_condition_and_validate_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_deserialize_fulfillment\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_didnt_reach_threshold\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_nested_and_or\",\n \"tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_nested\",\n \"tests/test_fulfillment.py::TestEscrow::test_escrow_execute\",\n \"tests/test_fulfillment.py::TestEscrow::test_escrow_abort\",\n \"tests/test_fulfillment.py::TestEscrow::test_escrow_execute_abort\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":581,"string":"581"}}},{"rowIdx":581,"cells":{"instance_id":{"kind":"string","value":"cdent__gabbi-153"},"base_commit":{"kind":"string","value":"0a8a3b8faf9a900fd132d9b147f67a851d52f178"},"created_at":{"kind":"string","value":"2016-06-12 20:11:11"},"environment_setup_commit":{"kind":"string","value":"0a8a3b8faf9a900fd132d9b147f67a851d52f178"},"hints_text":{"kind":"string","value":"cdent: @jd and @EmilienM, this good for you guys?\nEmilienM: :+1: "},"patch":{"kind":"string","value":"diff --git a/gabbi/driver.py b/gabbi/driver.py\nindex 33c0a98..49088fa 100644\n--- a/gabbi/driver.py\n+++ b/gabbi/driver.py\n@@ -39,7 +39,8 @@ from gabbi import utils\n \n def build_tests(path, loader, host=None, port=8001, intercept=None,\n test_loader_name=None, fixture_module=None,\n- response_handlers=None, prefix='', require_ssl=False):\n+ response_handlers=None, prefix='', require_ssl=False,\n+ url=None):\n \"\"\"Read YAML files from a directory to create tests.\n \n Each YAML file represents an ordered sequence of HTTP requests.\n@@ -54,6 +55,7 @@ def build_tests(path, loader, host=None, port=8001, intercept=None,\n :param response_handers: ResponseHandler classes.\n :type response_handlers: List of ResponseHandler classes.\n :param prefix: A URL prefix for all URLs that are not fully qualified.\n+ :param url: A full URL to test against. Replaces host, port and prefix.\n :param require_ssl: If ``True``, make all tests default to using SSL.\n :rtype: TestSuite containing multiple TestSuites (one for each YAML file).\n \"\"\"\n@@ -63,6 +65,12 @@ def build_tests(path, loader, host=None, port=8001, intercept=None,\n if not bool(host) ^ bool(intercept):\n raise AssertionError('must specify exactly one of host or intercept')\n \n+ # If url is being used, reset host, port and prefix.\n+ if url:\n+ host, port, prefix, force_ssl = utils.host_info_from_target(url)\n+ if force_ssl and not require_ssl:\n+ require_ssl = force_ssl\n+\n if test_loader_name is None:\n test_loader_name = inspect.stack()[1]\n test_loader_name = os.path.splitext(os.path.basename(\n@@ -97,7 +105,7 @@ def build_tests(path, loader, host=None, port=8001, intercept=None,\n def py_test_generator(test_dir, host=None, port=8001, intercept=None,\n prefix=None, test_loader_name=None,\n fixture_module=None, response_handlers=None,\n- require_ssl=False):\n+ require_ssl=False, url=None):\n \"\"\"Generate tests cases for py.test\n \n This uses build_tests to create TestCases and then yields them in\n@@ -110,7 +118,8 @@ def py_test_generator(test_dir, host=None, port=8001, intercept=None,\n test_loader_name=test_loader_name,\n fixture_module=fixture_module,\n response_handlers=response_handlers,\n- prefix=prefix, require_ssl=require_ssl)\n+ prefix=prefix, require_ssl=require_ssl,\n+ url=url)\n \n for test in tests:\n if hasattr(test, '_tests'):\ndiff --git a/gabbi/runner.py b/gabbi/runner.py\nindex 3411dbe..d4e79d5 100644\n--- a/gabbi/runner.py\n+++ b/gabbi/runner.py\n@@ -17,8 +17,6 @@ from importlib import import_module\n import sys\n import unittest\n \n-from six.moves.urllib import parse as urlparse\n-\n from gabbi import case\n from gabbi import handlers\n from gabbi.reporter import ConciseTestRunner\n@@ -93,7 +91,7 @@ def run():\n )\n \n args = parser.parse_args()\n- host, port, prefix, force_ssl = process_target_args(\n+ host, port, prefix, force_ssl = utils.host_info_from_target(\n args.target, args.prefix)\n \n # Initialize response handlers.\n@@ -113,31 +111,6 @@ def run():\n sys.exit(not result.wasSuccessful())\n \n \n-def process_target_args(target, prefix):\n- \"\"\"Turn the argparse args into a host, port and prefix.\"\"\"\n- force_ssl = False\n- split_url = urlparse.urlparse(target)\n-\n- if split_url.scheme:\n- if split_url.scheme == 'https':\n- force_ssl = True\n- return split_url.hostname, split_url.port, split_url.path, force_ssl\n- else:\n- target = target\n- prefix = prefix\n-\n- if ':' in target and '[' not in target:\n- host, port = target.rsplit(':', 1)\n- elif ']:' in target:\n- host, port = target.rsplit(':', 1)\n- else:\n- host = target\n- port = None\n- host = host.replace('[', '').replace(']', '')\n-\n- return host, port, prefix, force_ssl\n-\n-\n def initialize_handlers(response_handlers):\n custom_response_handlers = []\n for import_path in response_handlers or []:\ndiff --git a/gabbi/utils.py b/gabbi/utils.py\nindex 3de040d..172b4bf 100644\n--- a/gabbi/utils.py\n+++ b/gabbi/utils.py\n@@ -126,6 +126,31 @@ def not_binary(content_type):\n content_type.startswith('application/json'))\n \n \n+def host_info_from_target(target, prefix=None):\n+ \"\"\"Turn url or host:port and target into test destination.\"\"\"\n+ force_ssl = False\n+ split_url = urlparse.urlparse(target)\n+\n+ if split_url.scheme:\n+ if split_url.scheme == 'https':\n+ force_ssl = True\n+ return split_url.hostname, split_url.port, split_url.path, force_ssl\n+ else:\n+ target = target\n+ prefix = prefix\n+\n+ if ':' in target and '[' not in target:\n+ host, port = target.rsplit(':', 1)\n+ elif ']:' in target:\n+ host, port = target.rsplit(':', 1)\n+ else:\n+ host = target\n+ port = None\n+ host = host.replace('[', '').replace(']', '')\n+\n+ return host, port, prefix, force_ssl\n+\n+\n def _colorize(color, message):\n \"\"\"Add a color to the message.\"\"\"\n try:\n"},"problem_statement":{"kind":"string","value":"In 'live' testing scenarios argument passing to build_tests is convoluted and SSL may not work\nIf you want to use `build_tests` to create real TestCases against a live server it's likely you know the URL and that would be most convenient thing to pass instead of having to parse out the host, port and prefix (script_name) and then pass those.\r\n\r\nIn addition, if you have a URL you know if your server is SSL but the tests may not have been written to do SSL (with an `ssl: true` entry). Because of the test building process this is a bit awkward at the moment. It would be better to be able to say \"yeah, this is SSL\" for the whole run."},"repo":{"kind":"string","value":"cdent/gabbi"},"test_patch":{"kind":"string","value":"diff --git a/gabbi/tests/test_driver.py b/gabbi/tests/test_driver.py\nindex 0b2ce0a..8f6bca0 100644\n--- a/gabbi/tests/test_driver.py\n+++ b/gabbi/tests/test_driver.py\n@@ -70,3 +70,20 @@ class DriverTest(unittest.TestCase):\n first_test = suite._tests[0]._tests[0]\n full_url = first_test._parse_url(first_test.test_data['url'])\n self.assertEqual('http://localhost:8001/', full_url)\n+\n+ def test_build_url_target(self):\n+ suite = driver.build_tests(self.test_dir, self.loader,\n+ host='localhost', port='999',\n+ url='https://example.com:1024/theend')\n+ first_test = suite._tests[0]._tests[0]\n+ full_url = first_test._parse_url(first_test.test_data['url'])\n+ self.assertEqual('https://example.com:1024/theend/', full_url)\n+\n+ def test_build_url_target_forced_ssl(self):\n+ suite = driver.build_tests(self.test_dir, self.loader,\n+ host='localhost', port='999',\n+ url='http://example.com:1024/theend',\n+ require_ssl=True)\n+ first_test = suite._tests[0]._tests[0]\n+ full_url = first_test._parse_url(first_test.test_data['url'])\n+ self.assertEqual('https://example.com:1024/theend/', full_url)\ndiff --git a/gabbi/tests/test_runner.py b/gabbi/tests/test_runner.py\nindex 3c132b1..a854cf9 100644\n--- a/gabbi/tests/test_runner.py\n+++ b/gabbi/tests/test_runner.py\n@@ -229,93 +229,6 @@ class RunnerTest(unittest.TestCase):\n self._stderr.write(sys.stderr.read())\n \n \n-class RunnerHostArgParse(unittest.TestCase):\n-\n- def _test_hostport(self, url_or_host, expected_host,\n- provided_prefix=None, expected_port=None,\n- expected_prefix=None, expected_ssl=False):\n- host, port, prefix, ssl = runner.process_target_args(\n- url_or_host, provided_prefix)\n-\n- # normalize hosts, they are case insensitive\n- self.assertEqual(expected_host.lower(), host.lower())\n- # port can be a string or int depending on the inputs\n- self.assertEqual(expected_port, port)\n- self.assertEqual(expected_prefix, prefix)\n- self.assertEqual(expected_ssl, ssl)\n-\n- def test_plain_url_no_port(self):\n- self._test_hostport('http://foobar.com/news',\n- 'foobar.com',\n- expected_port=None,\n- expected_prefix='/news')\n-\n- def test_plain_url_with_port(self):\n- self._test_hostport('http://foobar.com:80/news',\n- 'foobar.com',\n- expected_port=80,\n- expected_prefix='/news')\n-\n- def test_ssl_url(self):\n- self._test_hostport('https://foobar.com/news',\n- 'foobar.com',\n- expected_prefix='/news',\n- expected_ssl=True)\n-\n- def test_ssl_port80_url(self):\n- self._test_hostport('https://foobar.com:80/news',\n- 'foobar.com',\n- expected_prefix='/news',\n- expected_port=80,\n- expected_ssl=True)\n-\n- def test_ssl_port_url(self):\n- self._test_hostport('https://foobar.com:999/news',\n- 'foobar.com',\n- expected_prefix='/news',\n- expected_port=999,\n- expected_ssl=True)\n-\n- def test_simple_hostport(self):\n- self._test_hostport('foobar.com:999',\n- 'foobar.com',\n- expected_port='999')\n-\n- def test_simple_hostport_with_prefix(self):\n- self._test_hostport('foobar.com:999',\n- 'foobar.com',\n- provided_prefix='/news',\n- expected_port='999',\n- expected_prefix='/news')\n-\n- def test_ipv6_url_long(self):\n- self._test_hostport(\n- 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/news',\n- 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210',\n- expected_port=999,\n- expected_prefix='/news')\n-\n- def test_ipv6_url_localhost(self):\n- self._test_hostport(\n- 'http://[::1]:999/news',\n- '::1',\n- expected_port=999,\n- expected_prefix='/news')\n-\n- def test_ipv6_host_localhost(self):\n- # If a user wants to use the hostport form, then they need\n- # to hack it with the brackets.\n- self._test_hostport(\n- '[::1]',\n- '::1')\n-\n- def test_ipv6_hostport_localhost(self):\n- self._test_hostport(\n- '[::1]:999',\n- '::1',\n- expected_port='999')\n-\n-\n class HTMLResponseHandler(handlers.ResponseHandler):\n \n test_key_suffix = 'html'\ndiff --git a/gabbi/tests/test_utils.py b/gabbi/tests/test_utils.py\nindex 1754dad..d5b8b50 100644\n--- a/gabbi/tests/test_utils.py\n+++ b/gabbi/tests/test_utils.py\n@@ -158,3 +158,90 @@ class CreateURLTest(unittest.TestCase):\n '/foo', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', port=999)\n self.assertEqual(\n 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/foo', url)\n+\n+\n+class UtilsHostInfoFromTarget(unittest.TestCase):\n+\n+ def _test_hostport(self, url_or_host, expected_host,\n+ provided_prefix=None, expected_port=None,\n+ expected_prefix=None, expected_ssl=False):\n+ host, port, prefix, ssl = utils.host_info_from_target(\n+ url_or_host, provided_prefix)\n+\n+ # normalize hosts, they are case insensitive\n+ self.assertEqual(expected_host.lower(), host.lower())\n+ # port can be a string or int depending on the inputs\n+ self.assertEqual(expected_port, port)\n+ self.assertEqual(expected_prefix, prefix)\n+ self.assertEqual(expected_ssl, ssl)\n+\n+ def test_plain_url_no_port(self):\n+ self._test_hostport('http://foobar.com/news',\n+ 'foobar.com',\n+ expected_port=None,\n+ expected_prefix='/news')\n+\n+ def test_plain_url_with_port(self):\n+ self._test_hostport('http://foobar.com:80/news',\n+ 'foobar.com',\n+ expected_port=80,\n+ expected_prefix='/news')\n+\n+ def test_ssl_url(self):\n+ self._test_hostport('https://foobar.com/news',\n+ 'foobar.com',\n+ expected_prefix='/news',\n+ expected_ssl=True)\n+\n+ def test_ssl_port80_url(self):\n+ self._test_hostport('https://foobar.com:80/news',\n+ 'foobar.com',\n+ expected_prefix='/news',\n+ expected_port=80,\n+ expected_ssl=True)\n+\n+ def test_ssl_port_url(self):\n+ self._test_hostport('https://foobar.com:999/news',\n+ 'foobar.com',\n+ expected_prefix='/news',\n+ expected_port=999,\n+ expected_ssl=True)\n+\n+ def test_simple_hostport(self):\n+ self._test_hostport('foobar.com:999',\n+ 'foobar.com',\n+ expected_port='999')\n+\n+ def test_simple_hostport_with_prefix(self):\n+ self._test_hostport('foobar.com:999',\n+ 'foobar.com',\n+ provided_prefix='/news',\n+ expected_port='999',\n+ expected_prefix='/news')\n+\n+ def test_ipv6_url_long(self):\n+ self._test_hostport(\n+ 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/news',\n+ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210',\n+ expected_port=999,\n+ expected_prefix='/news')\n+\n+ def test_ipv6_url_localhost(self):\n+ self._test_hostport(\n+ 'http://[::1]:999/news',\n+ '::1',\n+ expected_port=999,\n+ expected_prefix='/news')\n+\n+ def test_ipv6_host_localhost(self):\n+ # If a user wants to use the hostport form, then they need\n+ # to hack it with the brackets.\n+ self._test_hostport(\n+ '[::1]',\n+ '::1')\n+\n+ def test_ipv6_hostport_localhost(self):\n+ self._test_hostport(\n+ '[::1]:999',\n+ '::1',\n+ expected_port='999')\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"merge_commit\",\n \"failed_lite_validators\": [\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 1,\n \"test_score\": 1\n },\n \"num_modified_files\": 3\n}"},"version":{"kind":"string","value":"1.21"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\ncertifi==2021.5.30\ncolorama==0.4.5\ndecorator==5.1.1\n-e git+https://github.com/cdent/gabbi.git@0a8a3b8faf9a900fd132d9b147f67a851d52f178#egg=gabbi\nimportlib-metadata==4.8.3\niniconfig==1.1.1\njsonpath-rw==1.4.0\njsonpath-rw-ext==1.2.2\npackaging==21.3\npbr==6.1.1\npluggy==1.0.0\nply==3.11\npy==1.11.0\npyparsing==3.1.4\npytest==7.0.1\nPyYAML==6.0.1\nsix==1.17.0\ntomli==1.2.3\ntyping_extensions==4.1.1\nurllib3==1.26.20\nwsgi_intercept==1.13.1\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: gabbi\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - colorama==0.4.5\n - decorator==5.1.1\n - importlib-metadata==4.8.3\n - iniconfig==1.1.1\n - jsonpath-rw==1.4.0\n - jsonpath-rw-ext==1.2.2\n - packaging==21.3\n - pbr==6.1.1\n - pluggy==1.0.0\n - ply==3.11\n - py==1.11.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - pyyaml==6.0.1\n - six==1.17.0\n - tomli==1.2.3\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - wsgi-intercept==1.13.1\n - zipp==3.6.0\nprefix: /opt/conda/envs/gabbi\n"},"FAIL_TO_PASS":{"kind":"list like","value":["gabbi/tests/test_driver.py::DriverTest::test_build_url_target","gabbi/tests/test_driver.py::DriverTest::test_build_url_target_forced_ssl","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_host_localhost","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_hostport_localhost","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_localhost","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_long","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_no_port","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_with_port","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport_with_prefix","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port80_url","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port_url","gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_url"],"string":"[\n \"gabbi/tests/test_driver.py::DriverTest::test_build_url_target\",\n \"gabbi/tests/test_driver.py::DriverTest::test_build_url_target_forced_ssl\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_host_localhost\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_hostport_localhost\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_localhost\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_long\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_no_port\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_with_port\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport_with_prefix\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port80_url\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port_url\",\n \"gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_url\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["gabbi/tests/test_driver.py::DriverTest::test_build_require_ssl","gabbi/tests/test_driver.py::DriverTest::test_build_requires_host_or_intercept","gabbi/tests/test_driver.py::DriverTest::test_driver_loads_two_tests","gabbi/tests/test_driver.py::DriverTest::test_driver_prefix","gabbi/tests/test_runner.py::RunnerTest::test_custom_response_handler","gabbi/tests/test_runner.py::RunnerTest::test_exit_code","gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing","gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing_standard_port","gabbi/tests/test_utils.py::BinaryTypesTest::test_binary","gabbi/tests/test_utils.py::BinaryTypesTest::test_not_binary","gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_bad_params","gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_both","gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_charset","gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_multiple_params","gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_with_charset","gabbi/tests/test_utils.py::ColorizeTest::test_colorize_missing_color","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_already_bracket","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_full","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl_weird_port","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_no_double_colon","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_not_ssl_on_443","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port_and_ssl","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_prefix","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_preserve_query","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_simple","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl","gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl_on_80"],"string":"[\n \"gabbi/tests/test_driver.py::DriverTest::test_build_require_ssl\",\n \"gabbi/tests/test_driver.py::DriverTest::test_build_requires_host_or_intercept\",\n \"gabbi/tests/test_driver.py::DriverTest::test_driver_loads_two_tests\",\n \"gabbi/tests/test_driver.py::DriverTest::test_driver_prefix\",\n \"gabbi/tests/test_runner.py::RunnerTest::test_custom_response_handler\",\n \"gabbi/tests/test_runner.py::RunnerTest::test_exit_code\",\n \"gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing\",\n \"gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing_standard_port\",\n \"gabbi/tests/test_utils.py::BinaryTypesTest::test_binary\",\n \"gabbi/tests/test_utils.py::BinaryTypesTest::test_not_binary\",\n \"gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_bad_params\",\n \"gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_both\",\n \"gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_charset\",\n \"gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_multiple_params\",\n \"gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_with_charset\",\n \"gabbi/tests/test_utils.py::ColorizeTest::test_colorize_missing_color\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_already_bracket\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_full\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl_weird_port\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_no_double_colon\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_not_ssl_on_443\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port_and_ssl\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_prefix\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_preserve_query\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_simple\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl\",\n \"gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl_on_80\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":582,"string":"582"}}},{"rowIdx":582,"cells":{"instance_id":{"kind":"string","value":"kytos__python-openflow-99"},"base_commit":{"kind":"string","value":"1b4d191de2e51695ab94395d4f0ba93a7f0e98f8"},"created_at":{"kind":"string","value":"2016-06-13 23:18:31"},"environment_setup_commit":{"kind":"string","value":"1b4d191de2e51695ab94395d4f0ba93a7f0e98f8"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/pyof/v0x01/controller2switch/packet_out.py b/pyof/v0x01/controller2switch/packet_out.py\nindex 78cb669..e7c9965 100644\n--- a/pyof/v0x01/controller2switch/packet_out.py\n+++ b/pyof/v0x01/controller2switch/packet_out.py\n@@ -7,12 +7,16 @@ uses the OFPT_PACKET_OUT message\"\"\"\n \n # Local source tree imports\n from pyof.v0x01.common import header as of_header\n+from pyof.v0x01.common.phy_port import Port\n from pyof.v0x01.controller2switch import common\n from pyof.v0x01.foundation import base\n from pyof.v0x01.foundation import basic_types\n+from pyof.v0x01.foundation.exceptions import ValidationError\n \n # Classes\n \n+#: in_port valid virtual port values, for validation\n+_VIRT_IN_PORTS = (Port.OFPP_LOCAL, Port.OFPP_CONTROLLER, Port.OFPP_NONE)\n \n class PacketOut(base.GenericMessage):\n \"\"\"\n@@ -47,3 +51,25 @@ class PacketOut(base.GenericMessage):\n self.actions_len = actions_len\n self.actions = [] if actions is None else actions\n self.data = data\n+\n+ def validate(self):\n+ if not super().is_valid():\n+ raise ValidationError()\n+ self._validate_in_port()\n+\n+ def is_valid(self):\n+ try:\n+ self.validate()\n+ return True\n+ except ValidationError:\n+ return False\n+\n+ def _validate_in_port(self):\n+ port = self.in_port\n+ valid = True\n+ if isinstance(port, int) and (port < 1 or port >= Port.OFPP_MAX.value):\n+ valid = False\n+ elif isinstance(port, Port) and port not in _VIRT_IN_PORTS:\n+ valid = False\n+ if not valid:\n+ raise ValidationError('{} is not a valid input port.'.format(port))\ndiff --git a/pyof/v0x01/foundation/exceptions.py b/pyof/v0x01/foundation/exceptions.py\nindex 0dab2cd..13e9296 100644\n--- a/pyof/v0x01/foundation/exceptions.py\n+++ b/pyof/v0x01/foundation/exceptions.py\n@@ -1,6 +1,11 @@\n \"\"\"Exceptions defined on this Library\"\"\"\n \n \n+class ValidationError(Exception):\n+ \"\"\"Can be used directly or inherited by specific validation errors.\"\"\"\n+ pass\n+\n+\n class MethodNotImplemented(Exception):\n \"\"\"Exception to be raised when a method is not implemented\"\"\"\n def __init__(self, message=None):\n@@ -33,44 +38,11 @@ class WrongListItemType(Exception):\n return message\n \n \n-class PADHasNoValue(Exception):\n- \"\"\"Exception raised when user tries to set a value on a PAD attribute\"\"\"\n- def __str__(self):\n- return \"You can't set a value on a PAD attribute\"\n-\n-\n-class AttributeTypeError(Exception):\n- \"\"\"Error raise when the attribute is not of the expected type\n- defined on the class definition\"\"\"\n-\n- def __init__(self, item, item_class, expected_class):\n- super().__init__()\n- self.item = item\n- self.item_class = item_class\n- self.expected_class = expected_class\n-\n- def __str__(self):\n- msg = \"Unexpected value '{}' \".format(str(self.item))\n- msg += \"with class '{}' \".format(str(self.item_class))\n- msg += \"and expected class '{}'\".format(str(self.expected_class))\n- return msg\n-\n-\n class NotBinaryData(Exception):\n \"\"\"Error raised when the content of a BinaryData attribute is not binary\"\"\"\n def __str__(self):\n return \"The content of this variable needs to be binary data\"\n \n \n-class ValidationError(Exception):\n- \"\"\"Error on validate message or struct\"\"\"\n- def __init__(self, msg=\"Error on validate message\"):\n- super().__init__()\n- self.msg = msg\n-\n- def __str__(self):\n- return self.msg\n-\n-\n class UnpackException(Exception):\n pass\n"},"problem_statement":{"kind":"string","value":"Check 1.0.1 and 1.0.2 compliance"},"repo":{"kind":"string","value":"kytos/python-openflow"},"test_patch":{"kind":"string","value":"diff --git a/tests/v0x01/test_controller2switch/test_packet_out.py b/tests/v0x01/test_controller2switch/test_packet_out.py\nindex 38dfd5a..4130c77 100644\n--- a/tests/v0x01/test_controller2switch/test_packet_out.py\n+++ b/tests/v0x01/test_controller2switch/test_packet_out.py\n@@ -1,11 +1,12 @@\n import unittest\n \n from pyof.v0x01.common import phy_port\n+from pyof.v0x01.common.phy_port import Port\n from pyof.v0x01.controller2switch import packet_out\n+from pyof.v0x01.foundation.exceptions import ValidationError\n \n \n class TestPacketOut(unittest.TestCase):\n-\n def setUp(self):\n self.message = packet_out.PacketOut()\n self.message.header.xid = 80\n@@ -28,3 +29,35 @@ class TestPacketOut(unittest.TestCase):\n \"\"\"[Controller2Switch/PacketOut] - unpacking\"\"\"\n # TODO\n pass\n+\n+ def test_valid_virtual_in_ports(self):\n+ \"\"\"Valid virtual ports as defined in 1.0.1 spec.\"\"\"\n+ valid = (Port.OFPP_LOCAL, Port.OFPP_CONTROLLER, Port.OFPP_NONE)\n+ msg = packet_out.PacketOut()\n+ for in_port in valid:\n+ msg.in_port = in_port\n+ self.assertTrue(msg.is_valid())\n+\n+ def test_invalid_virtual_in_ports(self):\n+ \"\"\"Invalid virtual ports as defined in 1.0.1 spec.\"\"\"\n+ invalid = (Port.OFPP_IN_PORT, Port.OFPP_TABLE, Port.OFPP_NORMAL,\n+ Port.OFPP_FLOOD, Port.OFPP_ALL)\n+ for in_port in invalid:\n+ self.message.in_port = in_port\n+ self.assertFalse(self.message.is_valid())\n+ self.assertRaises(ValidationError, self.message.validate)\n+\n+ def test_valid_physical_in_ports(self):\n+ \"\"\"Physical port limits from 1.0.0 spec.\"\"\"\n+ max_valid = int(Port.OFPP_MAX.value) - 1\n+ for in_port in (1, max_valid):\n+ self.message.in_port = in_port\n+ self.assertTrue(self.message.is_valid())\n+\n+ def test_invalid_physical_in_port(self):\n+ \"\"\"Physical port limits from 1.0.0 spec.\"\"\"\n+ max_valid = int(Port.OFPP_MAX.value) - 1\n+ for in_port in (-1, 0, max_valid + 1, max_valid + 2):\n+ self.message.in_port = in_port\n+ self.assertFalse(self.message.is_valid())\n+ self.assertRaises(ValidationError, self.message.validate)\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_many_modified_files\",\n \"has_many_hunks\",\n \"has_pytest_match_arg\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 3,\n \"test_score\": 3\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"unknown"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\",\n \"pytest-cov\",\n \"coverage\"\n ],\n \"pre_install\": null,\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"coverage==7.8.0\nexceptiongroup==1.2.2\niniconfig==2.1.0\n-e git+https://github.com/kytos/python-openflow.git@1b4d191de2e51695ab94395d4f0ba93a7f0e98f8#egg=Kytos_OpenFlow_Parser_library\npackaging==24.2\npluggy==1.5.0\npytest==8.3.5\npytest-cov==6.0.0\ntomli==2.2.1\n"},"environment":{"kind":"string","value":"name: python-openflow\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - coverage==7.8.0\n - exceptiongroup==1.2.2\n - iniconfig==2.1.0\n - packaging==24.2\n - pluggy==1.5.0\n - pytest==8.3.5\n - pytest-cov==6.0.0\n - tomli==2.2.1\nprefix: /opt/conda/envs/python-openflow\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_invalid_physical_in_port","tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_invalid_virtual_in_ports"],"string":"[\n \"tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_invalid_physical_in_port\",\n \"tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_invalid_virtual_in_ports\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_get_size","tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_valid_physical_in_ports","tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_valid_virtual_in_ports"],"string":"[\n \"tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_get_size\",\n \"tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_valid_physical_in_ports\",\n \"tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_valid_virtual_in_ports\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":583,"string":"583"}}},{"rowIdx":583,"cells":{"instance_id":{"kind":"string","value":"mozilla__bleach-205"},"base_commit":{"kind":"string","value":"2235b8fcadc8abef3a2845bb0ce67206982f3489"},"created_at":{"kind":"string","value":"2016-06-14 16:16:47"},"environment_setup_commit":{"kind":"string","value":"edd91a00e1c50cebbc512c7db61897ad3d0ba00a"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/bleach/__init__.py b/bleach/__init__.py\nindex 3092cb7..ac163d1 100644\n--- a/bleach/__init__.py\n+++ b/bleach/__init__.py\n@@ -315,7 +315,7 @@ def linkify(text, callbacks=DEFAULT_CALLBACKS, skip_pre=False,\n if node.tag == ETREE_TAG('pre') and skip_pre:\n linkify_nodes(node, False)\n elif not (node in _seen):\n- linkify_nodes(node, True)\n+ linkify_nodes(node, parse_text)\n \n current_child += 1\n \n"},"problem_statement":{"kind":"string","value":"Children of
 tags should not be linkified when skip_pre=True (patch attached)\nThe children of `pre` tags should not be linkified when `skip_pre` is on \r\n\r\n```\r\ndiff --git a/bleach/__init__.py b/bleach/__init__.py\r\nindex 48b6512..4c2dd1b 100644\r\n--- a/bleach/__init__.py\r\n+++ b/bleach/__init__.py\r\n@@ -300,7 +300,7 @@ def linkify(text, callbacks=DEFAULT_CALLBACKS, skip_pre=False,\r\n                 if node.tag == ETREE_TAG('pre') and skip_pre:\r\n                     linkify_nodes(node, False)\r\n                 elif not (node in _seen):\r\n-                    linkify_nodes(node, True)\r\n+                    linkify_nodes(node, parse_text)\r\n \r\n             current_child += 1\r\n \r\ndiff --git a/bleach/tests/test_links.py b/bleach/tests/test_links.py\r\nindex 62da8d1..ae0fba7 100644\r\n--- a/bleach/tests/test_links.py\r\n+++ b/bleach/tests/test_links.py\r\n@@ -314,6 +314,13 @@ def test_skip_pre():\r\n     eq_(nofollowed, linkify(already_linked))\r\n     eq_(nofollowed, linkify(already_linked, skip_pre=True))\r\n \r\n+def test_skip_pre_child():\r\n+    # Don't linkify the children of pre tags.\r\n+    intext = '
http://foo.com
http://bar.com'\r\n+ expect = '
http://foo.com
http://bar.com'\r\n+ output = linkify(intext, skip_pre=True)\r\n+ eq_(expect, output)\r\n+\r\n \r\n def test_libgl():\r\n \"\"\"libgl.so.1 should not be linkified.\"\"\"\r\n```"},"repo":{"kind":"string","value":"mozilla/bleach"},"test_patch":{"kind":"string","value":"diff --git a/bleach/tests/test_links.py b/bleach/tests/test_links.py\nindex 62da8d1..2958f5e 100644\n--- a/bleach/tests/test_links.py\n+++ b/bleach/tests/test_links.py\n@@ -314,6 +314,13 @@ def test_skip_pre():\n eq_(nofollowed, linkify(already_linked))\n eq_(nofollowed, linkify(already_linked, skip_pre=True))\n \n+ eq_(\n+ linkify('
http://example.com
http://example.com',\n+ skip_pre=True),\n+ ('
http://example.com
'\n+ 'http://example.com')\n+ )\n+\n \n def test_libgl():\n \"\"\"libgl.so.1 should not be linkified.\"\"\"\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_hyperlinks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 1,\n \"test_score\": 3\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"1.4"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"nose\",\n \"flake8\",\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"alabaster==0.7.13\nattrs==22.2.0\nBabel==2.11.0\n-e git+https://github.com/mozilla/bleach.git@2235b8fcadc8abef3a2845bb0ce67206982f3489#egg=bleach\ncertifi==2021.5.30\ncffi==1.15.1\ncharset-normalizer==2.0.12\ncolorama==0.4.5\ncryptography==40.0.2\ndistlib==0.3.9\ndocutils==0.17.1\nfilelock==3.4.1\nflake8==5.0.4\nhtml5lib==0.9999999\nidna==3.10\nimagesize==1.4.1\nimportlib-metadata==4.2.0\nimportlib-resources==5.4.0\niniconfig==1.1.1\njeepney==0.7.1\nJinja2==3.0.3\nkeyring==23.4.1\nMarkupSafe==2.0.1\nmccabe==0.7.0\nnose==1.3.7\nordereddict==1.1\npackaging==21.3\npkginfo==1.10.0\nplatformdirs==2.4.0\npluggy==1.0.0\npy==1.11.0\npycodestyle==2.9.1\npycparser==2.21\npyflakes==2.5.0\nPygments==2.14.0\npyparsing==3.1.4\npytest==7.0.1\npytz==2025.2\nreadme-renderer==34.0\nrequests==2.27.1\nrequests-toolbelt==1.0.0\nrfc3986==1.5.0\nSecretStorage==3.3.3\nsix==1.17.0\nsnowballstemmer==2.2.0\nSphinx==4.3.2\nsphinxcontrib-applehelp==1.0.2\nsphinxcontrib-devhelp==1.0.2\nsphinxcontrib-htmlhelp==2.0.0\nsphinxcontrib-jsmath==1.0.1\nsphinxcontrib-qthelp==1.0.3\nsphinxcontrib-serializinghtml==1.1.5\ntoml==0.10.2\ntomli==1.2.3\ntox==3.28.0\ntqdm==4.64.1\ntwine==3.8.0\ntyping_extensions==4.1.1\nurllib3==1.26.20\nvirtualenv==20.16.2\nwebencodings==0.5.1\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: bleach\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - alabaster==0.7.13\n - attrs==22.2.0\n - babel==2.11.0\n - cffi==1.15.1\n - charset-normalizer==2.0.12\n - colorama==0.4.5\n - cryptography==40.0.2\n - distlib==0.3.9\n - docutils==0.17.1\n - filelock==3.4.1\n - flake8==5.0.4\n - html5lib==0.9999999\n - idna==3.10\n - imagesize==1.4.1\n - importlib-metadata==4.2.0\n - importlib-resources==5.4.0\n - iniconfig==1.1.1\n - jeepney==0.7.1\n - jinja2==3.0.3\n - keyring==23.4.1\n - markupsafe==2.0.1\n - mccabe==0.7.0\n - nose==1.3.7\n - ordereddict==1.1\n - packaging==21.3\n - pkginfo==1.10.0\n - platformdirs==2.4.0\n - pluggy==1.0.0\n - py==1.11.0\n - pycodestyle==2.9.1\n - pycparser==2.21\n - pyflakes==2.5.0\n - pygments==2.14.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - pytz==2025.2\n - readme-renderer==34.0\n - requests==2.27.1\n - requests-toolbelt==1.0.0\n - rfc3986==1.5.0\n - secretstorage==3.3.3\n - six==1.17.0\n - snowballstemmer==2.2.0\n - sphinx==4.3.2\n - sphinxcontrib-applehelp==1.0.2\n - sphinxcontrib-devhelp==1.0.2\n - sphinxcontrib-htmlhelp==2.0.0\n - sphinxcontrib-jsmath==1.0.1\n - sphinxcontrib-qthelp==1.0.3\n - sphinxcontrib-serializinghtml==1.1.5\n - toml==0.10.2\n - tomli==1.2.3\n - tox==3.28.0\n - tqdm==4.64.1\n - twine==3.8.0\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - virtualenv==20.16.2\n - webencodings==0.5.1\n - zipp==3.6.0\nprefix: /opt/conda/envs/bleach\n"},"FAIL_TO_PASS":{"kind":"list like","value":["bleach/tests/test_links.py::test_skip_pre"],"string":"[\n \"bleach/tests/test_links.py::test_skip_pre\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["bleach/tests/test_links.py::test_empty","bleach/tests/test_links.py::test_simple_link","bleach/tests/test_links.py::test_trailing_slash","bleach/tests/test_links.py::test_mangle_link","bleach/tests/test_links.py::test_mangle_text","bleach/tests/test_links.py::test_set_attrs","bleach/tests/test_links.py::test_only_proto_links","bleach/tests/test_links.py::test_stop_email","bleach/tests/test_links.py::test_tlds","bleach/tests/test_links.py::test_escaping","bleach/tests/test_links.py::test_nofollow_off","bleach/tests/test_links.py::test_link_in_html","bleach/tests/test_links.py::test_links_https","bleach/tests/test_links.py::test_add_rel_nofollow","bleach/tests/test_links.py::test_url_with_path","bleach/tests/test_links.py::test_link_ftp","bleach/tests/test_links.py::test_link_query","bleach/tests/test_links.py::test_link_fragment","bleach/tests/test_links.py::test_link_entities","bleach/tests/test_links.py::test_escaped_html","bleach/tests/test_links.py::test_link_http_complete","bleach/tests/test_links.py::test_non_url","bleach/tests/test_links.py::test_javascript_url","bleach/tests/test_links.py::test_unsafe_url","bleach/tests/test_links.py::test_libgl","bleach/tests/test_links.py::test_end_of_clause","bleach/tests/test_links.py::test_sarcasm","bleach/tests/test_links.py::test_parentheses_with_removing","bleach/tests/test_links.py::test_tokenizer","bleach/tests/test_links.py::test_ignore_bad_protocols","bleach/tests/test_links.py::test_max_recursion_depth","bleach/tests/test_links.py::test_link_emails_and_urls","bleach/tests/test_links.py::test_links_case_insensitive","bleach/tests/test_links.py::test_elements_inside_links","bleach/tests/test_links.py::test_remove_first_childlink"],"string":"[\n \"bleach/tests/test_links.py::test_empty\",\n \"bleach/tests/test_links.py::test_simple_link\",\n \"bleach/tests/test_links.py::test_trailing_slash\",\n \"bleach/tests/test_links.py::test_mangle_link\",\n \"bleach/tests/test_links.py::test_mangle_text\",\n \"bleach/tests/test_links.py::test_set_attrs\",\n \"bleach/tests/test_links.py::test_only_proto_links\",\n \"bleach/tests/test_links.py::test_stop_email\",\n \"bleach/tests/test_links.py::test_tlds\",\n \"bleach/tests/test_links.py::test_escaping\",\n \"bleach/tests/test_links.py::test_nofollow_off\",\n \"bleach/tests/test_links.py::test_link_in_html\",\n \"bleach/tests/test_links.py::test_links_https\",\n \"bleach/tests/test_links.py::test_add_rel_nofollow\",\n \"bleach/tests/test_links.py::test_url_with_path\",\n \"bleach/tests/test_links.py::test_link_ftp\",\n \"bleach/tests/test_links.py::test_link_query\",\n \"bleach/tests/test_links.py::test_link_fragment\",\n \"bleach/tests/test_links.py::test_link_entities\",\n \"bleach/tests/test_links.py::test_escaped_html\",\n \"bleach/tests/test_links.py::test_link_http_complete\",\n \"bleach/tests/test_links.py::test_non_url\",\n \"bleach/tests/test_links.py::test_javascript_url\",\n \"bleach/tests/test_links.py::test_unsafe_url\",\n \"bleach/tests/test_links.py::test_libgl\",\n \"bleach/tests/test_links.py::test_end_of_clause\",\n \"bleach/tests/test_links.py::test_sarcasm\",\n \"bleach/tests/test_links.py::test_parentheses_with_removing\",\n \"bleach/tests/test_links.py::test_tokenizer\",\n \"bleach/tests/test_links.py::test_ignore_bad_protocols\",\n \"bleach/tests/test_links.py::test_max_recursion_depth\",\n \"bleach/tests/test_links.py::test_link_emails_and_urls\",\n \"bleach/tests/test_links.py::test_links_case_insensitive\",\n \"bleach/tests/test_links.py::test_elements_inside_links\",\n \"bleach/tests/test_links.py::test_remove_first_childlink\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":584,"string":"584"}}},{"rowIdx":584,"cells":{"instance_id":{"kind":"string","value":"Backblaze__B2_Command_Line_Tool-173"},"base_commit":{"kind":"string","value":"ab2b5b4e3dc2c8b52b28592c7414ebb4646034e2"},"created_at":{"kind":"string","value":"2016-06-14 20:22:17"},"environment_setup_commit":{"kind":"string","value":"01c4e89f63f38b9efa6a6fa63f54cd556a0b5305"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/b2/sync.py b/b2/sync.py\nindex c3c4ad9..cffdc81 100644\n--- a/b2/sync.py\n+++ b/b2/sync.py\n@@ -67,12 +67,15 @@ class SyncReport(object):\n self.closed = False\n self.lock = threading.Lock()\n self._update_progress()\n+ self.warnings = []\n \n def close(self):\n with self.lock:\n if not self.no_progress:\n self._print_line('', False)\n self.closed = True\n+ for warning in self.warnings:\n+ self._print_line(warning, True)\n \n def __enter__(self):\n return self\n@@ -185,6 +188,9 @@ class SyncReport(object):\n self.transfer_bytes += byte_delta\n self._update_progress()\n \n+ def local_access_error(self, path):\n+ self.warnings.append('WARNING: %s could not be accessed (broken symlink?)' % (path,))\n+\n \n class SyncFileReporter(AbstractProgressListener):\n \"\"\"\n@@ -453,13 +459,17 @@ class AbstractFolder(object):\n \"\"\"\n \n @abstractmethod\n- def all_files(self):\n+ def all_files(self, reporter):\n \"\"\"\n Returns an iterator over all of the files in the folder, in\n the order that B2 uses.\n \n No matter what the folder separator on the local file system\n is, \"/\" is used in the returned file names.\n+\n+ If a file is found, but does not exist (for example due to\n+ a broken symlink or a race), reporter will be informed about\n+ each such problem.\n \"\"\"\n \n @abstractmethod\n@@ -494,9 +504,9 @@ class LocalFolder(AbstractFolder):\n def folder_type(self):\n return 'local'\n \n- def all_files(self):\n+ def all_files(self, reporter):\n prefix_len = len(self.root) + 1 # include trailing '/' in prefix length\n- for relative_path in self._walk_relative_paths(prefix_len, self.root):\n+ for relative_path in self._walk_relative_paths(prefix_len, self.root, reporter):\n yield self._make_file(relative_path)\n \n def make_full_path(self, file_name):\n@@ -514,7 +524,7 @@ class LocalFolder(AbstractFolder):\n elif not os.path.isdir(self.root):\n raise Exception('%s is not a directory' % (self.root,))\n \n- def _walk_relative_paths(self, prefix_len, dir_path):\n+ def _walk_relative_paths(self, prefix_len, dir_path, reporter):\n \"\"\"\n Yields all of the file names anywhere under this folder, in the\n order they would appear in B2.\n@@ -535,16 +545,21 @@ class LocalFolder(AbstractFolder):\n )\n full_path = os.path.join(dir_path, name)\n relative_path = full_path[prefix_len:]\n- if os.path.isdir(full_path):\n- name += six.u('/')\n- dirs.add(name)\n- names[name] = (full_path, relative_path)\n+ # Skip broken symlinks or other inaccessible files\n+ if not os.path.exists(full_path):\n+ if reporter is not None:\n+ reporter.local_access_error(full_path)\n+ else:\n+ if os.path.isdir(full_path):\n+ name += six.u('/')\n+ dirs.add(name)\n+ names[name] = (full_path, relative_path)\n \n # Yield all of the answers\n for name in sorted(names):\n (full_path, relative_path) = names[name]\n if name in dirs:\n- for rp in self._walk_relative_paths(prefix_len, full_path):\n+ for rp in self._walk_relative_paths(prefix_len, full_path, reporter):\n yield rp\n else:\n yield relative_path\n@@ -573,7 +588,7 @@ class B2Folder(AbstractFolder):\n self.bucket = api.get_bucket_by_name(bucket_name)\n self.prefix = '' if self.folder_name == '' else self.folder_name + '/'\n \n- def all_files(self):\n+ def all_files(self, reporter):\n current_name = None\n current_versions = []\n for (file_version_info, folder_name) in self.bucket.ls(\n@@ -625,7 +640,7 @@ def next_or_none(iterator):\n return None\n \n \n-def zip_folders(folder_a, folder_b, exclusions=tuple()):\n+def zip_folders(folder_a, folder_b, reporter, exclusions=tuple()):\n \"\"\"\n An iterator over all of the files in the union of two folders,\n matching file names.\n@@ -637,8 +652,10 @@ def zip_folders(folder_a, folder_b, exclusions=tuple()):\n :param folder_b: A Folder object.\n \"\"\"\n \n- iter_a = (f for f in folder_a.all_files() if not any(ex.match(f.name) for ex in exclusions))\n- iter_b = folder_b.all_files()\n+ iter_a = (\n+ f for f in folder_a.all_files(reporter) if not any(ex.match(f.name) for ex in exclusions)\n+ )\n+ iter_b = folder_b.all_files(reporter)\n \n current_a = next_or_none(iter_a)\n current_b = next_or_none(iter_b)\n@@ -810,7 +827,7 @@ def make_folder_sync_actions(source_folder, dest_folder, args, now_millis, repor\n ('b2', 'local'), ('local', 'b2')\n ]:\n raise NotImplementedError(\"Sync support only local-to-b2 and b2-to-local\")\n- for (source_file, dest_file) in zip_folders(source_folder, dest_folder, exclusions):\n+ for (source_file, dest_file) in zip_folders(source_folder, dest_folder, reporter, exclusions):\n if source_folder.folder_type() == 'local':\n if source_file is not None:\n reporter.update_compare(1)\n@@ -863,7 +880,9 @@ def count_files(local_folder, reporter):\n \"\"\"\n Counts all of the files in a local folder.\n \"\"\"\n- for _ in local_folder.all_files():\n+ # Don't pass in a reporter to all_files. Broken symlinks will be reported\n+ # during the next pass when the source and dest files are compared.\n+ for _ in local_folder.all_files(None):\n reporter.update_local(1)\n reporter.end_local()\n \n"},"problem_statement":{"kind":"string","value":"Broken symlink break sync\nI had this issue where one of my sysmlinks was broken and b2 tool broke, this is the stack trace:\r\n\r\n```\r\nTraceback (most recent call last): \r\n File \"/usr/local/bin/b2\", line 9, in \r\n load_entry_point('b2==0.5.4', 'console_scripts', 'b2')()\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/console_tool.py\", line 861, in main\r\n exit_status = ct.run_command(decoded_argv)\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/console_tool.py\", line 789, in run_command\r\n return command.run(args)\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/console_tool.py\", line 609, in run\r\n max_workers=max_workers\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/sync.py\", line 877, in sync_folders\r\n source_folder, dest_folder, args, now_millis, reporter\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/sync.py\", line 777, in make_folder_sync_actions\r\n for (source_file, dest_file) in zip_folders(source_folder, dest_folder):\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/sync.py\", line 646, in zip_folders\r\n current_a = next_or_none(iter_a)\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/sync.py\", line 620, in next_or_none\r\n return six.advance_iterator(iterator)\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/sync.py\", line 499, in all_files\r\n yield self._make_file(relative_path)\r\n File \"/usr/local/lib/python2.7/dist-packages/b2/sync.py\", line 553, in _make_file\r\n mod_time = int(round(os.path.getmtime(full_path) * 1000))\r\n File \"/usr/lib/python2.7/genericpath.py\", line 54, in getmtime\r\n return os.stat(filename).st_mtime\r\nOSError: [Errno 2] No such file or directory: '/media/2a9074d0-4788-45ab-bfae-fc46427c69fa/PersonalData/some-broken-symlink'\r\n\r\n```"},"repo":{"kind":"string","value":"Backblaze/B2_Command_Line_Tool"},"test_patch":{"kind":"string","value":"diff --git a/test/test_sync.py b/test/test_sync.py\nindex ad2b140..9102b6e 100644\n--- a/test/test_sync.py\n+++ b/test/test_sync.py\n@@ -37,36 +37,58 @@ def write_file(path, contents):\n f.write(contents)\n \n \n-def create_files(root_dir, relative_paths):\n- for relative_path in relative_paths:\n- full_path = os.path.join(root_dir, relative_path)\n- write_file(full_path, b'')\n+class TestLocalFolder(unittest.TestCase):\n+ NAMES = [\n+ six.u('.dot_file'), six.u('hello.'), six.u('hello/a/1'), six.u('hello/a/2'),\n+ six.u('hello/b'), six.u('hello0'), six.u('\\u81ea\\u7531')\n+ ]\n \n+ def setUp(self):\n+ self.reporter = MagicMock()\n+\n+ @classmethod\n+ def _create_files(cls, root_dir, relative_paths):\n+ for relative_path in relative_paths:\n+ full_path = os.path.join(root_dir, relative_path)\n+ write_file(full_path, b'')\n+\n+ def _prepare_folder(self, root_dir, broken_symlink=False):\n+ self._create_files(root_dir, self.NAMES)\n+ if broken_symlink:\n+ os.symlink(\n+ os.path.join(root_dir, 'non_existant_file'), os.path.join(root_dir, 'bad_symlink')\n+ )\n+ return LocalFolder(root_dir)\n \n-class TestLocalFolder(unittest.TestCase):\n def test_slash_sorting(self):\n # '/' should sort between '.' and '0'\n- names = [\n- six.u('.dot_file'), six.u('hello.'), six.u('hello/a/1'), six.u('hello/a/2'),\n- six.u('hello/b'), six.u('hello0'), six.u('\\u81ea\\u7531')\n- ]\n with TempDir() as tmpdir:\n- create_files(tmpdir, names)\n- folder = LocalFolder(tmpdir)\n- actual_names = list(f.name for f in folder.all_files())\n- self.assertEqual(names, actual_names)\n+ folder = self._prepare_folder(tmpdir)\n+ actual_names = list(f.name for f in folder.all_files(self.reporter))\n+ self.assertEqual(self.NAMES, actual_names)\n+ self.reporter.local_access_error.assert_not_called()\n+\n+ def test_broken_symlink(self):\n+ with TempDir() as tmpdir:\n+ folder = self._prepare_folder(tmpdir, broken_symlink=True)\n+ for f in folder.all_files(self.reporter):\n+ pass # just generate all the files\n+ self.reporter.local_access_error.assert_called_once_with(\n+ os.path.join(tmpdir, 'bad_symlink')\n+ )\n \n \n class TestB2Folder(unittest.TestCase):\n def setUp(self):\n self.bucket = MagicMock()\n self.api = MagicMock()\n+ self.reporter = MagicMock()\n self.api.get_bucket_by_name.return_value = self.bucket\n self.b2_folder = B2Folder('bucket-name', 'folder', self.api)\n \n def test_empty(self):\n self.bucket.ls.return_value = []\n- self.assertEqual([], list(self.b2_folder.all_files()))\n+ self.assertEqual([], list(self.b2_folder.all_files(self.reporter)))\n \n def test_multiple_versions(self):\n # Test two files, to cover the yield within the loop, and\n@@ -102,7 +124,7 @@ class TestB2Folder(unittest.TestCase):\n [\n \"File(a.txt, [FileVersion('a2', 'folder/a.txt', 2000, 'upload'), FileVersion('a1', 'folder/a.txt', 1000, 'upload')])\",\n \"File(b.txt, [FileVersion('b2', 'folder/b.txt', 2000, 'upload'), FileVersion('b1', 'folder/b.txt', 1000, 'upload')])\",\n- ], [str(f) for f in self.b2_folder.all_files()]\n+ ], [str(f) for f in self.b2_folder.all_files(self.reporter)]\n )\n \n \n@@ -111,7 +133,7 @@ class FakeFolder(AbstractFolder):\n self.f_type = f_type\n self.files = files\n \n- def all_files(self):\n+ def all_files(self, reporter):\n return iter(self.files)\n \n def folder_type(self):\n@@ -150,16 +172,19 @@ class TestParseSyncFolder(unittest.TestCase):\n \n \n class TestZipFolders(unittest.TestCase):\n+ def setUp(self):\n+ self.reporter = MagicMock()\n+\n def test_empty(self):\n folder_a = FakeFolder('b2', [])\n folder_b = FakeFolder('b2', [])\n- self.assertEqual([], list(zip_folders(folder_a, folder_b)))\n+ self.assertEqual([], list(zip_folders(folder_a, folder_b, self.reporter)))\n \n def test_one_empty(self):\n file_a1 = File(\"a.txt\", [FileVersion(\"a\", \"a\", 100, \"upload\", 10)])\n folder_a = FakeFolder('b2', [file_a1])\n folder_b = FakeFolder('b2', [])\n- self.assertEqual([(file_a1, None)], list(zip_folders(folder_a, folder_b)))\n+ self.assertEqual([(file_a1, None)], list(zip_folders(folder_a, folder_b, self.reporter)))\n \n def test_two(self):\n file_a1 = File(\"a.txt\", [FileVersion(\"a\", \"a\", 100, \"upload\", 10)])\n@@ -174,9 +199,22 @@ class TestZipFolders(unittest.TestCase):\n [\n (file_a1, None), (file_a2, file_b1), (file_a3, None), (None, file_b2),\n (file_a4, None)\n- ], list(zip_folders(folder_a, folder_b))\n+ ], list(zip_folders(folder_a, folder_b, self.reporter))\n )\n \n+ def test_pass_reporter_to_folder(self):\n+ \"\"\"\n+ Check that the zip_folders() function passes the reporter through\n+ to both folders.\n+ \"\"\"\n+ folder_a = MagicMock()\n+ folder_b = MagicMock()\n+ folder_a.all_files = MagicMock(return_value=iter([]))\n+ folder_b.all_files = MagicMock(return_value=iter([]))\n+ self.assertEqual([], list(zip_folders(folder_a, folder_b, self.reporter)))\n+ folder_a.all_files.assert_called_once_with(self.reporter)\n+ folder_b.all_files.assert_called_once_with(self.reporter)\n+\n \n class FakeArgs(object):\n \"\"\"\ndiff --git a/test_b2_command_line.py b/test_b2_command_line.py\nindex 8d23678..0628248 100644\n--- a/test_b2_command_line.py\n+++ b/test_b2_command_line.py\n@@ -200,6 +200,8 @@ class CommandLine(object):\n sys.exit(1)\n if expected_pattern is not None:\n if re.search(expected_pattern, stdout) is None:\n+ print('STDOUT:')\n+ print(stdout)\n error_and_exit('did not match pattern: ' + expected_pattern)\n return stdout\n \n@@ -469,8 +471,12 @@ def _sync_test_using_dir(b2_tool, bucket_name, dir_):\n write_file(p('a'), b'hello')\n write_file(p('b'), b'hello')\n write_file(p('c'), b'hello')\n+ os.symlink('broken', p('d'))\n \n- b2_tool.should_succeed(['sync', '--noProgress', dir_path, b2_sync_point])\n+ b2_tool.should_succeed(\n+ ['sync', '--noProgress', dir_path, b2_sync_point],\n+ expected_pattern=\"/d could not be accessed\"\n+ )\n file_versions = b2_tool.list_file_versions(bucket_name)\n should_equal(\n [\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 1,\n \"test_score\": 2\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"0.5"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"nose\",\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements.txt\",\n \"requirements-test.txt\",\n \"requirements-setup.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\n-e git+https://github.com/Backblaze/B2_Command_Line_Tool.git@ab2b5b4e3dc2c8b52b28592c7414ebb4646034e2#egg=b2\ncertifi==2021.5.30\ncharset-normalizer==2.0.12\nidna==3.10\nimportlib-metadata==4.8.3\nimportlib-resources==5.4.0\niniconfig==1.1.1\nmock==5.2.0\nnose==1.3.7\npackaging==21.3\npluggy==1.0.0\npy==1.11.0\npyflakes==3.0.1\npyparsing==3.1.4\npytest==7.0.1\nrequests==2.27.1\nsix==1.17.0\ntomli==1.2.3\ntqdm==4.64.1\ntyping_extensions==4.1.1\nurllib3==1.26.20\nyapf==0.32.0\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: B2_Command_Line_Tool\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - charset-normalizer==2.0.12\n - idna==3.10\n - importlib-metadata==4.8.3\n - importlib-resources==5.4.0\n - iniconfig==1.1.1\n - mock==5.2.0\n - nose==1.3.7\n - packaging==21.3\n - pluggy==1.0.0\n - py==1.11.0\n - pyflakes==3.0.1\n - pyparsing==3.1.4\n - pytest==7.0.1\n - requests==2.27.1\n - six==1.17.0\n - tomli==1.2.3\n - tqdm==4.64.1\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - yapf==0.32.0\n - zipp==3.6.0\nprefix: /opt/conda/envs/B2_Command_Line_Tool\n"},"FAIL_TO_PASS":{"kind":"list like","value":["test/test_sync.py::TestLocalFolder::test_broken_symlink","test/test_sync.py::TestLocalFolder::test_slash_sorting","test/test_sync.py::TestB2Folder::test_empty","test/test_sync.py::TestB2Folder::test_multiple_versions","test/test_sync.py::TestZipFolders::test_empty","test/test_sync.py::TestZipFolders::test_one_empty","test/test_sync.py::TestZipFolders::test_pass_reporter_to_folder","test/test_sync.py::TestZipFolders::test_two","test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_delete","test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_keep","test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_keep_days","test/test_sync.py::TestMakeSyncActions::test_compare_b2_none_newer","test/test_sync.py::TestMakeSyncActions::test_compare_b2_none_older","test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_equal","test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_not_equal","test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_not_equal_delete","test/test_sync.py::TestMakeSyncActions::test_delete_b2","test/test_sync.py::TestMakeSyncActions::test_delete_b2_multiple_versions","test/test_sync.py::TestMakeSyncActions::test_delete_hide_b2_multiple_versions","test/test_sync.py::TestMakeSyncActions::test_delete_local","test/test_sync.py::TestMakeSyncActions::test_empty_b2","test/test_sync.py::TestMakeSyncActions::test_empty_local","test/test_sync.py::TestMakeSyncActions::test_file_exclusions","test/test_sync.py::TestMakeSyncActions::test_file_exclusions_with_delete","test/test_sync.py::TestMakeSyncActions::test_keep_days_no_change_with_old_file","test/test_sync.py::TestMakeSyncActions::test_newer_b2","test/test_sync.py::TestMakeSyncActions::test_newer_b2_clean_old_versions","test/test_sync.py::TestMakeSyncActions::test_newer_b2_delete_old_versions","test/test_sync.py::TestMakeSyncActions::test_newer_local","test/test_sync.py::TestMakeSyncActions::test_no_delete_b2","test/test_sync.py::TestMakeSyncActions::test_no_delete_local","test/test_sync.py::TestMakeSyncActions::test_not_there_b2","test/test_sync.py::TestMakeSyncActions::test_not_there_local","test/test_sync.py::TestMakeSyncActions::test_older_b2","test/test_sync.py::TestMakeSyncActions::test_older_b2_replace","test/test_sync.py::TestMakeSyncActions::test_older_b2_replace_delete","test/test_sync.py::TestMakeSyncActions::test_older_b2_skip","test/test_sync.py::TestMakeSyncActions::test_older_local","test/test_sync.py::TestMakeSyncActions::test_older_local_replace","test/test_sync.py::TestMakeSyncActions::test_older_local_skip","test/test_sync.py::TestMakeSyncActions::test_same_b2","test/test_sync.py::TestMakeSyncActions::test_same_clean_old_versions","test/test_sync.py::TestMakeSyncActions::test_same_delete_old_versions","test/test_sync.py::TestMakeSyncActions::test_same_leave_old_versions","test/test_sync.py::TestMakeSyncActions::test_same_local"],"string":"[\n \"test/test_sync.py::TestLocalFolder::test_broken_symlink\",\n \"test/test_sync.py::TestLocalFolder::test_slash_sorting\",\n \"test/test_sync.py::TestB2Folder::test_empty\",\n \"test/test_sync.py::TestB2Folder::test_multiple_versions\",\n \"test/test_sync.py::TestZipFolders::test_empty\",\n \"test/test_sync.py::TestZipFolders::test_one_empty\",\n \"test/test_sync.py::TestZipFolders::test_pass_reporter_to_folder\",\n \"test/test_sync.py::TestZipFolders::test_two\",\n \"test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_delete\",\n \"test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_keep\",\n \"test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_keep_days\",\n \"test/test_sync.py::TestMakeSyncActions::test_compare_b2_none_newer\",\n \"test/test_sync.py::TestMakeSyncActions::test_compare_b2_none_older\",\n \"test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_equal\",\n \"test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_not_equal\",\n \"test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_not_equal_delete\",\n \"test/test_sync.py::TestMakeSyncActions::test_delete_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_delete_b2_multiple_versions\",\n \"test/test_sync.py::TestMakeSyncActions::test_delete_hide_b2_multiple_versions\",\n \"test/test_sync.py::TestMakeSyncActions::test_delete_local\",\n \"test/test_sync.py::TestMakeSyncActions::test_empty_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_empty_local\",\n \"test/test_sync.py::TestMakeSyncActions::test_file_exclusions\",\n \"test/test_sync.py::TestMakeSyncActions::test_file_exclusions_with_delete\",\n \"test/test_sync.py::TestMakeSyncActions::test_keep_days_no_change_with_old_file\",\n \"test/test_sync.py::TestMakeSyncActions::test_newer_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_newer_b2_clean_old_versions\",\n \"test/test_sync.py::TestMakeSyncActions::test_newer_b2_delete_old_versions\",\n \"test/test_sync.py::TestMakeSyncActions::test_newer_local\",\n \"test/test_sync.py::TestMakeSyncActions::test_no_delete_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_no_delete_local\",\n \"test/test_sync.py::TestMakeSyncActions::test_not_there_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_not_there_local\",\n \"test/test_sync.py::TestMakeSyncActions::test_older_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_older_b2_replace\",\n \"test/test_sync.py::TestMakeSyncActions::test_older_b2_replace_delete\",\n \"test/test_sync.py::TestMakeSyncActions::test_older_b2_skip\",\n \"test/test_sync.py::TestMakeSyncActions::test_older_local\",\n \"test/test_sync.py::TestMakeSyncActions::test_older_local_replace\",\n \"test/test_sync.py::TestMakeSyncActions::test_older_local_skip\",\n \"test/test_sync.py::TestMakeSyncActions::test_same_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_same_clean_old_versions\",\n \"test/test_sync.py::TestMakeSyncActions::test_same_delete_old_versions\",\n \"test/test_sync.py::TestMakeSyncActions::test_same_leave_old_versions\",\n \"test/test_sync.py::TestMakeSyncActions::test_same_local\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["test/test_sync.py::TestParseSyncFolder::test_b2_double_slash","test/test_sync.py::TestParseSyncFolder::test_b2_no_double_slash","test/test_sync.py::TestParseSyncFolder::test_b2_no_folder","test/test_sync.py::TestParseSyncFolder::test_b2_trailing_slash","test/test_sync.py::TestParseSyncFolder::test_local","test/test_sync.py::TestParseSyncFolder::test_local_trailing_slash","test/test_sync.py::TestMakeSyncActions::test_illegal_b2_to_b2","test/test_sync.py::TestMakeSyncActions::test_illegal_delete_and_keep_days","test/test_sync.py::TestMakeSyncActions::test_illegal_local_to_local","test/test_sync.py::TestMakeSyncActions::test_illegal_skip_and_replace","test_b2_command_line.py::TestCommandLine::test_stderr_patterns"],"string":"[\n \"test/test_sync.py::TestParseSyncFolder::test_b2_double_slash\",\n \"test/test_sync.py::TestParseSyncFolder::test_b2_no_double_slash\",\n \"test/test_sync.py::TestParseSyncFolder::test_b2_no_folder\",\n \"test/test_sync.py::TestParseSyncFolder::test_b2_trailing_slash\",\n \"test/test_sync.py::TestParseSyncFolder::test_local\",\n \"test/test_sync.py::TestParseSyncFolder::test_local_trailing_slash\",\n \"test/test_sync.py::TestMakeSyncActions::test_illegal_b2_to_b2\",\n \"test/test_sync.py::TestMakeSyncActions::test_illegal_delete_and_keep_days\",\n \"test/test_sync.py::TestMakeSyncActions::test_illegal_local_to_local\",\n \"test/test_sync.py::TestMakeSyncActions::test_illegal_skip_and_replace\",\n \"test_b2_command_line.py::TestCommandLine::test_stderr_patterns\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":585,"string":"585"}}},{"rowIdx":585,"cells":{"instance_id":{"kind":"string","value":"juju-solutions__charms.reactive-71"},"base_commit":{"kind":"string","value":"04663e45f3683d4c497f43526d3ac26593ee10a2"},"created_at":{"kind":"string","value":"2016-06-14 21:26:10"},"environment_setup_commit":{"kind":"string","value":"59b07bd9447d8a4cb027ea2515089216b8d20549"},"hints_text":{"kind":"string","value":"kwmonroe: There was some chatter on #juju about not using a string representation for toggle (instead using `object()`). I'm fine with this as-in, or with that changed.\nstub42: This needs a test, which I suspect is trivial."},"patch":{"kind":"string","value":"diff --git a/charms/reactive/relations.py b/charms/reactive/relations.py\nindex 173ef28..a8c1499 100644\n--- a/charms/reactive/relations.py\n+++ b/charms/reactive/relations.py\n@@ -30,7 +30,9 @@ from charms.reactive.bus import _load_module\n from charms.reactive.bus import StateList\n \n \n-ALL = '__ALL_SERVICES__'\n+# arbitrary obj instances to use as defaults instead of None\n+ALL = object()\n+TOGGLE = object()\n \n \n class scopes(object):\n@@ -296,13 +298,13 @@ class RelationBase(with_metaclass(AutoAccessors, object)):\n \"\"\"\n return self.conversation(scope).is_state(state)\n \n- def toggle_state(self, state, active=None, scope=None):\n+ def toggle_state(self, state, active=TOGGLE, scope=None):\n \"\"\"\n Toggle the state for the :class:`Conversation` with the given scope.\n \n In Python, this is equivalent to::\n \n- relation.conversation(scope).toggle_state(state)\n+ relation.conversation(scope).toggle_state(state, active)\n \n See :meth:`conversation` and :meth:`Conversation.toggle_state`.\n \"\"\"\n@@ -549,7 +551,7 @@ class Conversation(object):\n return False\n return self.key in value['conversations']\n \n- def toggle_state(self, state, active=None):\n+ def toggle_state(self, state, active=TOGGLE):\n \"\"\"\n Toggle the given state for this conversation.\n \n@@ -565,7 +567,7 @@ class Conversation(object):\n \n This will set the state if ``value`` is equal to ``foo``.\n \"\"\"\n- if active is None:\n+ if active is TOGGLE:\n active = not self.is_state(state)\n if active:\n self.set_state(state)\n"},"problem_statement":{"kind":"string","value":"toggle_state default for active is error-prone\n`toggle_state` takes an optional `active` param that lets you specify whether the state should be on or off, instead of it being switched from its previous value. Having a default value of `None` is problematic because `None` can easily be mistaken for a \"truthy\" `False` when dealing with relation data, which leads to the state being unexpectedly set. For example, the following breaks:\r\n\r\n```python\r\nconv.toggle_state('{relation_name}.feature_x',\r\n active=conv.get_remote('feature_x_available'))\r\n```\r\n\r\nThis can also be more subtle because `None and ` returns `None` instead of `False` as one might expect. For example, this also breaks:\r\n\r\n```python\r\nname = conv.get_remote('name')\r\nversion = conv.get_remote('version')\r\nconv.toggle_state('{relation_name}.ready', name and version)\r\n```\r\n"},"repo":{"kind":"string","value":"juju-solutions/charms.reactive"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_relations.py b/tests/test_relations.py\nindex c4977da..d49c3e1 100644\n--- a/tests/test_relations.py\n+++ b/tests/test_relations.py\n@@ -171,6 +171,11 @@ class TestRelationBase(unittest.TestCase):\n rb.conversation.assert_called_once_with('scope')\n conv.toggle_state.assert_called_once_with('state', 'active')\n \n+ conv.toggle_state.reset_mock()\n+ rb.toggle_state('state')\n+ conv.toggle_state.assert_called_once_with('state',\n+ relations.TOGGLE)\n+\n def test_set_remote(self):\n conv = mock.Mock(name='conv')\n rb = relations.RelationBase('relname', 'unit')\n@@ -391,12 +396,14 @@ class TestConversation(unittest.TestCase):\n \n conv.toggle_state('foo')\n self.assertEqual(conv.remove_state.call_count, 1)\n+ conv.toggle_state('foo', None)\n+ self.assertEqual(conv.remove_state.call_count, 2)\n conv.toggle_state('foo')\n self.assertEqual(conv.set_state.call_count, 1)\n conv.toggle_state('foo', True)\n self.assertEqual(conv.set_state.call_count, 2)\n conv.toggle_state('foo', False)\n- self.assertEqual(conv.remove_state.call_count, 2)\n+ self.assertEqual(conv.remove_state.call_count, 3)\n \n @mock.patch.object(relations.hookenv, 'relation_set')\n @mock.patch.object(relations.Conversation, 'relation_ids', ['rel:1', 'rel:2'])\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 0,\n \"test_score\": 3\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"0.4"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"coverage\",\n \"mock\",\n \"nose\",\n \"flake8\",\n \"ipython\",\n \"ipdb\",\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.6\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\nbackcall==0.2.0\ncertifi==2021.5.30\ncharmhelpers==1.2.1\n-e git+https://github.com/juju-solutions/charms.reactive.git@04663e45f3683d4c497f43526d3ac26593ee10a2#egg=charms.reactive\ncoverage==6.2\ndecorator==5.1.1\nflake8==5.0.4\nimportlib-metadata==4.2.0\nimportlib-resources==5.4.0\niniconfig==1.1.1\nipdb==0.13.13\nipython==7.16.3\nipython-genutils==0.2.0\njedi==0.17.2\nJinja2==3.0.3\nMarkupSafe==2.0.1\nmccabe==0.7.0\nmock==5.2.0\nnetaddr==0.10.1\nnose==1.3.7\npackaging==21.3\nparso==0.7.1\npbr==6.1.1\npexpect==4.9.0\npickleshare==0.7.5\npluggy==1.0.0\nprompt-toolkit==3.0.36\nptyprocess==0.7.0\npy==1.11.0\npyaml==23.5.8\npycodestyle==2.9.1\npyflakes==2.5.0\nPygments==2.14.0\npyparsing==3.1.4\npytest==7.0.1\nPyYAML==6.0.1\nsix==1.17.0\ntomli==1.2.3\ntraitlets==4.3.3\ntyping_extensions==4.1.1\nwcwidth==0.2.13\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: charms.reactive\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - backcall==0.2.0\n - charmhelpers==1.2.1\n - coverage==6.2\n - decorator==5.1.1\n - flake8==5.0.4\n - importlib-metadata==4.2.0\n - importlib-resources==5.4.0\n - iniconfig==1.1.1\n - ipdb==0.13.13\n - ipython==7.16.3\n - ipython-genutils==0.2.0\n - jedi==0.17.2\n - jinja2==3.0.3\n - markupsafe==2.0.1\n - mccabe==0.7.0\n - mock==5.2.0\n - netaddr==0.10.1\n - nose==1.3.7\n - packaging==21.3\n - parso==0.7.1\n - pbr==6.1.1\n - pexpect==4.9.0\n - pickleshare==0.7.5\n - pluggy==1.0.0\n - prompt-toolkit==3.0.36\n - ptyprocess==0.7.0\n - py==1.11.0\n - pyaml==23.5.8\n - pycodestyle==2.9.1\n - pyflakes==2.5.0\n - pygments==2.14.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - pyyaml==6.0.1\n - six==1.17.0\n - tomli==1.2.3\n - traitlets==4.3.3\n - typing-extensions==4.1.1\n - wcwidth==0.2.13\n - zipp==3.6.0\nprefix: /opt/conda/envs/charms.reactive\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_relations.py::TestRelationBase::test_toggle_state","tests/test_relations.py::TestConversation::test_toggle_state"],"string":"[\n \"tests/test_relations.py::TestRelationBase::test_toggle_state\",\n \"tests/test_relations.py::TestConversation::test_toggle_state\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_relations.py::TestAutoAccessors::test_accessor","tests/test_relations.py::TestAutoAccessors::test_accessor_doc","tests/test_relations.py::TestRelationBase::test_conversation","tests/test_relations.py::TestRelationBase::test_find_impl","tests/test_relations.py::TestRelationBase::test_find_subclass","tests/test_relations.py::TestRelationBase::test_from_name","tests/test_relations.py::TestRelationBase::test_from_state","tests/test_relations.py::TestRelationBase::test_get_local","tests/test_relations.py::TestRelationBase::test_get_remote","tests/test_relations.py::TestRelationBase::test_is_state","tests/test_relations.py::TestRelationBase::test_remove_state","tests/test_relations.py::TestRelationBase::test_set_local","tests/test_relations.py::TestRelationBase::test_set_remote","tests/test_relations.py::TestRelationBase::test_set_state","tests/test_relations.py::TestConversation::test_depart","tests/test_relations.py::TestConversation::test_get_local","tests/test_relations.py::TestConversation::test_get_remote","tests/test_relations.py::TestConversation::test_is_state","tests/test_relations.py::TestConversation::test_join","tests/test_relations.py::TestConversation::test_key","tests/test_relations.py::TestConversation::test_load","tests/test_relations.py::TestConversation::test_relation_ids","tests/test_relations.py::TestConversation::test_remove_state","tests/test_relations.py::TestConversation::test_set_local","tests/test_relations.py::TestConversation::test_set_remote","tests/test_relations.py::TestConversation::test_set_state","tests/test_relations.py::TestMigrateConvs::test_migrate","tests/test_relations.py::TestRelationCall::test_call_conversations","tests/test_relations.py::TestRelationCall::test_call_name","tests/test_relations.py::TestRelationCall::test_call_state","tests/test_relations.py::TestRelationCall::test_no_impl"],"string":"[\n \"tests/test_relations.py::TestAutoAccessors::test_accessor\",\n \"tests/test_relations.py::TestAutoAccessors::test_accessor_doc\",\n \"tests/test_relations.py::TestRelationBase::test_conversation\",\n \"tests/test_relations.py::TestRelationBase::test_find_impl\",\n \"tests/test_relations.py::TestRelationBase::test_find_subclass\",\n \"tests/test_relations.py::TestRelationBase::test_from_name\",\n \"tests/test_relations.py::TestRelationBase::test_from_state\",\n \"tests/test_relations.py::TestRelationBase::test_get_local\",\n \"tests/test_relations.py::TestRelationBase::test_get_remote\",\n \"tests/test_relations.py::TestRelationBase::test_is_state\",\n \"tests/test_relations.py::TestRelationBase::test_remove_state\",\n \"tests/test_relations.py::TestRelationBase::test_set_local\",\n \"tests/test_relations.py::TestRelationBase::test_set_remote\",\n \"tests/test_relations.py::TestRelationBase::test_set_state\",\n \"tests/test_relations.py::TestConversation::test_depart\",\n \"tests/test_relations.py::TestConversation::test_get_local\",\n \"tests/test_relations.py::TestConversation::test_get_remote\",\n \"tests/test_relations.py::TestConversation::test_is_state\",\n \"tests/test_relations.py::TestConversation::test_join\",\n \"tests/test_relations.py::TestConversation::test_key\",\n \"tests/test_relations.py::TestConversation::test_load\",\n \"tests/test_relations.py::TestConversation::test_relation_ids\",\n \"tests/test_relations.py::TestConversation::test_remove_state\",\n \"tests/test_relations.py::TestConversation::test_set_local\",\n \"tests/test_relations.py::TestConversation::test_set_remote\",\n \"tests/test_relations.py::TestConversation::test_set_state\",\n \"tests/test_relations.py::TestMigrateConvs::test_migrate\",\n \"tests/test_relations.py::TestRelationCall::test_call_conversations\",\n \"tests/test_relations.py::TestRelationCall::test_call_name\",\n \"tests/test_relations.py::TestRelationCall::test_call_state\",\n \"tests/test_relations.py::TestRelationCall::test_no_impl\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":586,"string":"586"}}},{"rowIdx":586,"cells":{"instance_id":{"kind":"string","value":"juju-solutions__charms.reactive-73"},"base_commit":{"kind":"string","value":"04663e45f3683d4c497f43526d3ac26593ee10a2"},"created_at":{"kind":"string","value":"2016-06-15 01:33:48"},"environment_setup_commit":{"kind":"string","value":"59b07bd9447d8a4cb027ea2515089216b8d20549"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/charms/reactive/bus.py b/charms/reactive/bus.py\nindex 885e498..853571a 100644\n--- a/charms/reactive/bus.py\n+++ b/charms/reactive/bus.py\n@@ -229,6 +229,7 @@ class Handler(object):\n self._action = action\n self._args = []\n self._predicates = []\n+ self._post_callbacks = []\n self._states = set()\n \n def id(self):\n@@ -255,6 +256,12 @@ class Handler(object):\n hookenv.log(' Adding predicate for %s: %s' % (self.id(), _predicate), level=hookenv.DEBUG)\n self._predicates.append(predicate)\n \n+ def add_post_callback(self, callback):\n+ \"\"\"\n+ Add a callback to be run after the action is invoked.\n+ \"\"\"\n+ self._post_callbacks.append(callback)\n+\n def test(self):\n \"\"\"\n Check the predicate(s) and return True if this handler should be invoked.\n@@ -278,6 +285,8 @@ class Handler(object):\n \"\"\"\n args = self._get_args()\n self._action(*args)\n+ for callback in self._post_callbacks:\n+ callback()\n \n def register_states(self, states):\n \"\"\"\ndiff --git a/charms/reactive/decorators.py b/charms/reactive/decorators.py\nindex 7918106..e89332f 100644\n--- a/charms/reactive/decorators.py\n+++ b/charms/reactive/decorators.py\n@@ -205,18 +205,18 @@ def not_unless(*desired_states):\n return _decorator\n \n \n-def only_once(action):\n+def only_once(action=None):\n \"\"\"\n- Ensure that the decorated function is only executed the first time it is called.\n+ Register the decorated function to be run once, and only once.\n \n- This can be used on reactive handlers to ensure that they are only triggered\n- once, even if their conditions continue to match on subsequent calls, even\n- across hook invocations.\n+ This decorator will never cause arguments to be passed to the handler.\n \"\"\"\n- @wraps(action)\n- def wrapper(*args, **kwargs):\n- action_id = _action_id(action)\n- if not was_invoked(action_id):\n- action(*args, **kwargs)\n- mark_invoked(action_id)\n- return wrapper\n+ if action is None:\n+ # allow to be used as @only_once or @only_once()\n+ return only_once\n+\n+ action_id = _action_id(action)\n+ handler = Handler.get(action)\n+ handler.add_predicate(lambda: not was_invoked(action_id))\n+ handler.add_post_callback(partial(mark_invoked, action_id))\n+ return action\n"},"problem_statement":{"kind":"string","value":"only_once help unclear\n_From @jacekn on January 27, 2016 17:29_\n\nI was trying to execute certain function only once in my code.\r\n\r\nThis does not work:\r\n```\r\n@only_once()\r\ndef basenode():\r\n print(\"in basenode\")\r\n```\r\n```\r\nTypeError: only_once() missing 1 required positional argument: 'action'\r\n```\r\n\r\nI tried like this but it also did not work:\r\n```\r\n@only_once(\"basenode\")\r\ndef basenode():\r\n print(\"in basenode\")\r\n```\r\n```\r\nAttributeError: 'str' object has no attribute '__code__'\r\n```\r\nCan documentation be clarified to show correct use of this decorator?\n\n_Copied from original issue: juju/charm-tools#94_"},"repo":{"kind":"string","value":"juju-solutions/charms.reactive"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_decorators.py b/tests/test_decorators.py\nindex 4691a30..2599b53 100644\n--- a/tests/test_decorators.py\n+++ b/tests/test_decorators.py\n@@ -241,11 +241,28 @@ class TestReactiveDecorators(unittest.TestCase):\n calls = []\n \n @reactive.decorators.only_once\n- def test(num):\n- calls.append(num)\n+ def test():\n+ calls.append(len(calls)+1)\n+\n+ handler = reactive.bus.Handler.get(test)\n \n- test(1)\n- test(2)\n+ assert handler.test()\n+ handler.invoke()\n+ assert not handler.test()\n+ self.assertEquals(calls, [1])\n+\n+ def test_only_once_parens(self):\n+ calls = []\n+\n+ @reactive.decorators.only_once()\n+ def test():\n+ calls.append(len(calls)+1)\n+\n+ handler = reactive.bus.Handler.get(test)\n+\n+ assert handler.test()\n+ handler.invoke()\n+ assert not handler.test()\n self.assertEquals(calls, [1])\n \n def test_multi(self):\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 2,\n \"test_score\": 3\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"0.4"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"coverage\",\n \"mock\",\n \"nose\",\n \"flake8\",\n \"ipython\",\n \"ipdb\",\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.6\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\nbackcall==0.2.0\ncertifi==2021.5.30\ncharmhelpers==1.2.1\n-e git+https://github.com/juju-solutions/charms.reactive.git@04663e45f3683d4c497f43526d3ac26593ee10a2#egg=charms.reactive\ncoverage==6.2\ndecorator==5.1.1\nflake8==5.0.4\nimportlib-metadata==4.2.0\nimportlib-resources==5.4.0\niniconfig==1.1.1\nipdb==0.13.13\nipython==7.16.3\nipython-genutils==0.2.0\njedi==0.17.2\nJinja2==3.0.3\nMarkupSafe==2.0.1\nmccabe==0.7.0\nmock==5.2.0\nnetaddr==0.10.1\nnose==1.3.7\npackaging==21.3\nparso==0.7.1\npbr==6.1.1\npexpect==4.9.0\npickleshare==0.7.5\npluggy==1.0.0\nprompt-toolkit==3.0.36\nptyprocess==0.7.0\npy==1.11.0\npyaml==23.5.8\npycodestyle==2.9.1\npyflakes==2.5.0\nPygments==2.14.0\npyparsing==3.1.4\npytest==7.0.1\nPyYAML==6.0.1\nsix==1.17.0\ntomli==1.2.3\ntraitlets==4.3.3\ntyping_extensions==4.1.1\nwcwidth==0.2.13\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: charms.reactive\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - backcall==0.2.0\n - charmhelpers==1.2.1\n - coverage==6.2\n - decorator==5.1.1\n - flake8==5.0.4\n - importlib-metadata==4.2.0\n - importlib-resources==5.4.0\n - iniconfig==1.1.1\n - ipdb==0.13.13\n - ipython==7.16.3\n - ipython-genutils==0.2.0\n - jedi==0.17.2\n - jinja2==3.0.3\n - markupsafe==2.0.1\n - mccabe==0.7.0\n - mock==5.2.0\n - netaddr==0.10.1\n - nose==1.3.7\n - packaging==21.3\n - parso==0.7.1\n - pbr==6.1.1\n - pexpect==4.9.0\n - pickleshare==0.7.5\n - pluggy==1.0.0\n - prompt-toolkit==3.0.36\n - ptyprocess==0.7.0\n - py==1.11.0\n - pyaml==23.5.8\n - pycodestyle==2.9.1\n - pyflakes==2.5.0\n - pygments==2.14.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - pyyaml==6.0.1\n - six==1.17.0\n - tomli==1.2.3\n - traitlets==4.3.3\n - typing-extensions==4.1.1\n - wcwidth==0.2.13\n - zipp==3.6.0\nprefix: /opt/conda/envs/charms.reactive\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_decorators.py::TestReactiveDecorators::test_only_once","tests/test_decorators.py::TestReactiveDecorators::test_only_once_parens"],"string":"[\n \"tests/test_decorators.py::TestReactiveDecorators::test_only_once\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_only_once_parens\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_decorators.py::TestReactiveDecorators::test_hook","tests/test_decorators.py::TestReactiveDecorators::test_multi","tests/test_decorators.py::TestReactiveDecorators::test_not_unless","tests/test_decorators.py::TestReactiveDecorators::test_when","tests/test_decorators.py::TestReactiveDecorators::test_when_all","tests/test_decorators.py::TestReactiveDecorators::test_when_any","tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed","tests/test_decorators.py::TestReactiveDecorators::test_when_none","tests/test_decorators.py::TestReactiveDecorators::test_when_not","tests/test_decorators.py::TestReactiveDecorators::test_when_not_all"],"string":"[\n \"tests/test_decorators.py::TestReactiveDecorators::test_hook\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_multi\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_not_unless\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_all\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_any\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_none\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_not\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_not_all\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":587,"string":"587"}}},{"rowIdx":587,"cells":{"instance_id":{"kind":"string","value":"juju-solutions__charms.reactive-74"},"base_commit":{"kind":"string","value":"04663e45f3683d4c497f43526d3ac26593ee10a2"},"created_at":{"kind":"string","value":"2016-06-15 02:46:03"},"environment_setup_commit":{"kind":"string","value":"59b07bd9447d8a4cb027ea2515089216b8d20549"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/charms/reactive/bus.py b/charms/reactive/bus.py\nindex 885e498..1bd1364 100644\n--- a/charms/reactive/bus.py\n+++ b/charms/reactive/bus.py\n@@ -170,12 +170,16 @@ def get_state(state, default=None):\n \n \n def _action_id(action):\n+ if hasattr(action, '_action_id'):\n+ return action._action_id\n return \"%s:%s:%s\" % (action.__code__.co_filename,\n action.__code__.co_firstlineno,\n action.__code__.co_name)\n \n \n def _short_action_id(action):\n+ if hasattr(action, '_short_action_id'):\n+ return action._short_action_id\n filepath = os.path.relpath(action.__code__.co_filename, hookenv.charm_dir())\n return \"%s:%s:%s\" % (filepath,\n action.__code__.co_firstlineno,\ndiff --git a/charms/reactive/decorators.py b/charms/reactive/decorators.py\nindex 7918106..7de571c 100644\n--- a/charms/reactive/decorators.py\n+++ b/charms/reactive/decorators.py\n@@ -21,6 +21,7 @@ from charmhelpers.core import hookenv\n from charms.reactive.bus import Handler\n from charms.reactive.bus import get_states\n from charms.reactive.bus import _action_id\n+from charms.reactive.bus import _short_action_id\n from charms.reactive.relations import RelationBase\n from charms.reactive.helpers import _hook\n from charms.reactive.helpers import _when_all\n@@ -188,19 +189,21 @@ def not_unless(*desired_states):\n This is primarily for informational purposes and as a guard clause.\n \"\"\"\n def _decorator(func):\n+ action_id = _action_id(func)\n+ short_action_id = _short_action_id(func)\n+\n @wraps(func)\n def _wrapped(*args, **kwargs):\n active_states = get_states()\n missing_states = [state for state in desired_states if state not in active_states]\n if missing_states:\n- func_id = \"%s:%s:%s\" % (func.__code__.co_filename,\n- func.__code__.co_firstlineno,\n- func.__code__.co_name)\n hookenv.log('%s called before state%s: %s' % (\n- func_id,\n+ short_action_id,\n 's' if len(missing_states) > 1 else '',\n ', '.join(missing_states)), hookenv.WARNING)\n return func(*args, **kwargs)\n+ _wrapped._action_id = action_id\n+ _wrapped._short_action_id = short_action_id\n return _wrapped\n return _decorator\n \n"},"problem_statement":{"kind":"string","value":"Incorrect handler name logged using not_unless decorator\nI'm getting the following in my logs:\r\n\r\n2016-01-11 14:58:37 INFO juju-log replication:1: Invoking reactive handler: lib/pypi/charms/reactive/decorators.py:149:_wrapped\r\n\r\nIt looks like a name isn't being copied from the wrapped function in the not_unless decorator"},"repo":{"kind":"string","value":"juju-solutions/charms.reactive"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_decorators.py b/tests/test_decorators.py\nindex 4691a30..78733c7 100644\n--- a/tests/test_decorators.py\n+++ b/tests/test_decorators.py\n@@ -236,6 +236,10 @@ class TestReactiveDecorators(unittest.TestCase):\n self.assertEqual(action.call_count, 3)\n assert log_msg(0).endswith('test called before states: foo, bar'), log_msg(0)\n assert log_msg(1).endswith('test called before state: bar'), log_msg(1)\n+ self.assertIn('tests/test_decorators.py:', reactive.bus._action_id(test))\n+ self.assertIn(':test', reactive.bus._action_id(test))\n+ self.assertIn('tests/test_decorators.py:', reactive.bus._short_action_id(test))\n+ self.assertIn(':test', reactive.bus._short_action_id(test))\n \n def test_only_once(self):\n calls = []\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_many_modified_files\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 2,\n \"test_score\": 2\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"0.4"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"coverage\",\n \"mock\",\n \"nose\",\n \"flake8\",\n \"ipython\",\n \"ipdb\",\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.6\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\nbackcall==0.2.0\ncertifi==2021.5.30\ncharmhelpers==1.2.1\n-e git+https://github.com/juju-solutions/charms.reactive.git@04663e45f3683d4c497f43526d3ac26593ee10a2#egg=charms.reactive\ncoverage==6.2\ndecorator==5.1.1\nflake8==5.0.4\nimportlib-metadata==4.2.0\nimportlib-resources==5.4.0\niniconfig==1.1.1\nipdb==0.13.13\nipython==7.16.3\nipython-genutils==0.2.0\njedi==0.17.2\nJinja2==3.0.3\nMarkupSafe==2.0.1\nmccabe==0.7.0\nmock==5.2.0\nnetaddr==0.10.1\nnose==1.3.7\npackaging==21.3\nparso==0.7.1\npbr==6.1.1\npexpect==4.9.0\npickleshare==0.7.5\npluggy==1.0.0\nprompt-toolkit==3.0.36\nptyprocess==0.7.0\npy==1.11.0\npyaml==23.5.8\npycodestyle==2.9.1\npyflakes==2.5.0\nPygments==2.14.0\npyparsing==3.1.4\npytest==7.0.1\nPyYAML==6.0.1\nsix==1.17.0\ntomli==1.2.3\ntraitlets==4.3.3\ntyping_extensions==4.1.1\nwcwidth==0.2.13\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: charms.reactive\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - backcall==0.2.0\n - charmhelpers==1.2.1\n - coverage==6.2\n - decorator==5.1.1\n - flake8==5.0.4\n - importlib-metadata==4.2.0\n - importlib-resources==5.4.0\n - iniconfig==1.1.1\n - ipdb==0.13.13\n - ipython==7.16.3\n - ipython-genutils==0.2.0\n - jedi==0.17.2\n - jinja2==3.0.3\n - markupsafe==2.0.1\n - mccabe==0.7.0\n - mock==5.2.0\n - netaddr==0.10.1\n - nose==1.3.7\n - packaging==21.3\n - parso==0.7.1\n - pbr==6.1.1\n - pexpect==4.9.0\n - pickleshare==0.7.5\n - pluggy==1.0.0\n - prompt-toolkit==3.0.36\n - ptyprocess==0.7.0\n - py==1.11.0\n - pyaml==23.5.8\n - pycodestyle==2.9.1\n - pyflakes==2.5.0\n - pygments==2.14.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - pyyaml==6.0.1\n - six==1.17.0\n - tomli==1.2.3\n - traitlets==4.3.3\n - typing-extensions==4.1.1\n - wcwidth==0.2.13\n - zipp==3.6.0\nprefix: /opt/conda/envs/charms.reactive\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_decorators.py::TestReactiveDecorators::test_not_unless"],"string":"[\n \"tests/test_decorators.py::TestReactiveDecorators::test_not_unless\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_decorators.py::TestReactiveDecorators::test_hook","tests/test_decorators.py::TestReactiveDecorators::test_multi","tests/test_decorators.py::TestReactiveDecorators::test_only_once","tests/test_decorators.py::TestReactiveDecorators::test_when","tests/test_decorators.py::TestReactiveDecorators::test_when_all","tests/test_decorators.py::TestReactiveDecorators::test_when_any","tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed","tests/test_decorators.py::TestReactiveDecorators::test_when_none","tests/test_decorators.py::TestReactiveDecorators::test_when_not","tests/test_decorators.py::TestReactiveDecorators::test_when_not_all"],"string":"[\n \"tests/test_decorators.py::TestReactiveDecorators::test_hook\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_multi\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_only_once\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_all\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_any\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_none\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_not\",\n \"tests/test_decorators.py::TestReactiveDecorators::test_when_not_all\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":588,"string":"588"}}},{"rowIdx":588,"cells":{"instance_id":{"kind":"string","value":"cdent__gabbi-157"},"base_commit":{"kind":"string","value":"1b9a0be830dac86865bee85c33886d3b2fb4d37b"},"created_at":{"kind":"string","value":"2016-06-16 12:05:42"},"environment_setup_commit":{"kind":"string","value":"1b9a0be830dac86865bee85c33886d3b2fb4d37b"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/gabbi/driver.py b/gabbi/driver.py\nindex 9cb88fe..22a48c4 100644\n--- a/gabbi/driver.py\n+++ b/gabbi/driver.py\n@@ -29,8 +29,10 @@ import os\n import unittest\n from unittest import suite\n import uuid\n+import warnings\n \n from gabbi import case\n+from gabbi import exception\n from gabbi import handlers\n from gabbi import reporter\n from gabbi import suitemaker\n@@ -83,6 +85,10 @@ def build_tests(path, loader, host=None, port=8001, intercept=None,\n \n top_suite = suite.TestSuite()\n for test_file in glob.iglob('%s/*.yaml' % path):\n+ if '_' in os.path.basename(test_file):\n+ warnings.warn(exception.GabbiSyntaxWarning(\n+ \"'_' in test filename %s. This can break suite grouping.\"\n+ % test_file))\n if intercept:\n host = str(uuid.uuid4())\n suite_dict = utils.load_yaml(yaml_file=test_file)\n@@ -134,7 +140,6 @@ def py_test_generator(test_dir, host=None, port=8001, intercept=None,\n def test_suite_from_yaml(loader, test_base_name, test_yaml, test_directory,\n host, port, fixture_module, intercept, prefix=''):\n \"\"\"Legacy wrapper retained for backwards compatibility.\"\"\"\n- import warnings\n \n with warnings.catch_warnings(): # ensures warnings filter is restored\n warnings.simplefilter('default', DeprecationWarning)\ndiff --git a/gabbi/exception.py b/gabbi/exception.py\nindex 3d4ef45..2bc93e4 100644\n--- a/gabbi/exception.py\n+++ b/gabbi/exception.py\n@@ -16,3 +16,8 @@\n class GabbiFormatError(ValueError):\n \"\"\"An exception to encapsulate poorly formed test data.\"\"\"\n pass\n+\n+\n+class GabbiSyntaxWarning(SyntaxWarning):\n+ \"\"\"A warning about syntax that is not desirable.\"\"\"\n+ pass\n"},"problem_statement":{"kind":"string","value":"Q: What characters are legal / recommended for test name in YAML?\nI suspect plain alphanum + spaces is recommended, but I might sometimes want to do hyphen or parens. So, just being thorough.\r\n\r\nThanks!\r\n"},"repo":{"kind":"string","value":"cdent/gabbi"},"test_patch":{"kind":"string","value":"diff --git a/gabbi/tests/gabbits_intercept/json_extensions.yaml b/gabbi/tests/gabbits_intercept/json-extensions.yaml\nsimilarity index 100%\nrename from gabbi/tests/gabbits_intercept/json_extensions.yaml\nrename to gabbi/tests/gabbits_intercept/json-extensions.yaml\ndiff --git a/gabbi/tests/gabbits_intercept/last_url.yaml b/gabbi/tests/gabbits_intercept/last-url.yaml\nsimilarity index 100%\nrename from gabbi/tests/gabbits_intercept/last_url.yaml\nrename to gabbi/tests/gabbits_intercept/last-url.yaml\ndiff --git a/gabbi/tests/gabbits_intercept/method_shortcut.yaml b/gabbi/tests/gabbits_intercept/method-shortcut.yaml\nsimilarity index 100%\nrename from gabbi/tests/gabbits_intercept/method_shortcut.yaml\nrename to gabbi/tests/gabbits_intercept/method-shortcut.yaml\ndiff --git a/gabbi/tests/test_syntax_warning.py b/gabbi/tests/test_syntax_warning.py\nnew file mode 100644\nindex 0000000..529dbf6\n--- /dev/null\n+++ b/gabbi/tests/test_syntax_warning.py\n@@ -0,0 +1,41 @@\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n+# not use this file except in compliance with the License. You may obtain\n+# a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n+# License for the specific language governing permissions and limitations\n+# under the License.\n+\"\"\"Test that the driver warns on bad yaml name.\"\"\"\n+\n+import os\n+import unittest\n+import warnings\n+\n+from gabbi import driver\n+from gabbi import exception\n+\n+\n+TESTS_DIR = 'warning_gabbits'\n+\n+\n+class DriverTest(unittest.TestCase):\n+\n+ def setUp(self):\n+ super(DriverTest, self).setUp()\n+ self.loader = unittest.defaultTestLoader\n+ self.test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)\n+\n+ def test_driver_warngs_on_files(self):\n+ with warnings.catch_warnings(record=True) as the_warnings:\n+ driver.build_tests(\n+ self.test_dir, self.loader, host='localhost', port=8001)\n+ self.assertEqual(1, len(the_warnings))\n+ the_warning = the_warnings[-1]\n+ self.assertEqual(\n+ the_warning.category, exception.GabbiSyntaxWarning)\n+ self.assertIn(\"'_' in test filename\", str(the_warning.message))\ndiff --git a/gabbi/tests/warning_gabbits/underscore_sample.yaml b/gabbi/tests/warning_gabbits/underscore_sample.yaml\nnew file mode 100644\nindex 0000000..185e378\n--- /dev/null\n+++ b/gabbi/tests/warning_gabbits/underscore_sample.yaml\n@@ -0,0 +1,6 @@\n+\n+tests:\n+ - name: one\n+ url: /\n+ - name: two\n+ url: http://example.com/moo\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 3,\n \"test_score\": 2\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"1.22"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"mock\",\n \"testrepository\",\n \"coverage\",\n \"hacking\",\n \"sphinx\",\n \"pytest\"\n ],\n \"pre_install\": null,\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"alabaster==0.7.13\nattrs==22.2.0\nBabel==2.11.0\ncertifi==2021.5.30\ncharset-normalizer==2.0.12\ncolorama==0.4.5\ncoverage==6.2\ndecorator==5.1.1\ndocutils==0.18.1\nextras==1.0.0\nfixtures==4.0.1\nflake8==3.8.4\n-e git+https://github.com/cdent/gabbi.git@1b9a0be830dac86865bee85c33886d3b2fb4d37b#egg=gabbi\nhacking==4.1.0\nidna==3.10\nimagesize==1.4.1\nimportlib-metadata==4.8.3\niniconfig==1.1.1\niso8601==1.1.0\nJinja2==3.0.3\njsonpath-rw==1.4.0\njsonpath-rw-ext==1.2.2\nMarkupSafe==2.0.1\nmccabe==0.6.1\nmock==5.2.0\npackaging==21.3\npbr==6.1.1\npluggy==1.0.0\nply==3.11\npy==1.11.0\npycodestyle==2.6.0\npyflakes==2.2.0\nPygments==2.14.0\npyparsing==3.1.4\npytest==7.0.1\npython-subunit==1.4.2\npytz==2025.2\nPyYAML==6.0.1\nrequests==2.27.1\nsix==1.17.0\nsnowballstemmer==2.2.0\nSphinx==5.3.0\nsphinxcontrib-applehelp==1.0.2\nsphinxcontrib-devhelp==1.0.2\nsphinxcontrib-htmlhelp==2.0.0\nsphinxcontrib-jsmath==1.0.1\nsphinxcontrib-qthelp==1.0.3\nsphinxcontrib-serializinghtml==1.1.5\ntestrepository==0.0.21\ntesttools==2.6.0\ntomli==1.2.3\ntyping_extensions==4.1.1\nurllib3==1.26.20\nwsgi_intercept==1.13.1\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: gabbi\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - alabaster==0.7.13\n - attrs==22.2.0\n - babel==2.11.0\n - charset-normalizer==2.0.12\n - colorama==0.4.5\n - coverage==6.2\n - decorator==5.1.1\n - docutils==0.18.1\n - extras==1.0.0\n - fixtures==4.0.1\n - flake8==3.8.4\n - hacking==4.1.0\n - idna==3.10\n - imagesize==1.4.1\n - importlib-metadata==4.8.3\n - iniconfig==1.1.1\n - iso8601==1.1.0\n - jinja2==3.0.3\n - jsonpath-rw==1.4.0\n - jsonpath-rw-ext==1.2.2\n - markupsafe==2.0.1\n - mccabe==0.6.1\n - mock==5.2.0\n - packaging==21.3\n - pbr==6.1.1\n - pluggy==1.0.0\n - ply==3.11\n - py==1.11.0\n - pycodestyle==2.6.0\n - pyflakes==2.2.0\n - pygments==2.14.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - python-subunit==1.4.2\n - pytz==2025.2\n - pyyaml==6.0.1\n - requests==2.27.1\n - six==1.17.0\n - snowballstemmer==2.2.0\n - sphinx==5.3.0\n - sphinxcontrib-applehelp==1.0.2\n - sphinxcontrib-devhelp==1.0.2\n - sphinxcontrib-htmlhelp==2.0.0\n - sphinxcontrib-jsmath==1.0.1\n - sphinxcontrib-qthelp==1.0.3\n - sphinxcontrib-serializinghtml==1.1.5\n - testrepository==0.0.21\n - testtools==2.6.0\n - tomli==1.2.3\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - wsgi-intercept==1.13.1\n - zipp==3.6.0\nprefix: /opt/conda/envs/gabbi\n"},"FAIL_TO_PASS":{"kind":"list like","value":["gabbi/tests/test_syntax_warning.py::DriverTest::test_driver_warngs_on_files"],"string":"[\n \"gabbi/tests/test_syntax_warning.py::DriverTest::test_driver_warngs_on_files\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":589,"string":"589"}}},{"rowIdx":589,"cells":{"instance_id":{"kind":"string","value":"box__box-python-sdk-139"},"base_commit":{"kind":"string","value":"a1dba2d7699f6d3e798e89821d4650720e299ffd"},"created_at":{"kind":"string","value":"2016-06-16 15:45:59"},"environment_setup_commit":{"kind":"string","value":"ded623f4b6de0530d8f983d3c3d2cafe646c126b"},"hints_text":{"kind":"string","value":"boxcla: Hi @kelseymorris95, thanks for the pull request. Before we can merge it, we need you to sign our Contributor License Agreement. You can do so electronically here: http://opensource.box.com/cla\n\nOnce you have signed, just add a comment to this pull request saying, \"CLA signed\". Thanks!\nkelseymorris95: CLA signed\nboxcla: Verified that @kelseymorris95 has just signed the CLA. Thanks, and we look forward to your contribution.\njmoldow: Something to think about: `Translator.translate()` takes a type, and tries to translate it. If it fails, it'll return `BaseObject`. Then, the usual procedure is to pass `session, object_id, response_object` to the class that is returned.\r\n\r\nThis has two problems:\r\n- Ideally, the default return value would be either `BaseObject` or `APIJSONObject`, depending on the object. I would choose `BaseObject` if there were an `id`, and `APIJSONObject` otherwise. However, we can't do that since the method only accepts type. We'd need to make a backwards-incompatible change to make it accept additional information.\r\n- The types of classes we return have different `__init__` parameters. So you can't initialize an object unless you know in advance which type it's going to be. We could fix this by:\r\n - Moving the object creation inside of `Translator.translate()` (after dealing with the above problem).\r\n - Making `APIJSONObject.__init__` have the same argument list as `BaseObject.__init__`, even though it doesn't need most of them.\r\n\r\nLet's not worry about this right now. What we have now works well enough to push what you have as-is. But we'll want to revisit this before or during work on #140.\nHootyMcOwlface: :+1:\r\n\njmoldow: 👍 \r\n\r\nThanks @kelseymorris95 ! This all looks great. I'm going to merge it now.\r\n\r\nBefore releasing this to PyPI, over the next few days, let's make sure we're happy with the names of the new classes, make a final decision about `Mapping` vs `MutableMapping` vs `dict`, and double-check that we aren't introducing any other backwards incompatibilities."},"patch":{"kind":"string","value":"diff --git a/boxsdk/object/__init__.py b/boxsdk/object/__init__.py\nindex ffd3611..e4fdb61 100644\n--- a/boxsdk/object/__init__.py\n+++ b/boxsdk/object/__init__.py\n@@ -5,4 +5,4 @@\n from six.moves import map # pylint:disable=redefined-builtin\n \n \n-__all__ = list(map(str, ['collaboration', 'events', 'file', 'folder', 'group', 'group_membership', 'search', 'user']))\n+__all__ = list(map(str, ['collaboration', 'events', 'event', 'file', 'folder', 'group', 'group_membership', 'search', 'user']))\ndiff --git a/boxsdk/object/api_json_object.py b/boxsdk/object/api_json_object.py\nnew file mode 100644\nindex 0000000..e407b1c\n--- /dev/null\n+++ b/boxsdk/object/api_json_object.py\n@@ -0,0 +1,26 @@\n+# coding: utf-8\n+\n+from __future__ import unicode_literals, absolute_import\n+from collections import Mapping\n+from abc import ABCMeta\n+import six\n+\n+from .base_api_json_object import BaseAPIJSONObject, BaseAPIJSONObjectMeta\n+\n+\n+class APIJSONObjectMeta(BaseAPIJSONObjectMeta, ABCMeta):\n+ \"\"\"\n+ Avoid conflicting metaclass definitions for APIJSONObject.\n+ http://code.activestate.com/recipes/204197-solving-the-metaclass-conflict/\n+ \"\"\"\n+ pass\n+\n+\n+class APIJSONObject(six.with_metaclass(APIJSONObjectMeta, BaseAPIJSONObject, Mapping)):\n+ \"\"\"Class representing objects that are not part of the REST API.\"\"\"\n+\n+ def __len__(self):\n+ return len(self._response_object)\n+\n+ def __iter__(self):\n+ return iter(self._response_object)\ndiff --git a/boxsdk/object/base_api_json_object.py b/boxsdk/object/base_api_json_object.py\nnew file mode 100644\nindex 0000000..8dbacde\n--- /dev/null\n+++ b/boxsdk/object/base_api_json_object.py\n@@ -0,0 +1,63 @@\n+# coding: utf-8\n+\n+from __future__ import unicode_literals, absolute_import\n+import six\n+\n+from ..util.translator import Translator\n+\n+\n+class BaseAPIJSONObjectMeta(type):\n+ \"\"\"\n+ Metaclass for Box API objects. Registers classes so that API responses can be translated to the correct type.\n+ Relies on the _item_type field defined on the classes to match the type property of the response json.\n+ But the type-class mapping will only be registered if the module of the class is imported.\n+ So it's also important to add the module name to __all__ in object/__init__.py.\n+ \"\"\"\n+ def __init__(cls, name, bases, attrs):\n+ super(BaseAPIJSONObjectMeta, cls).__init__(name, bases, attrs)\n+ item_type = attrs.get('_item_type', None)\n+ if item_type is not None:\n+ Translator().register(item_type, cls)\n+\n+\n+@six.add_metaclass(BaseAPIJSONObjectMeta)\n+class BaseAPIJSONObject(object):\n+ \"\"\"Base class containing basic logic shared between true REST objects and other objects (such as an Event)\"\"\"\n+\n+ _item_type = None\n+\n+ def __init__(self, response_object=None, **kwargs):\n+ \"\"\"\n+ :param response_object:\n+ A JSON object representing the object returned from a Box API request.\n+ :type response_object:\n+ `dict`\n+ \"\"\"\n+ super(BaseAPIJSONObject, self).__init__(**kwargs)\n+ self._response_object = response_object or {}\n+ self.__dict__.update(self._response_object)\n+\n+ def __getitem__(self, item):\n+ \"\"\"\n+ Try to get the attribute from the API response object.\n+\n+ :param item:\n+ The attribute to retrieve from the API response object.\n+ :type item:\n+ `unicode`\n+ \"\"\"\n+ return self._response_object[item]\n+\n+ def __repr__(self):\n+ \"\"\"Base class override. Return a human-readable representation using the Box ID or name of the object.\"\"\"\n+ extra_description = ' - {0}'.format(self._description) if self._description else ''\n+ description = ''.format(self.__class__.__name__, extra_description)\n+ if six.PY2:\n+ return description.encode('utf-8')\n+ else:\n+ return description\n+\n+ @property\n+ def _description(self):\n+ \"\"\"Return a description of the object if one exists.\"\"\"\n+ return \"\"\ndiff --git a/boxsdk/object/base_endpoint.py b/boxsdk/object/base_endpoint.py\nindex 76b0ffe..d24d8ca 100644\n--- a/boxsdk/object/base_endpoint.py\n+++ b/boxsdk/object/base_endpoint.py\n@@ -1,19 +1,23 @@\n # coding: utf-8\n \n-from __future__ import unicode_literals\n+from __future__ import unicode_literals, absolute_import\n \n \n class BaseEndpoint(object):\n \"\"\"A Box API endpoint.\"\"\"\n \n- def __init__(self, session):\n+ def __init__(self, session, **kwargs):\n \"\"\"\n-\n :param session:\n The Box session used to make requests.\n :type session:\n :class:`BoxSession`\n+ :param kwargs:\n+ Keyword arguments for base class constructors.\n+ :type kwargs:\n+ `dict`\n \"\"\"\n+ super(BaseEndpoint, self).__init__(**kwargs)\n self._session = session\n \n def get_url(self, endpoint, *args):\ndiff --git a/boxsdk/object/base_object.py b/boxsdk/object/base_object.py\nindex 3fe1d8b..5823222 100644\n--- a/boxsdk/object/base_object.py\n+++ b/boxsdk/object/base_object.py\n@@ -1,35 +1,15 @@\n # coding: utf-8\n \n-from __future__ import unicode_literals\n-from abc import ABCMeta\n+from __future__ import unicode_literals, absolute_import\n import json\n \n-import six\n+from .base_endpoint import BaseEndpoint\n+from .base_api_json_object import BaseAPIJSONObject\n+from ..util.translator import Translator\n \n-from boxsdk.object.base_endpoint import BaseEndpoint\n-from boxsdk.util.translator import Translator\n \n-\n-class ObjectMeta(ABCMeta):\n- \"\"\"\n- Metaclass for Box API objects. Registers classes so that API responses can be translated to the correct type.\n- Relies on the _item_type field defined on the classes to match the type property of the response json.\n- But the type-class mapping will only be registered if the module of the class is imported.\n- So it's also important to add the module name to __all__ in object/__init__.py.\n- \"\"\"\n- def __init__(cls, name, bases, attrs):\n- super(ObjectMeta, cls).__init__(name, bases, attrs)\n- item_type = attrs.get('_item_type', None)\n- if item_type is not None:\n- Translator().register(item_type, cls)\n-\n-\n-@six.add_metaclass(ObjectMeta)\n-class BaseObject(BaseEndpoint):\n- \"\"\"\n- A Box API endpoint for interacting with a Box object.\n- \"\"\"\n- _item_type = None\n+class BaseObject(BaseEndpoint, BaseAPIJSONObject):\n+ \"\"\"A Box API endpoint for interacting with a Box object.\"\"\"\n \n def __init__(self, session, object_id, response_object=None):\n \"\"\"\n@@ -42,29 +22,16 @@ def __init__(self, session, object_id, response_object=None):\n :type object_id:\n `unicode`\n :param response_object:\n- The Box API response representing the object.\n+ A JSON object representing the object returned from a Box API request.\n :type response_object:\n- :class:`BoxResponse`\n+ `dict`\n \"\"\"\n- super(BaseObject, self).__init__(session)\n+ super(BaseObject, self).__init__(session=session, response_object=response_object)\n self._object_id = object_id\n- self._response_object = response_object or {}\n- self.__dict__.update(self._response_object)\n-\n- def __getitem__(self, item):\n- \"\"\"Base class override. Try to get the attribute from the API response object.\"\"\"\n- return self._response_object[item]\n-\n- def __repr__(self):\n- \"\"\"Base class override. Return a human-readable representation using the Box ID or name of the object.\"\"\"\n- description = ''.format(self.__class__.__name__, self._description)\n- if six.PY2:\n- return description.encode('utf-8')\n- else:\n- return description\n \n @property\n def _description(self):\n+ \"\"\"Base class override. Return a description for the object.\"\"\"\n if 'name' in self._response_object:\n return '{0} ({1})'.format(self._object_id, self.name) # pylint:disable=no-member\n else:\n@@ -185,7 +152,7 @@ def delete(self, params=None, headers=None):\n return box_response.ok\n \n def __eq__(self, other):\n- \"\"\"Base class override. Equality is determined by object id.\"\"\"\n+ \"\"\"Equality as determined by object id\"\"\"\n return self._object_id == other.object_id\n \n def _paging_wrapper(self, url, starting_index, limit, factory=None):\ndiff --git a/boxsdk/object/event.py b/boxsdk/object/event.py\nnew file mode 100644\nindex 0000000..8025d80\n--- /dev/null\n+++ b/boxsdk/object/event.py\n@@ -0,0 +1,11 @@\n+# coding: utf-8\n+\n+from __future__ import unicode_literals, absolute_import\n+\n+from .api_json_object import APIJSONObject\n+\n+\n+class Event(APIJSONObject):\n+ \"\"\"Represents a single Box event.\"\"\"\n+\n+ _item_type = 'event'\ndiff --git a/boxsdk/object/events.py b/boxsdk/object/events.py\nindex dbb321f..3d62b43 100644\n--- a/boxsdk/object/events.py\n+++ b/boxsdk/object/events.py\n@@ -1,14 +1,14 @@\n # coding: utf-8\n \n-from __future__ import unicode_literals\n-\n+from __future__ import unicode_literals, absolute_import\n from requests.exceptions import Timeout\n from six import with_metaclass\n \n-from boxsdk.object.base_endpoint import BaseEndpoint\n-from boxsdk.util.enum import ExtendableEnumMeta\n-from boxsdk.util.lru_cache import LRUCache\n-from boxsdk.util.text_enum import TextEnum\n+from .base_endpoint import BaseEndpoint\n+from ..util.enum import ExtendableEnumMeta\n+from ..util.lru_cache import LRUCache\n+from ..util.text_enum import TextEnum\n+from ..util.translator import Translator\n \n \n # pylint:disable=too-many-ancestors\n@@ -79,8 +79,7 @@ def get_events(self, limit=100, stream_position=0, stream_type=UserEventsStreamT\n :type stream_type:\n :enum:`EventsStreamType`\n :returns:\n- JSON response from the Box /events endpoint. Contains the next stream position to use for the next call,\n- along with some number of events.\n+ Dictionary containing the next stream position along with a list of some number of events.\n :rtype:\n `dict`\n \"\"\"\n@@ -91,7 +90,10 @@ def get_events(self, limit=100, stream_position=0, stream_type=UserEventsStreamT\n 'stream_type': stream_type,\n }\n box_response = self._session.get(url, params=params)\n- return box_response.json()\n+ response = box_response.json().copy()\n+ if 'entries' in response:\n+ response['entries'] = [Translator().translate(item['type'])(item) for item in response['entries']]\n+ return response\n \n def get_latest_stream_position(self, stream_type=UserEventsStreamType.ALL):\n \"\"\"\ndiff --git a/boxsdk/object/folder.py b/boxsdk/object/folder.py\nindex 3aaf1c2..db07b60 100644\n--- a/boxsdk/object/folder.py\n+++ b/boxsdk/object/folder.py\n@@ -4,6 +4,7 @@\n import json\n import os\n from six import text_type\n+\n from boxsdk.config import API\n from boxsdk.object.collaboration import Collaboration\n from boxsdk.object.file import File\ndiff --git a/boxsdk/object/item.py b/boxsdk/object/item.py\nindex cc885af..d0d99cd 100644\n--- a/boxsdk/object/item.py\n+++ b/boxsdk/object/item.py\n@@ -1,7 +1,6 @@\n # coding: utf-8\n \n-from __future__ import unicode_literals\n-\n+from __future__ import unicode_literals, absolute_import\n import json\n \n from .base_object import BaseObject\n@@ -111,6 +110,10 @@ def rename(self, name):\n def get(self, fields=None, etag=None):\n \"\"\"Base class override.\n \n+ :param fields:\n+ List of fields to request.\n+ :type fields:\n+ `Iterable` of `unicode`\n :param etag:\n If specified, instruct the Box API to get the info only if the current version's etag doesn't match.\n :type etag:\ndiff --git a/boxsdk/object/metadata.py b/boxsdk/object/metadata.py\nindex 9c3fed0..7d5adee 100644\n--- a/boxsdk/object/metadata.py\n+++ b/boxsdk/object/metadata.py\n@@ -1,6 +1,6 @@\n # coding: utf-8\n \n-from __future__ import unicode_literals\n+from __future__ import unicode_literals, absolute_import\n import json\n from boxsdk.object.base_endpoint import BaseEndpoint\n \n"},"problem_statement":{"kind":"string","value":"Add an Event class\nRight now `get_events()` method in the `Events` class returns a `dict`. Ideally, we should have an `Event` class, and `Event` objects can also be translated. So `Events.get_events()` call will return a list of `Event` objects."},"repo":{"kind":"string","value":"box/box-python-sdk"},"test_patch":{"kind":"string","value":"diff --git a/test/functional/test_events.py b/test/functional/test_events.py\nindex b0ccd49..590682d 100644\n--- a/test/functional/test_events.py\n+++ b/test/functional/test_events.py\n@@ -8,6 +8,7 @@\n import requests\n \n from boxsdk.object.folder import FolderSyncState\n+from boxsdk.object.event import Event as BoxEvent\n \n \n @pytest.fixture\n@@ -36,6 +37,7 @@ def helper(get_item, event_type, stream_position=0):\n assert event['event_type'] == event_type\n assert event['source']['name'] == item.name\n assert event['source']['id'] == item.id\n+ assert isinstance(event, BoxEvent)\n \n return helper\n \ndiff --git a/test/unit/object/test_api_json_object.py b/test/unit/object/test_api_json_object.py\nnew file mode 100644\nindex 0000000..1be04ef\n--- /dev/null\n+++ b/test/unit/object/test_api_json_object.py\n@@ -0,0 +1,21 @@\n+# coding: utf-8\n+\n+from __future__ import unicode_literals, absolute_import\n+import pytest\n+\n+from boxsdk.object.api_json_object import APIJSONObject\n+\n+\n+@pytest.fixture(params=[{'foo': 'bar'}, {'a': {'b': 'c'}}])\n+def api_json_object(request):\n+ return request.param, APIJSONObject(request.param)\n+\n+\n+def test_len(api_json_object):\n+ dictionary, test_object = api_json_object\n+ assert len(dictionary) == len(test_object)\n+\n+\n+def test_api_json_object_dict(api_json_object):\n+ dictionary, test_object = api_json_object\n+ assert dictionary == test_object\ndiff --git a/test/unit/object/test_base_api_json_object.py b/test/unit/object/test_base_api_json_object.py\nnew file mode 100644\nindex 0000000..3032f11\n--- /dev/null\n+++ b/test/unit/object/test_base_api_json_object.py\n@@ -0,0 +1,24 @@\n+# coding: utf-8\n+\n+from __future__ import unicode_literals, absolute_import\n+import pytest\n+\n+from boxsdk.object.base_api_json_object import BaseAPIJSONObject\n+\n+\n+@pytest.fixture(params=[{'foo': 'bar'}, {'a': {'b': 'c'}}])\n+def response(request):\n+ return request.param\n+\n+\n+@pytest.fixture()\n+def base_api_json_object(response):\n+ dictionary_response = response\n+ return dictionary_response, BaseAPIJSONObject(dictionary_response)\n+\n+\n+def test_getitem(base_api_json_object):\n+ dictionary_response, test_object = base_api_json_object\n+ assert isinstance(test_object, BaseAPIJSONObject)\n+ for key in dictionary_response:\n+ assert test_object[key] == dictionary_response[key]\ndiff --git a/test/unit/object/test_event.py b/test/unit/object/test_event.py\nnew file mode 100644\nindex 0000000..1c4cd2e\n--- /dev/null\n+++ b/test/unit/object/test_event.py\n@@ -0,0 +1,20 @@\n+# coding: utf-8\n+\n+from __future__ import unicode_literals\n+\n+from boxsdk.object.event import Event\n+\n+\n+def test_init_event():\n+ event = Event(\n+ {\n+ \"type\": \"event\",\n+ \"event_id\": \"f82c3ba03e41f7e8a7608363cc6c0390183c3f83\",\n+ \"source\":\n+ {\n+ \"type\": \"folder\",\n+ \"id\": \"11446498\",\n+ },\n+ })\n+ assert event['type'] == 'event'\n+ assert event['event_id'] == 'f82c3ba03e41f7e8a7608363cc6c0390183c3f83'\ndiff --git a/test/unit/object/test_events.py b/test/unit/object/test_events.py\nindex bf45687..ff6c88e 100644\n--- a/test/unit/object/test_events.py\n+++ b/test/unit/object/test_events.py\n@@ -1,6 +1,6 @@\n # coding: utf-8\n \n-from __future__ import unicode_literals\n+from __future__ import unicode_literals, absolute_import\n \n from itertools import chain\n import json\n@@ -13,6 +13,7 @@\n \n from boxsdk.network.default_network import DefaultNetworkResponse\n from boxsdk.object.events import Events, EventsStreamType, UserEventsStreamType\n+from boxsdk.object.event import Event\n from boxsdk.session.box_session import BoxResponse\n from boxsdk.util.ordered_dict import OrderedDict\n \n@@ -169,22 +170,22 @@ def max_retries_long_poll_response(make_mock_box_request):\n \n \n @pytest.fixture()\n-def mock_event():\n+def mock_event_json():\n return {\n \"type\": \"event\",\n \"event_id\": \"f82c3ba03e41f7e8a7608363cc6c0390183c3f83\",\n \"source\": {\n \"type\": \"folder\",\n \"id\": \"11446498\",\n- }\n+ },\n }\n \n \n @pytest.fixture()\n-def events_response(initial_stream_position, mock_event, make_mock_box_request):\n+def events_response(initial_stream_position, mock_event_json, make_mock_box_request):\n # pylint:disable=redefined-outer-name\n mock_box_response, _ = make_mock_box_request(\n- response={\"next_stream_position\": initial_stream_position, \"entries\": [mock_event]},\n+ response={\"next_stream_position\": initial_stream_position, \"entries\": [mock_event_json]},\n )\n return mock_box_response\n \n@@ -205,6 +206,10 @@ def test_get_events(\n expected_url,\n params=dict(limit=100, stream_position=0, **expected_stream_type_params),\n )\n+ event_entries = events['entries']\n+ assert event_entries == events_response.json.return_value['entries']\n+ for event in event_entries:\n+ assert isinstance(event, Event)\n \n \n def test_get_long_poll_options(\n@@ -234,7 +239,7 @@ def test_generate_events_with_long_polling(\n new_change_long_poll_response,\n reconnect_long_poll_response,\n max_retries_long_poll_response,\n- mock_event,\n+ mock_event_json,\n stream_type_kwargs,\n expected_stream_type,\n expected_stream_type_params,\n@@ -253,7 +258,7 @@ def test_generate_events_with_long_polling(\n empty_events_response,\n ]\n events = test_events.generate_events_with_long_polling(**stream_type_kwargs)\n- assert next(events) == mock_event\n+ assert next(events) == Event(mock_event_json)\n with pytest.raises(StopIteration):\n next(events)\n events.close()\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"merge_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_added_files\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 2,\n \"test_score\": 3\n },\n \"num_modified_files\": 7\n}"},"version":{"kind":"string","value":"1.5"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\",\n \"pytest-cov\",\n \"pytest-xdist\",\n \"pytest-mock\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\",\n \"requirements-dev.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"alabaster==0.7.16\nastroid==3.3.9\nasync-timeout==5.0.1\nbabel==2.17.0\nbottle==0.13.2\n-e git+https://github.com/box/box-python-sdk.git@a1dba2d7699f6d3e798e89821d4650720e299ffd#egg=boxsdk\ncachetools==5.5.2\ncertifi==2025.1.31\ncffi==1.17.1\nchardet==5.2.0\ncharset-normalizer==3.4.1\ncolorama==0.4.6\ncoverage==7.8.0\ncryptography==44.0.2\ndill==0.3.9\ndistlib==0.3.9\ndocutils==0.21.2\nexceptiongroup==1.2.2\nexecnet==2.1.1\nfilelock==3.18.0\ngreenlet==3.1.1\nidna==3.10\nimagesize==1.4.1\nimportlib_metadata==8.6.1\niniconfig==2.1.0\nisort==6.0.1\nJinja2==3.1.6\njsonpatch==1.33\njsonpointer==3.0.0\nMarkupSafe==3.0.2\nmccabe==0.7.0\nmock==5.2.0\npackaging==24.2\npep8==1.7.1\nplatformdirs==4.3.7\npluggy==1.5.0\npycparser==2.22\nPygments==2.19.1\nPyJWT==2.10.1\npylint==3.3.6\npyproject-api==1.9.0\npytest==8.3.5\npytest-cov==6.0.0\npytest-mock==3.14.0\npytest-xdist==3.6.1\nredis==5.2.1\nrequests==2.32.3\nrequests-toolbelt==1.0.0\nsix==1.17.0\nsnowballstemmer==2.2.0\nSphinx==7.4.7\nsphinxcontrib-applehelp==2.0.0\nsphinxcontrib-devhelp==2.0.0\nsphinxcontrib-htmlhelp==2.1.0\nsphinxcontrib-jsmath==1.0.1\nsphinxcontrib-qthelp==2.0.0\nsphinxcontrib-serializinghtml==2.0.0\nSQLAlchemy==2.0.40\ntomli==2.2.1\ntomlkit==0.13.2\ntox==4.25.0\ntyping_extensions==4.13.0\nurllib3==2.3.0\nvirtualenv==20.29.3\nzipp==3.21.0\n"},"environment":{"kind":"string","value":"name: box-python-sdk\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - alabaster==0.7.16\n - astroid==3.3.9\n - async-timeout==5.0.1\n - babel==2.17.0\n - bottle==0.13.2\n - cachetools==5.5.2\n - certifi==2025.1.31\n - cffi==1.17.1\n - chardet==5.2.0\n - charset-normalizer==3.4.1\n - colorama==0.4.6\n - coverage==7.8.0\n - cryptography==44.0.2\n - dill==0.3.9\n - distlib==0.3.9\n - docutils==0.21.2\n - exceptiongroup==1.2.2\n - execnet==2.1.1\n - filelock==3.18.0\n - greenlet==3.1.1\n - idna==3.10\n - imagesize==1.4.1\n - importlib-metadata==8.6.1\n - iniconfig==2.1.0\n - isort==6.0.1\n - jinja2==3.1.6\n - jsonpatch==1.33\n - jsonpointer==3.0.0\n - markupsafe==3.0.2\n - mccabe==0.7.0\n - mock==5.2.0\n - packaging==24.2\n - pep8==1.7.1\n - platformdirs==4.3.7\n - pluggy==1.5.0\n - pycparser==2.22\n - pygments==2.19.1\n - pyjwt==2.10.1\n - pylint==3.3.6\n - pyproject-api==1.9.0\n - pytest==8.3.5\n - pytest-cov==6.0.0\n - pytest-mock==3.14.0\n - pytest-xdist==3.6.1\n - redis==5.2.1\n - requests==2.32.3\n - requests-toolbelt==1.0.0\n - six==1.17.0\n - snowballstemmer==2.2.0\n - sphinx==7.4.7\n - sphinxcontrib-applehelp==2.0.0\n - sphinxcontrib-devhelp==2.0.0\n - sphinxcontrib-htmlhelp==2.1.0\n - sphinxcontrib-jsmath==1.0.1\n - sphinxcontrib-qthelp==2.0.0\n - sphinxcontrib-serializinghtml==2.0.0\n - sqlalchemy==2.0.40\n - tomli==2.2.1\n - tomlkit==0.13.2\n - tox==4.25.0\n - typing-extensions==4.13.0\n - urllib3==2.3.0\n - virtualenv==20.29.3\n - zipp==3.21.0\nprefix: /opt/conda/envs/box-python-sdk\n"},"FAIL_TO_PASS":{"kind":"list like","value":["test/unit/object/test_api_json_object.py::test_len[api_json_object0]","test/unit/object/test_api_json_object.py::test_len[api_json_object1]","test/unit/object/test_api_json_object.py::test_api_json_object_dict[api_json_object0]","test/unit/object/test_api_json_object.py::test_api_json_object_dict[api_json_object1]","test/unit/object/test_base_api_json_object.py::test_getitem[response0]","test/unit/object/test_base_api_json_object.py::test_getitem[response1]","test/unit/object/test_event.py::test_init_event","test/unit/object/test_events.py::test_events_stream_type_extended_enum_class_has_expected_members","test/unit/object/test_events.py::test_get_events[None]","test/unit/object/test_events.py::test_get_long_poll_options[None]","test/unit/object/test_events.py::test_get_events[all0]","test/unit/object/test_events.py::test_get_long_poll_options[all0]","test/unit/object/test_events.py::test_get_events[changes0]","test/unit/object/test_events.py::test_get_long_poll_options[changes0]","test/unit/object/test_events.py::test_get_events[sync0]","test/unit/object/test_events.py::test_get_long_poll_options[sync0]","test/unit/object/test_events.py::test_get_events[admin_logs0]","test/unit/object/test_events.py::test_get_long_poll_options[admin_logs0]","test/unit/object/test_events.py::test_get_events[all1]","test/unit/object/test_events.py::test_get_long_poll_options[all1]","test/unit/object/test_events.py::test_get_events[changes1]","test/unit/object/test_events.py::test_get_long_poll_options[changes1]","test/unit/object/test_events.py::test_get_events[sync1]","test/unit/object/test_events.py::test_get_long_poll_options[sync1]","test/unit/object/test_events.py::test_get_events[admin_logs1]","test/unit/object/test_events.py::test_get_long_poll_options[admin_logs1]","test/unit/object/test_events.py::test_get_events[future_stream_type]","test/unit/object/test_events.py::test_get_long_poll_options[future_stream_type]"],"string":"[\n \"test/unit/object/test_api_json_object.py::test_len[api_json_object0]\",\n \"test/unit/object/test_api_json_object.py::test_len[api_json_object1]\",\n \"test/unit/object/test_api_json_object.py::test_api_json_object_dict[api_json_object0]\",\n \"test/unit/object/test_api_json_object.py::test_api_json_object_dict[api_json_object1]\",\n \"test/unit/object/test_base_api_json_object.py::test_getitem[response0]\",\n \"test/unit/object/test_base_api_json_object.py::test_getitem[response1]\",\n \"test/unit/object/test_event.py::test_init_event\",\n \"test/unit/object/test_events.py::test_events_stream_type_extended_enum_class_has_expected_members\",\n \"test/unit/object/test_events.py::test_get_events[None]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[None]\",\n \"test/unit/object/test_events.py::test_get_events[all0]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[all0]\",\n \"test/unit/object/test_events.py::test_get_events[changes0]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[changes0]\",\n \"test/unit/object/test_events.py::test_get_events[sync0]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[sync0]\",\n \"test/unit/object/test_events.py::test_get_events[admin_logs0]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[admin_logs0]\",\n \"test/unit/object/test_events.py::test_get_events[all1]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[all1]\",\n \"test/unit/object/test_events.py::test_get_events[changes1]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[changes1]\",\n \"test/unit/object/test_events.py::test_get_events[sync1]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[sync1]\",\n \"test/unit/object/test_events.py::test_get_events[admin_logs1]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[admin_logs1]\",\n \"test/unit/object/test_events.py::test_get_events[future_stream_type]\",\n \"test/unit/object/test_events.py::test_get_long_poll_options[future_stream_type]\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":["test/unit/object/test_events.py::test_generate_events_with_long_polling[None]","test/unit/object/test_events.py::test_generate_events_with_long_polling[all0]","test/unit/object/test_events.py::test_generate_events_with_long_polling[changes0]","test/unit/object/test_events.py::test_generate_events_with_long_polling[sync0]","test/unit/object/test_events.py::test_generate_events_with_long_polling[admin_logs0]","test/unit/object/test_events.py::test_generate_events_with_long_polling[all1]","test/unit/object/test_events.py::test_generate_events_with_long_polling[changes1]","test/unit/object/test_events.py::test_generate_events_with_long_polling[sync1]","test/unit/object/test_events.py::test_generate_events_with_long_polling[admin_logs1]","test/unit/object/test_events.py::test_generate_events_with_long_polling[future_stream_type]"],"string":"[\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[None]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[all0]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[changes0]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[sync0]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[admin_logs0]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[all1]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[changes1]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[sync1]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[admin_logs1]\",\n \"test/unit/object/test_events.py::test_generate_events_with_long_polling[future_stream_type]\"\n]"},"PASS_TO_PASS":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"Apache License 2.0"},"__index_level_0__":{"kind":"number","value":590,"string":"590"}}},{"rowIdx":590,"cells":{"instance_id":{"kind":"string","value":"Tiendil__pynames-15"},"base_commit":{"kind":"string","value":"bc496f64be0da44db0882b74b54125ce2e5e556b"},"created_at":{"kind":"string","value":"2016-06-17 08:36:12"},"environment_setup_commit":{"kind":"string","value":"bc496f64be0da44db0882b74b54125ce2e5e556b"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/helpers/merge_names.py b/helpers/merge_names.py\nindex b4628a9..a282df3 100644\n--- a/helpers/merge_names.py\n+++ b/helpers/merge_names.py\n@@ -3,6 +3,8 @@\n import os\n import json\n \n+import six\n+\n \n FIXTURES = ['mongolian/fixtures/mongolian_names_list.json',\n 'russian/fixtures/pagan_names_list.json',\n@@ -27,8 +29,8 @@ def names_equal(name, original_name):\n if language not in original_languages:\n continue\n \n- text = languages[language] if isinstance(languages[language], basestring) else languages[language][0]\n- original_text = original_languages[language] if isinstance(original_languages[language], basestring) else original_languages[language][0]\n+ text = languages[language] if isinstance(languages[language], six.string_types) else languages[language][0]\n+ original_text = original_languages[language] if isinstance(original_languages[language], six.string_types) else original_languages[language][0]\n \n if text == original_text:\n return True\n@@ -37,8 +39,8 @@ def names_equal(name, original_name):\n \n \n def merge_names(name, original_name):\n- for gender, languages in name['genders'].iteritems():\n- for language, data in languages.iteritems():\n+ for gender, languages in six.iteritems(name['genders']):\n+ for language, data in six.iteritems(languages):\n original_name['genders'][gender][language] = data\n \n \n@@ -54,7 +56,7 @@ def pretty_dump(data):\n content = []\n content.append(u'{')\n \n- for key, value in data.iteritems():\n+ for key, value in six.iteritems(data):\n if key != 'names':\n content.append(u' \"%s\": %s,' % (key, json.dumps(value, ensure_ascii=False)))\n \ndiff --git a/pynames/exceptions.py b/pynames/exceptions.py\nindex 48d5de7..16bbfb2 100644\n--- a/pynames/exceptions.py\n+++ b/pynames/exceptions.py\n@@ -1,5 +1,7 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n \n class PynamesError(Exception):\n MSG = None\n@@ -9,7 +11,7 @@ class PynamesError(Exception):\n \n \n class NoDefaultNameValue(PynamesError):\n- MSG = u'Name: can not get default value for name with data: %(raw_data)r'\n+ MSG = 'Name: can not get default value for name with data: %(raw_data)r'\n \n \n class FromListGeneratorError(PynamesError):\n@@ -17,7 +19,7 @@ class FromListGeneratorError(PynamesError):\n \n \n class NoNamesLoadedFromListError(FromListGeneratorError):\n- MSG = u'no names loaded from \"%(source)s\"'\n+ MSG = 'no names loaded from \"%(source)s\"'\n \n \n class FromTablesGeneratorError(PynamesError):\n@@ -25,11 +27,11 @@ class FromTablesGeneratorError(PynamesError):\n \n \n class WrongTemplateStructureError(FromTablesGeneratorError):\n- MSG = u'wrong template structure - cannot choose template for genders %(genders)r with template source: \"%(source)s\"'\n+ MSG = 'wrong template structure - cannot choose template for genders %(genders)r with template source: \"%(source)s\"'\n \n \n class NotEqualFormsLengths(FromTablesGeneratorError):\n- MSG = u'not equal forms lengths: [%(left)r] and [%(right)r]'\n+ MSG = 'not equal forms lengths: [%(left)r] and [%(right)r]'\n \n \n class WrongCSVData(FromTablesGeneratorError):\ndiff --git a/pynames/from_list_generator.py b/pynames/from_list_generator.py\nindex 9875e38..996e214 100644\n--- a/pynames/from_list_generator.py\n+++ b/pynames/from_list_generator.py\n@@ -1,4 +1,7 @@\n # coding: utf-8\n+\n+from __future__ import unicode_literals\n+\n import json\n import random\n \ndiff --git a/pynames/from_tables_generator.py b/pynames/from_tables_generator.py\nindex 7b68475..8688ec8 100644\n--- a/pynames/from_tables_generator.py\n+++ b/pynames/from_tables_generator.py\n@@ -1,11 +1,14 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n # python lib:\n import json\n import random\n from collections import Iterable\n \n # thirdparties:\n+import six\n import unicodecsv\n \n # pynames:\n@@ -39,28 +42,28 @@ class Template(object):\n \n @classmethod\n def merge_forms(cls, left, right):\n- if not isinstance(left, basestring):\n- if not isinstance(right, basestring):\n+ if not isinstance(left, six.string_types):\n+ if not isinstance(right, six.string_types):\n if len(left) != len(right):\n raise exceptions.NotEqualFormsLengths(left=left, right=right)\n return [l+r for l, r in zip(left, right)]\n else:\n return [l+right for l in left]\n else:\n- if not isinstance(right, basestring):\n+ if not isinstance(right, six.string_types):\n return [left+r for r in right]\n else:\n return left + right\n \n def get_name(self, tables):\n languages = dict(\n- (lang, u'') for lang in self.languages\n+ (lang, '') for lang in self.languages\n )\n for slug in self.template:\n record = random.choice(tables[slug])\n languages = {\n lang: self.merge_forms(forms, record['languages'][lang])\n- for lang, forms in languages.iteritems()\n+ for lang, forms in six.iteritems(languages)\n }\n \n genders = dict(\n@@ -103,7 +106,7 @@ class FromTablesGenerator(BaseGenerator):\n raise NotImplementedError(error_msg)\n \n with file_adapter(source) as f:\n- data = json.load(f)\n+ data = json.loads(f.read().decode('utf-8'))\n self.native_language = data['native_language']\n self.languages = set(data['languages'])\n self.full_forms_for_languages = set(data.get('full_forms_for_languages', set()))\n@@ -153,7 +156,7 @@ class FromTablesGenerator(BaseGenerator):\n return name.get_for(gender, language)\n \n def test_names_consistency(self, test):\n- for table_name, table in self.tables.iteritems():\n+ for table_name, table in six.iteritems(self.tables):\n for record in table:\n test.assertEqual(set(record['languages'].keys()) & self.languages, self.languages)\n \ndiff --git a/pynames/names.py b/pynames/names.py\nindex 1fcf27d..d69a297 100644\n--- a/pynames/names.py\n+++ b/pynames/names.py\n@@ -1,5 +1,9 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n+import six\n+\n from pynames.relations import GENDER, LANGUAGE\n from pynames import exceptions\n \n@@ -20,7 +24,7 @@ class Name(object):\n \n forms = self.translations[gender][language]\n \n- if not isinstance(forms, basestring):\n+ if not isinstance(forms, six.string_types):\n return forms[0]\n \n return forms\n@@ -31,7 +35,7 @@ class Name(object):\n \n forms = self.translations[gender][language]\n \n- if not isinstance(forms, basestring):\n+ if not isinstance(forms, six.string_types):\n return list(forms)\n \n return None\ndiff --git a/pynames/relations.py b/pynames/relations.py\nindex 3b2b5f3..f065488 100644\n--- a/pynames/relations.py\n+++ b/pynames/relations.py\n@@ -1,5 +1,7 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n class GENDER:\n MALE = 'm'\n FEMALE = 'f'\ndiff --git a/pynames/utils.py b/pynames/utils.py\nindex b7865e8..0430487 100644\n--- a/pynames/utils.py\n+++ b/pynames/utils.py\n@@ -1,5 +1,7 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n import contextlib\n import importlib\n import pkgutil\n@@ -54,6 +56,6 @@ def file_adapter(file_or_path):\n if is_file(file_or_path):\n file_obj = file_or_path\n else:\n- file_obj = open(file_or_path)\n+ file_obj = open(file_or_path, 'rb')\n yield file_obj\n file_obj.close()\ndiff --git a/setup.py b/setup.py\nindex a5e70ad..eb2a544 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -22,12 +22,14 @@ setuptools.setup(\n \n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n+ 'Programming Language :: Python :: 3',\n+ 'Programming Language :: Python :: 3.5',\n \n 'Natural Language :: English',\n 'Natural Language :: Russian'],\n keywords=['gamedev', 'game', 'game development', 'names', 'names generation'],\n packages=setuptools.find_packages(),\n- install_requires=['unicodecsv'],\n+ install_requires=['six', 'unicodecsv'],\n include_package_data=True,\n test_suite = 'tests',\n )\n"},"problem_statement":{"kind":"string","value":"Поддержка Python 3"},"repo":{"kind":"string","value":"Tiendil/pynames"},"test_patch":{"kind":"string","value":"diff --git a/pynames/tests/__init__.py b/pynames/tests/__init__.py\nindex 91bd147..e69de29 100644\n--- a/pynames/tests/__init__.py\n+++ b/pynames/tests/__init__.py\n@@ -1,7 +0,0 @@\n-# coding: utf-8\n-\n-from pynames.tests.test_name import *\n-from pynames.tests.test_from_list_generator import *\n-from pynames.tests.test_from_tables_generator import *\n-from pynames.tests.test_generators import *\n-from pynames.tests.test_utils import *\ndiff --git a/pynames/tests/test_from_list_generator.py b/pynames/tests/test_from_list_generator.py\nindex 35b7e10..3ffc28a 100644\n--- a/pynames/tests/test_from_list_generator.py\n+++ b/pynames/tests/test_from_list_generator.py\n@@ -1,8 +1,12 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n import os\n import unittest\n \n+from six.moves import xrange\n+\n from pynames.relations import GENDER, LANGUAGE\n from pynames.from_list_generator import FromListGenerator\n \ndiff --git a/pynames/tests/test_from_tables_generator.py b/pynames/tests/test_from_tables_generator.py\nindex 52b07e7..b1aef3f 100644\n--- a/pynames/tests/test_from_tables_generator.py\n+++ b/pynames/tests/test_from_tables_generator.py\n@@ -1,8 +1,13 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n import os\n import unittest\n \n+import six\n+from six.moves import xrange\n+\n from pynames.relations import GENDER, LANGUAGE\n from pynames.from_tables_generator import FromTablesGenerator, FromCSVTablesGenerator\n \n@@ -116,13 +121,9 @@ class TestFromCSVTablesGenerator(unittest.TestCase):\n csv_generator = self.TestCSVGenerator()\n \n for attr_name in ['native_language', 'languages', 'templates', 'tables']:\n- try:\n- json_attr = getattr(json_generator, attr_name)\n- csv_attr = getattr(csv_generator, attr_name)\n- if isinstance(json_attr, list):\n- self.assertItemsEqual(csv_attr, json_attr)\n- else:\n- self.assertEqual(csv_attr, json_attr)\n- except Exception:\n- from nose.tools import set_trace; set_trace()\n- raise\n+ json_attr = getattr(json_generator, attr_name)\n+ csv_attr = getattr(csv_generator, attr_name)\n+ if isinstance(json_attr, list):\n+ six.assertCountEqual(self, csv_attr, json_attr)\n+ else:\n+ self.assertEqual(csv_attr, json_attr)\ndiff --git a/pynames/tests/test_name.py b/pynames/tests/test_name.py\nindex 19182c0..0403736 100644\n--- a/pynames/tests/test_name.py\n+++ b/pynames/tests/test_name.py\n@@ -1,5 +1,8 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n+import six\n import unittest\n \n from pynames.relations import GENDER, LANGUAGE\n@@ -10,7 +13,7 @@ class TestName(unittest.TestCase):\n \n def test_base(self):\n name = Name('ru', {'genders': {'m': {'ru': 'ru_name'}}})\n- self.assertEqual(unicode(name), 'ru_name')\n+ self.assertEqual(six.text_type(name), 'ru_name')\n self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.RU), 'ru_name')\n self.assertEqual(name.get_for(GENDER.MALE), 'ru_name')\n self.assertEqual(name.get_forms_for(GENDER.MALE), None)\n@@ -18,7 +21,7 @@ class TestName(unittest.TestCase):\n def test_genders(self):\n name = Name('ru', {'genders': {'m': {'ru': 'ru_m_name'},\n 'f': {'ru': 'ru_f_name'}}})\n- self.assertEqual(unicode(name), 'ru_m_name')\n+ self.assertEqual(six.text_type(name), 'ru_m_name')\n self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.RU), 'ru_m_name')\n self.assertEqual(name.get_for(GENDER.FEMALE, LANGUAGE.RU), 'ru_f_name')\n \n@@ -27,7 +30,7 @@ class TestName(unittest.TestCase):\n 'en': 'en_m_name'},\n 'f': {'ru': 'ru_f_name',\n 'en': 'en_f_name'}}})\n- self.assertEqual(unicode(name), 'ru_m_name')\n+ self.assertEqual(six.text_type(name), 'ru_m_name')\n self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.RU), 'ru_m_name')\n self.assertEqual(name.get_for(GENDER.FEMALE, LANGUAGE.RU), 'ru_f_name')\n self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.EN), 'en_m_name')\ndiff --git a/pynames/tests/test_utils.py b/pynames/tests/test_utils.py\nindex acab40a..a62aa06 100644\n--- a/pynames/tests/test_utils.py\n+++ b/pynames/tests/test_utils.py\n@@ -1,5 +1,7 @@\n # coding: utf-8\n \n+from __future__ import unicode_literals\n+\n import os\n import tempfile\n import unittest\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 3,\n \"test_score\": 3\n },\n \"num_modified_files\": 8\n}"},"version":{"kind":"string","value":"0.2"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\",\n \"six\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements/base.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"exceptiongroup==1.2.2\niniconfig==2.1.0\npackaging==24.2\npluggy==1.5.0\n-e git+https://github.com/Tiendil/pynames.git@bc496f64be0da44db0882b74b54125ce2e5e556b#egg=Pynames\npytest==8.3.5\nsix==1.17.0\ntomli==2.2.1\nunicodecsv==0.14.1\n"},"environment":{"kind":"string","value":"name: pynames\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - exceptiongroup==1.2.2\n - iniconfig==2.1.0\n - packaging==24.2\n - pluggy==1.5.0\n - pytest==8.3.5\n - six==1.17.0\n - tomli==2.2.1\n - unicodecsv==0.14.1\nprefix: /opt/conda/envs/pynames\n"},"FAIL_TO_PASS":{"kind":"list like","value":["pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_base","pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_get_name__with_forms","pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_get_name_simple","pynames/tests/test_from_tables_generator.py::TestFromCSVTablesGenerator::test_init_state_equal","pynames/tests/test_name.py::TestName::test_base","pynames/tests/test_name.py::TestName::test_forms","pynames/tests/test_name.py::TestName::test_genders","pynames/tests/test_name.py::TestName::test_languages"],"string":"[\n \"pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_base\",\n \"pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_get_name__with_forms\",\n \"pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_get_name_simple\",\n \"pynames/tests/test_from_tables_generator.py::TestFromCSVTablesGenerator::test_init_state_equal\",\n \"pynames/tests/test_name.py::TestName::test_base\",\n \"pynames/tests/test_name.py::TestName::test_forms\",\n \"pynames/tests/test_name.py::TestName::test_genders\",\n \"pynames/tests/test_name.py::TestName::test_languages\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":["pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_base","pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_get_name__simple","pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_get_name__with_forms","pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_male_female_selection"],"string":"[\n \"pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_base\",\n \"pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_get_name__simple\",\n \"pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_get_name__with_forms\",\n \"pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_male_female_selection\"\n]"},"PASS_TO_PASS":{"kind":"list like","value":["pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_not_derived","pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_wrong_path","pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_male_female_selection","pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_not_derived","pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_wrong_path","pynames/tests/test_utils.py::TestName::test_file_adapter","pynames/tests/test_utils.py::TestName::test_is_file","pynames/tests/test_utils.py::TestName::test_is_file_on_django_files"],"string":"[\n \"pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_not_derived\",\n \"pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_wrong_path\",\n \"pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_male_female_selection\",\n \"pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_not_derived\",\n \"pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_wrong_path\",\n \"pynames/tests/test_utils.py::TestName::test_file_adapter\",\n \"pynames/tests/test_utils.py::TestName::test_is_file\",\n \"pynames/tests/test_utils.py::TestName::test_is_file_on_django_files\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD 3-Clause \"New\" or \"Revised\" License"},"__index_level_0__":{"kind":"number","value":591,"string":"591"}}},{"rowIdx":591,"cells":{"instance_id":{"kind":"string","value":"Axelrod-Python__Axelrod-638"},"base_commit":{"kind":"string","value":"89651f45910f4b41a79c58358d9f5beca4197fc1"},"created_at":{"kind":"string","value":"2016-06-19 20:45:17"},"environment_setup_commit":{"kind":"string","value":"89651f45910f4b41a79c58358d9f5beca4197fc1"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/axelrod/strategies/finite_state_machines.py b/axelrod/strategies/finite_state_machines.py\nindex defc4770..1c231d43 100644\n--- a/axelrod/strategies/finite_state_machines.py\n+++ b/axelrod/strategies/finite_state_machines.py\n@@ -54,6 +54,7 @@ class FSMPlayer(Player):\n initial_state = 1\n initial_action = C\n Player.__init__(self)\n+ self.initial_state = initial_state\n self.initial_action = initial_action\n self.fsm = SimpleFSM(transitions, initial_state)\n \n@@ -67,6 +68,10 @@ class FSMPlayer(Player):\n self.state = self.fsm.state\n return action\n \n+ def reset(self):\n+ Player.reset(self)\n+ self.fsm.state = self.initial_state\n+\n \n class Fortress3(FSMPlayer):\n \"\"\"Finite state machine player specified in DOI:10.1109/CEC.2006.1688322.\n"},"problem_statement":{"kind":"string","value":"Finite state machine players don't reset properly\n```\r\n>>> import axelrod as axl\r\n>>> tft = axl.TitForTat()\r\n>>> predator = axl.Predator()\r\n>>> predator.fsm.state\r\n1\r\n>>> m = axl.Match((tft, predator), 2)\r\n>>> m.play()\r\n[('C', 'C'), ('C', 'D')]\r\n>>> predator.fsm.state\r\n 2\r\n>>> predator.reset()\r\n>>> predator.fsm.state\r\n2\r\n```\r\n\r\nStumbled on this working on #636 (writing a hypothesis strategy that contrite TfT reduces to TfT in 0 noise) so the above is reduced from seeing that when playing the same match again we get a different output:\r\n\r\n```\r\n>>> m = axl.Match((tft, predator), 2)\r\n>>> m.play()\r\n[('C', 'C'), ('C', 'C')]\r\n```\r\n\r\nAm going to work on a fix now and include a hypothesis test that checks that random deterministic matches give the same outcomes."},"repo":{"kind":"string","value":"Axelrod-Python/Axelrod"},"test_patch":{"kind":"string","value":"diff --git a/axelrod/tests/integration/test_matches.py b/axelrod/tests/integration/test_matches.py\nnew file mode 100644\nindex 00000000..b6241145\n--- /dev/null\n+++ b/axelrod/tests/integration/test_matches.py\n@@ -0,0 +1,25 @@\n+\"\"\"Tests for some expected match behaviours\"\"\"\n+import unittest\n+import axelrod\n+\n+from hypothesis import given\n+from hypothesis.strategies import integers\n+from axelrod.tests.property import strategy_lists\n+\n+C, D = axelrod.Actions.C, axelrod.Actions.D\n+\n+deterministic_strategies = [s for s in axelrod.ordinary_strategies\n+ if not s().classifier['stochastic']] # Well behaved strategies\n+\n+class TestMatchOutcomes(unittest.TestCase):\n+\n+ @given(strategies=strategy_lists(strategies=deterministic_strategies,\n+ min_size=2, max_size=2),\n+ turns=integers(min_value=1, max_value=20))\n+ def test_outcome_repeats(self, strategies, turns):\n+ \"\"\"A test that if we repeat 3 matches with deterministic and well\n+ behaved strategies then we get the same result\"\"\"\n+ players = [s() for s in strategies]\n+ matches = [axelrod.Match(players, turns) for _ in range(3)]\n+ self.assertEqual(matches[0].play(), matches[1].play())\n+ self.assertEqual(matches[1].play(), matches[2].play())\ndiff --git a/axelrod/tests/unit/test_finite_state_machines.py b/axelrod/tests/unit/test_finite_state_machines.py\nindex 043834a1..d8147a59 100644\n--- a/axelrod/tests/unit/test_finite_state_machines.py\n+++ b/axelrod/tests/unit/test_finite_state_machines.py\n@@ -111,6 +111,12 @@ class TestFSMPlayer(TestPlayer):\n fsm = player.fsm\n self.assertTrue(check_state_transitions(fsm.state_transitions))\n \n+ def test_reset_initial_state(self):\n+ player = self.player()\n+ player.fsm.state = -1\n+ player.reset()\n+ self.assertFalse(player.fsm.state == -1)\n+\n \n class TestFortress3(TestFSMPlayer):\n \n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_issue_reference\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 0,\n \"test_score\": 0\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"1.2"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\",\n \"pytest-cov\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==25.3.0\n-e git+https://github.com/Axelrod-Python/Axelrod.git@89651f45910f4b41a79c58358d9f5beca4197fc1#egg=Axelrod\ncoverage==7.8.0\ncycler==0.12.1\nexceptiongroup==1.2.2\nhypothesis==6.130.5\niniconfig==2.1.0\nkiwisolver==1.4.7\nmatplotlib==3.3.4\nnumpy==2.0.2\npackaging==24.2\npillow==11.1.0\npluggy==1.5.0\npyparsing==2.1.1\npytest==8.3.5\npytest-cov==6.0.0\npython-dateutil==2.9.0.post0\nsix==1.17.0\nsortedcontainers==2.4.0\ntomli==2.2.1\ntqdm==3.4.0\n"},"environment":{"kind":"string","value":"name: Axelrod\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==25.3.0\n - coverage==7.8.0\n - cycler==0.12.1\n - exceptiongroup==1.2.2\n - hypothesis==6.130.5\n - iniconfig==2.1.0\n - kiwisolver==1.4.7\n - matplotlib==3.3.4\n - numpy==2.0.2\n - packaging==24.2\n - pillow==11.1.0\n - pluggy==1.5.0\n - pyparsing==2.1.1\n - pytest==8.3.5\n - pytest-cov==6.0.0\n - python-dateutil==2.9.0.post0\n - six==1.17.0\n - sortedcontainers==2.4.0\n - tomli==2.2.1\n - tqdm==3.4.0\nprefix: /opt/conda/envs/Axelrod\n"},"FAIL_TO_PASS":{"kind":"list like","value":["axelrod/tests/integration/test_matches.py::TestMatchOutcomes::test_outcome_repeats","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_reset_initial_state","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_reset_initial_state"],"string":"[\n \"axelrod/tests/integration/test_matches.py::TestMatchOutcomes::test_outcome_repeats\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_reset_initial_state\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_reset_initial_state\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_cooperator","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_defector","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_malformed_tables","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_tft","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_wsls","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_clone","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_initialisation","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_match_attributes","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_repr","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_reset","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_strategy","axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_transitions","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsFortress3::test_rounds","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsTitForTat::test_rounds","axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsCooperator::test_rounds","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsFortress4::test_rounds","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsTitForTat::test_rounds","axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsCooperator::test_rounds"],"string":"[\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_cooperator\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_defector\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_malformed_tables\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_tft\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_wsls\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_clone\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_initialisation\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_match_attributes\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_repr\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_reset\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_strategy\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_transitions\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsFortress3::test_rounds\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsTitForTat::test_rounds\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsCooperator::test_rounds\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsFortress4::test_rounds\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsTitForTat::test_rounds\",\n \"axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsCooperator::test_rounds\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":592,"string":"592"}}},{"rowIdx":592,"cells":{"instance_id":{"kind":"string","value":"scrapy__scrapy-2065"},"base_commit":{"kind":"string","value":"d43a35735a062a4260b002cfbcd3236c77ef9399"},"created_at":{"kind":"string","value":"2016-06-20 14:49:59"},"environment_setup_commit":{"kind":"string","value":"d7b26edf6b419e379a7a0a425093f02cac2fcf33"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/scrapy/utils/gz.py b/scrapy/utils/gz.py\nindex cfb652143..afc7ed128 100644\n--- a/scrapy/utils/gz.py\n+++ b/scrapy/utils/gz.py\n@@ -50,9 +50,12 @@ def gunzip(data):\n raise\n return output\n \n-_is_gzipped_re = re.compile(br'^application/(x-)?gzip\\b', re.I)\n+_is_gzipped = re.compile(br'^application/(x-)?gzip\\b', re.I).search\n+_is_octetstream = re.compile(br'^(application|binary)/octet-stream\\b', re.I).search\n \n def is_gzipped(response):\n \"\"\"Return True if the response is gzipped, or False otherwise\"\"\"\n ctype = response.headers.get('Content-Type', b'')\n- return _is_gzipped_re.search(ctype) is not None\n+ cenc = response.headers.get('Content-Encoding', b'').lower()\n+ return (_is_gzipped(ctype) or\n+ (_is_octetstream(ctype) and cenc in (b'gzip', b'x-gzip')))\n"},"problem_statement":{"kind":"string","value":"IOError, 'Not a gzipped file'\nwhile trying to access sitemap from robots.txt , Scrapy fails with **IOError, 'Not a gzipped file'** error\r\n\r\nnot sure if this issue is related to following issue(s)\r\nhttps://github.com/scrapy/scrapy/issues/193 -> closed issue\r\nhttps://github.com/scrapy/scrapy/pull/660 -> merged pull request to address issue 193\r\nhttps://github.com/scrapy/scrapy/issues/951 -> open issue\r\n\r\n> line where code fails in gzip.py at line # 197\r\n```python \r\ndef _read_gzip_header(self):\r\n magic = self.fileobj.read(2)\r\n if magic != '\\037\\213':\r\n raise IOError, 'Not a gzipped file'\r\n```\r\n\r\n#Response Header\r\n```\r\nContent-Encoding: gzip\r\nAccept-Ranges: bytes\r\nX-Amz-Request-Id: BFFF010DDE6268DA\r\nVary: Accept-Encoding\r\nServer: AmazonS3\r\nLast-Modified: Wed, 15 Jun 2016 19:02:20 GMT\r\nEtag: \"300bb71d6897cb2a22bba0bd07978c84\"\r\nCache-Control: no-transform\r\nDate: Sun, 19 Jun 2016 10:54:53 GMT\r\nContent-Type: binary/octet-stream\r\n```\r\n\r\n\r\nError Log:\r\n\r\n```log\r\n Traceback (most recent call last):\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\utils\\defer.py\", line 102, in iter_errback\r\n yield next(it)\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\spidermiddlewares\\offsite.py\", line 29, in process_spider_output\r\n for x in result:\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\spidermiddlewares\\referer.py\", line 22, in \r\n return (_set_referer(r) for r in result or ())\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\spidermiddlewares\\urllength.py\", line 37, in \r\n return (r for r in result or () if _filter(r))\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\spidermiddlewares\\depth.py\", line 58, in \r\n return (r for r in result or () if _filter(r))\r\n File \"D:\\projects\\sitemap_spider\\sitemap_spider\\spiders\\mainspider.py\", line 31, in _parse_sitemap\r\n body = self._get_sitemap_body(response)\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\spiders\\sitemap.py\", line 67, in _get_sitemap_body\r\n return gunzip(response.body)\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\utils\\gz.py\", line 37, in gunzip\r\n chunk = read1(f, 8196)\r\n File \"c:\\venv\\scrapy1.0\\lib\\site-packages\\scrapy\\utils\\gz.py\", line 21, in read1\r\n return gzf.read(size)\r\n File \"c:\\python27\\Lib\\gzip.py\", line 268, in read\r\n self._read(readsize)\r\n File \"c:\\python27\\Lib\\gzip.py\", line 303, in _read\r\n self._read_gzip_header()\r\n File \"c:\\python27\\Lib\\gzip.py\", line 197, in _read_gzip_header\r\n raise IOError, 'Not a gzipped file'\r\n```\r\ni did download file manually and was able to extract the content so it is not like file is corrupted \r\n\r\nas an example sitemap url : you can follow amazon robots.txt"},"repo":{"kind":"string","value":"scrapy/scrapy"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_downloadermiddleware_httpcompression.py b/tests/test_downloadermiddleware_httpcompression.py\nindex 24955a515..b2426946d 100644\n--- a/tests/test_downloadermiddleware_httpcompression.py\n+++ b/tests/test_downloadermiddleware_httpcompression.py\n@@ -145,6 +145,26 @@ class HttpCompressionTest(TestCase):\n self.assertEqual(response.headers['Content-Encoding'], b'gzip')\n self.assertEqual(response.headers['Content-Type'], b'application/gzip')\n \n+ def test_process_response_gzip_app_octetstream_contenttype(self):\n+ response = self._getresponse('gzip')\n+ response.headers['Content-Type'] = 'application/octet-stream'\n+ request = response.request\n+\n+ newresponse = self.mw.process_response(request, response, self.spider)\n+ self.assertIs(newresponse, response)\n+ self.assertEqual(response.headers['Content-Encoding'], b'gzip')\n+ self.assertEqual(response.headers['Content-Type'], b'application/octet-stream')\n+\n+ def test_process_response_gzip_binary_octetstream_contenttype(self):\n+ response = self._getresponse('x-gzip')\n+ response.headers['Content-Type'] = 'binary/octet-stream'\n+ request = response.request\n+\n+ newresponse = self.mw.process_response(request, response, self.spider)\n+ self.assertIs(newresponse, response)\n+ self.assertEqual(response.headers['Content-Encoding'], b'gzip')\n+ self.assertEqual(response.headers['Content-Type'], b'binary/octet-stream')\n+\n def test_process_response_head_request_no_decode_required(self):\n response = self._getresponse('gzip')\n response.headers['Content-Type'] = 'application/gzip'\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [],\n \"has_test_patch\": true,\n \"is_lite\": true,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 0,\n \"test_score\": 0\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"1.2"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\",\n \"pytest-cov\",\n \"pytest-xdist\",\n \"pytest-mock\",\n \"pytest-asyncio\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==25.3.0\nAutomat==24.8.1\ncffi==1.17.1\nconstantly==23.10.4\ncoverage==7.8.0\ncryptography==44.0.2\ncssselect==1.3.0\nexceptiongroup==1.2.2\nexecnet==2.1.1\nhyperlink==21.0.0\nidna==3.10\nincremental==24.7.2\niniconfig==2.1.0\njmespath==1.0.1\nlxml==5.3.1\npackaging==24.2\nparsel==1.10.0\npluggy==1.5.0\npyasn1==0.6.1\npyasn1_modules==0.4.2\npycparser==2.22\nPyDispatcher==2.0.7\npyOpenSSL==25.0.0\npytest==8.3.5\npytest-asyncio==0.26.0\npytest-cov==6.0.0\npytest-mock==3.14.0\npytest-xdist==3.6.1\nqueuelib==1.7.0\n-e git+https://github.com/scrapy/scrapy.git@d43a35735a062a4260b002cfbcd3236c77ef9399#egg=Scrapy\nservice-identity==24.2.0\nsix==1.17.0\ntomli==2.2.1\nTwisted==24.11.0\ntyping_extensions==4.13.0\nw3lib==2.3.1\nzope.interface==7.2\n"},"environment":{"kind":"string","value":"name: scrapy\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==25.3.0\n - automat==24.8.1\n - cffi==1.17.1\n - constantly==23.10.4\n - coverage==7.8.0\n - cryptography==44.0.2\n - cssselect==1.3.0\n - exceptiongroup==1.2.2\n - execnet==2.1.1\n - hyperlink==21.0.0\n - idna==3.10\n - incremental==24.7.2\n - iniconfig==2.1.0\n - jmespath==1.0.1\n - lxml==5.3.1\n - packaging==24.2\n - parsel==1.10.0\n - pluggy==1.5.0\n - pyasn1==0.6.1\n - pyasn1-modules==0.4.2\n - pycparser==2.22\n - pydispatcher==2.0.7\n - pyopenssl==25.0.0\n - pytest==8.3.5\n - pytest-asyncio==0.26.0\n - pytest-cov==6.0.0\n - pytest-mock==3.14.0\n - pytest-xdist==3.6.1\n - queuelib==1.7.0\n - service-identity==24.2.0\n - six==1.17.0\n - tomli==2.2.1\n - twisted==24.11.0\n - typing-extensions==4.13.0\n - w3lib==2.3.1\n - zope-interface==7.2\nprefix: /opt/conda/envs/scrapy\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_app_octetstream_contenttype","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_binary_octetstream_contenttype"],"string":"[\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_app_octetstream_contenttype\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_binary_octetstream_contenttype\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_multipleencodings","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_request","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_encoding_inside_body","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_force_recalculate_encoding","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzipped_contenttype","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_head_request_no_decode_required","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_plain","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_rawdeflate","tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_zlibdelate"],"string":"[\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_multipleencodings\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_request\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_encoding_inside_body\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_force_recalculate_encoding\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzipped_contenttype\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_head_request_no_decode_required\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_plain\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_rawdeflate\",\n \"tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_zlibdelate\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD 3-Clause \"New\" or \"Revised\" License"},"__index_level_0__":{"kind":"number","value":593,"string":"593"}}},{"rowIdx":593,"cells":{"instance_id":{"kind":"string","value":"Backblaze__B2_Command_Line_Tool-178"},"base_commit":{"kind":"string","value":"761d24c8dbd00f94decbf14cf0136de0a0d9f054"},"created_at":{"kind":"string","value":"2016-06-21 15:08:47"},"environment_setup_commit":{"kind":"string","value":"01c4e89f63f38b9efa6a6fa63f54cd556a0b5305"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/b2/bucket.py b/b2/bucket.py\nindex 9347570..6d4332a 100644\n--- a/b2/bucket.py\n+++ b/b2/bucket.py\n@@ -34,7 +34,7 @@ class LargeFileUploadState(object):\n \"\"\"\n \n def __init__(self, file_progress_listener):\n- self.lock = threading.Lock()\n+ self.lock = threading.RLock()\n self.error_message = None\n self.file_progress_listener = file_progress_listener\n self.part_number_to_part_state = {}\n@@ -48,6 +48,11 @@ class LargeFileUploadState(object):\n with self.lock:\n return self.error_message is not None\n \n+ def get_error_message(self):\n+ with self.lock:\n+ assert self.has_error()\n+ return self.error_message\n+\n def update_part_bytes(self, bytes_delta):\n with self.lock:\n self.bytes_completed += bytes_delta\n"},"problem_statement":{"kind":"string","value":"LargeFileUploadState object has no attribute get_error_message\nIn my backup log file I saw this line:\r\n\r\n`b2_upload(/backup/#########.tar.gz,#########.tar.gz, 1466468375649): AttributeError(\"'LargeFileUploadState' object has no attribute 'get_error_message'\",) 'LargeFileUploadState' object has no attribute 'get_error_message'`\r\n\r\nNo retry attempt were made and the file failed to upload.\r\n\r\n(the ### were intentional and not the real file name)"},"repo":{"kind":"string","value":"Backblaze/B2_Command_Line_Tool"},"test_patch":{"kind":"string","value":"diff --git a/test/test_bucket.py b/test/test_bucket.py\nindex 766af3c..44cb2e2 100644\n--- a/test/test_bucket.py\n+++ b/test/test_bucket.py\n@@ -18,8 +18,9 @@ import six\n \n from b2.account_info import StubAccountInfo\n from b2.api import B2Api\n+from b2.bucket import LargeFileUploadState\n from b2.download_dest import DownloadDestBytes\n-from b2.exception import B2Error, InvalidAuthToken, MaxRetriesExceeded\n+from b2.exception import AlreadyFailed, B2Error, InvalidAuthToken, MaxRetriesExceeded\n from b2.file_version import FileVersionInfo\n from b2.part import Part\n from b2.progress import AbstractProgressListener\n@@ -146,6 +147,22 @@ class TestListParts(TestCaseWithBucket):\n self.assertEqual(expected_parts, list(self.bucket.list_parts(file1.file_id, batch_size=1)))\n \n \n+class TestUploadPart(TestCaseWithBucket):\n+ def test_error_in_state(self):\n+ file1 = self.bucket.start_large_file('file1.txt', 'text/plain', {})\n+ content = six.b('hello world')\n+ file_progress_listener = mock.MagicMock()\n+ large_file_upload_state = LargeFileUploadState(file_progress_listener)\n+ large_file_upload_state.set_error('test error')\n+ try:\n+ self.bucket._upload_part(\n+ file1.file_id, 1, (0, 11), UploadSourceBytes(content), large_file_upload_state\n+ )\n+ self.fail('should have thrown')\n+ except AlreadyFailed:\n+ pass\n+\n+\n class TestListUnfinished(TestCaseWithBucket):\n def test_empty(self):\n self.assertEqual([], list(self.bucket.list_unfinished_large_files()))\ndiff --git a/test_b2_command_line.py b/test_b2_command_line.py\nindex 7cadd76..8d23678 100644\n--- a/test_b2_command_line.py\n+++ b/test_b2_command_line.py\n@@ -319,8 +319,8 @@ def basic_test(b2_tool, bucket_name):\n \n file_to_upload = 'README.md'\n \n- with open(file_to_upload, 'rb') as f:\n- hex_sha1 = hashlib.sha1(f.read()).hexdigest()\n+ hex_sha1 = hashlib.sha1(read_file(file_to_upload)).hexdigest()\n+\n uploaded_a = b2_tool.should_succeed_json(\n [\n 'upload_file', '--noProgress', '--quiet', bucket_name, file_to_upload, 'a'\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [],\n \"has_test_patch\": true,\n \"is_lite\": true,\n \"llm_score\": {\n \"difficulty_score\": 0,\n \"issue_text_score\": 3,\n \"test_score\": 2\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"0.5"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"nose\",\n \"yapf\",\n \"pyflakes\",\n \"pytest\"\n ],\n \"pre_install\": [],\n \"python\": \"3.5\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\n-e git+https://github.com/Backblaze/B2_Command_Line_Tool.git@761d24c8dbd00f94decbf14cf0136de0a0d9f054#egg=b2\ncertifi==2021.5.30\ncharset-normalizer==2.0.12\nidna==3.10\nimportlib-metadata==4.8.3\nimportlib-resources==5.4.0\niniconfig==1.1.1\nnose==1.3.7\npackaging==21.3\npluggy==1.0.0\npy==1.11.0\npyflakes==3.0.1\npyparsing==3.1.4\npytest==7.0.1\nrequests==2.27.1\nsix==1.17.0\ntomli==1.2.3\ntqdm==4.64.1\ntyping_extensions==4.1.1\nurllib3==1.26.20\nyapf==0.32.0\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: B2_Command_Line_Tool\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - charset-normalizer==2.0.12\n - idna==3.10\n - importlib-metadata==4.8.3\n - importlib-resources==5.4.0\n - iniconfig==1.1.1\n - nose==1.3.7\n - packaging==21.3\n - pluggy==1.0.0\n - py==1.11.0\n - pyflakes==3.0.1\n - pyparsing==3.1.4\n - pytest==7.0.1\n - requests==2.27.1\n - six==1.17.0\n - tomli==1.2.3\n - tqdm==4.64.1\n - typing-extensions==4.1.1\n - urllib3==1.26.20\n - yapf==0.32.0\n - zipp==3.6.0\nprefix: /opt/conda/envs/B2_Command_Line_Tool\n"},"FAIL_TO_PASS":{"kind":"list like","value":["test/test_bucket.py::TestUploadPart::test_error_in_state"],"string":"[\n \"test/test_bucket.py::TestUploadPart::test_error_in_state\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["test/test_bucket.py::TestReauthorization::testCreateBucket","test/test_bucket.py::TestListParts::testEmpty","test/test_bucket.py::TestListParts::testThree","test/test_bucket.py::TestListUnfinished::test_empty","test/test_bucket.py::TestListUnfinished::test_one","test/test_bucket.py::TestListUnfinished::test_three","test/test_bucket.py::TestLs::test_empty","test/test_bucket.py::TestLs::test_hidden_file","test/test_bucket.py::TestLs::test_one_file_at_root","test/test_bucket.py::TestLs::test_started_large_file","test/test_bucket.py::TestLs::test_three_files_at_root","test/test_bucket.py::TestLs::test_three_files_in_dir","test/test_bucket.py::TestLs::test_three_files_multiple_versions","test/test_bucket.py::TestUpload::test_upload_bytes","test/test_bucket.py::TestUpload::test_upload_bytes_progress","test/test_bucket.py::TestUpload::test_upload_file_one_fatal_error","test/test_bucket.py::TestUpload::test_upload_file_too_many_retryable_errors","test/test_bucket.py::TestUpload::test_upload_large","test/test_bucket.py::TestUpload::test_upload_large_resume","test/test_bucket.py::TestUpload::test_upload_large_resume_all_parts_there","test/test_bucket.py::TestUpload::test_upload_large_resume_file_info","test/test_bucket.py::TestUpload::test_upload_large_resume_file_info_does_not_match","test/test_bucket.py::TestUpload::test_upload_large_resume_no_parts","test/test_bucket.py::TestUpload::test_upload_large_resume_part_does_not_match","test/test_bucket.py::TestUpload::test_upload_large_resume_wrong_part_size","test/test_bucket.py::TestUpload::test_upload_local_file","test/test_bucket.py::TestUpload::test_upload_one_retryable_error","test/test_bucket.py::TestDownload::test_download_by_id_no_progress","test/test_bucket.py::TestDownload::test_download_by_id_progress","test/test_bucket.py::TestDownload::test_download_by_name_no_progress","test/test_bucket.py::TestDownload::test_download_by_name_progress","test_b2_command_line.py::TestCommandLine::test_stderr_patterns"],"string":"[\n \"test/test_bucket.py::TestReauthorization::testCreateBucket\",\n \"test/test_bucket.py::TestListParts::testEmpty\",\n \"test/test_bucket.py::TestListParts::testThree\",\n \"test/test_bucket.py::TestListUnfinished::test_empty\",\n \"test/test_bucket.py::TestListUnfinished::test_one\",\n \"test/test_bucket.py::TestListUnfinished::test_three\",\n \"test/test_bucket.py::TestLs::test_empty\",\n \"test/test_bucket.py::TestLs::test_hidden_file\",\n \"test/test_bucket.py::TestLs::test_one_file_at_root\",\n \"test/test_bucket.py::TestLs::test_started_large_file\",\n \"test/test_bucket.py::TestLs::test_three_files_at_root\",\n \"test/test_bucket.py::TestLs::test_three_files_in_dir\",\n \"test/test_bucket.py::TestLs::test_three_files_multiple_versions\",\n \"test/test_bucket.py::TestUpload::test_upload_bytes\",\n \"test/test_bucket.py::TestUpload::test_upload_bytes_progress\",\n \"test/test_bucket.py::TestUpload::test_upload_file_one_fatal_error\",\n \"test/test_bucket.py::TestUpload::test_upload_file_too_many_retryable_errors\",\n \"test/test_bucket.py::TestUpload::test_upload_large\",\n \"test/test_bucket.py::TestUpload::test_upload_large_resume\",\n \"test/test_bucket.py::TestUpload::test_upload_large_resume_all_parts_there\",\n \"test/test_bucket.py::TestUpload::test_upload_large_resume_file_info\",\n \"test/test_bucket.py::TestUpload::test_upload_large_resume_file_info_does_not_match\",\n \"test/test_bucket.py::TestUpload::test_upload_large_resume_no_parts\",\n \"test/test_bucket.py::TestUpload::test_upload_large_resume_part_does_not_match\",\n \"test/test_bucket.py::TestUpload::test_upload_large_resume_wrong_part_size\",\n \"test/test_bucket.py::TestUpload::test_upload_local_file\",\n \"test/test_bucket.py::TestUpload::test_upload_one_retryable_error\",\n \"test/test_bucket.py::TestDownload::test_download_by_id_no_progress\",\n \"test/test_bucket.py::TestDownload::test_download_by_id_progress\",\n \"test/test_bucket.py::TestDownload::test_download_by_name_no_progress\",\n \"test/test_bucket.py::TestDownload::test_download_by_name_progress\",\n \"test_b2_command_line.py::TestCommandLine::test_stderr_patterns\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"MIT License"},"__index_level_0__":{"kind":"number","value":594,"string":"594"}}},{"rowIdx":594,"cells":{"instance_id":{"kind":"string","value":"joblib__joblib-370"},"base_commit":{"kind":"string","value":"40341615cc2600675ce7457d9128fb030f6f89fa"},"created_at":{"kind":"string","value":"2016-06-22 09:45:21"},"environment_setup_commit":{"kind":"string","value":"40341615cc2600675ce7457d9128fb030f6f89fa"},"hints_text":{"kind":"string","value":"aabadie: I pushed an update commit (1c7763e) that ensures the numpy array wrapper is written in a dedicated frame in the pickle byte stream. I think it's cleaner.\naabadie: @lesteve, comments addressed.\naabadie: @lesteve, I reverted to the initial solution. \nlesteve: LGTM, merging, great job!"},"patch":{"kind":"string","value":"diff --git a/joblib/numpy_pickle.py b/joblib/numpy_pickle.py\nindex 0cb616d..f029582 100644\n--- a/joblib/numpy_pickle.py\n+++ b/joblib/numpy_pickle.py\n@@ -265,6 +265,14 @@ class NumpyPickler(Pickler):\n wrapper = self._create_array_wrapper(obj)\n Pickler.save(self, wrapper)\n \n+ # A framer was introduced with pickle protocol 4 and we want to\n+ # ensure the wrapper object is written before the numpy array\n+ # buffer in the pickle file.\n+ # See https://www.python.org/dev/peps/pep-3154/#framing to get\n+ # more information on the framer behavior.\n+ if self.proto >= 4:\n+ self.framer.commit_frame(force=True)\n+\n # And then array bytes are written right after the wrapper.\n wrapper.write_array(obj, self)\n return\n"},"problem_statement":{"kind":"string","value":"load fails when dump use pickle.HIGHEST_PROTOCOL in Python 3\nin master branch a96878e (version 0.10.0.dev0), the following code gives `KeyError`\r\n\r\n```py\r\nimport pickle\r\nimport numpy as np\r\nimport joblib\r\n\r\na = np.zeros((1, 235), np.uint32)\r\njoblib.dump(a, 'tmp.jl', protocol=pickle.HIGHEST_PROTOCOL)\r\njoblib.load('tmp.jl')\r\n```\r\n\r\nThat is: joblib seems do not support load data which saved with `pickle.HIGHEST_PROTOCOL`"},"repo":{"kind":"string","value":"joblib/joblib"},"test_patch":{"kind":"string","value":"diff --git a/joblib/test/test_numpy_pickle.py b/joblib/test/test_numpy_pickle.py\nindex 321a428..19a5e95 100644\n--- a/joblib/test/test_numpy_pickle.py\n+++ b/joblib/test/test_numpy_pickle.py\n@@ -13,6 +13,7 @@ import warnings\n import nose\n import gzip\n import zlib\n+import pickle\n from contextlib import closing\n \n from joblib.test.common import np, with_numpy\n@@ -821,3 +822,18 @@ def test_non_contiguous_array_pickling():\n array_reloaded = numpy_pickle.load(filename)\n np.testing.assert_array_equal(array_reloaded, array)\n os.remove(filename)\n+\n+\n+@with_numpy\n+def test_pickle_highest_protocol():\n+ # ensure persistence of a numpy array is valid even when using\n+ # the pickle HIGHEST_PROTOCOL.\n+ # see https://github.com/joblib/joblib/issues/362\n+\n+ filename = env['filename'] + str(random.randint(0, 1000))\n+ test_array = np.zeros(10)\n+\n+ numpy_pickle.dump(test_array, filename, protocol=pickle.HIGHEST_PROTOCOL)\n+ array_reloaded = numpy_pickle.load(filename)\n+\n+ np.testing.assert_array_equal(array_reloaded, test_array)\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"merge_commit\",\n \"failed_lite_validators\": [],\n \"has_test_patch\": true,\n \"is_lite\": true,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 1,\n \"test_score\": 0\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"0.9"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"\",\n \"pip_packages\": [\n \"nose\",\n \"coverage\",\n \"numpy>=1.6.1\",\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.5\",\n \"reqs_path\": null,\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==22.2.0\ncertifi==2021.5.30\ncoverage==6.2\nimportlib-metadata==4.8.3\niniconfig==1.1.1\n-e git+https://github.com/joblib/joblib.git@40341615cc2600675ce7457d9128fb030f6f89fa#egg=joblib\nnose==1.3.7\nnumpy==1.19.5\npackaging==21.3\npluggy==1.0.0\npy==1.11.0\npyparsing==3.1.4\npytest==7.0.1\ntomli==1.2.3\ntyping_extensions==4.1.1\nzipp==3.6.0\n"},"environment":{"kind":"string","value":"name: joblib\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2021.5.30=py36h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.3=he6710b0_2\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=21.2.2=py36h06a4308_0\n - python=3.6.13=h12debd9_1\n - readline=8.2=h5eee18b_0\n - setuptools=58.0.4=py36h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.37.1=pyhd3eb1b0_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==22.2.0\n - coverage==6.2\n - importlib-metadata==4.8.3\n - iniconfig==1.1.1\n - nose==1.3.7\n - numpy==1.19.5\n - packaging==21.3\n - pluggy==1.0.0\n - py==1.11.0\n - pyparsing==3.1.4\n - pytest==7.0.1\n - tomli==1.2.3\n - typing-extensions==4.1.1\n - zipp==3.6.0\nprefix: /opt/conda/envs/joblib\n"},"FAIL_TO_PASS":{"kind":"list like","value":["joblib/test/test_numpy_pickle.py::test_pickle_highest_protocol"],"string":"[\n \"joblib/test/test_numpy_pickle.py::test_pickle_highest_protocol\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":["joblib/test/test_numpy_pickle.py::test_cache_size_warning","joblib/test/test_numpy_pickle.py::test_joblib_pickle_across_python_versions"],"string":"[\n \"joblib/test/test_numpy_pickle.py::test_cache_size_warning\",\n \"joblib/test/test_numpy_pickle.py::test_joblib_pickle_across_python_versions\"\n]"},"PASS_TO_PASS":{"kind":"list like","value":["joblib/test/test_numpy_pickle.py::test_value_error","joblib/test/test_numpy_pickle.py::test_compress_level_error","joblib/test/test_numpy_pickle.py::test_numpy_persistence","joblib/test/test_numpy_pickle.py::test_numpy_persistence_bufferred_array_compression","joblib/test/test_numpy_pickle.py::test_memmap_persistence","joblib/test/test_numpy_pickle.py::test_memmap_persistence_mixed_dtypes","joblib/test/test_numpy_pickle.py::test_masked_array_persistence","joblib/test/test_numpy_pickle.py::test_compress_mmap_mode_warning","joblib/test/test_numpy_pickle.py::test_compressed_pickle_dump_and_load","joblib/test/test_numpy_pickle.py::test_compress_tuple_argument","joblib/test/test_numpy_pickle.py::test_joblib_compression_formats","joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files","joblib/test/test_numpy_pickle.py::test_compression_using_file_extension","joblib/test/test_numpy_pickle.py::test_binary_zlibfile","joblib/test/test_numpy_pickle.py::test_numpy_subclass","joblib/test/test_numpy_pickle.py::test_pathlib","joblib/test/test_numpy_pickle.py::test_non_contiguous_array_pickling"],"string":"[\n \"joblib/test/test_numpy_pickle.py::test_value_error\",\n \"joblib/test/test_numpy_pickle.py::test_compress_level_error\",\n \"joblib/test/test_numpy_pickle.py::test_numpy_persistence\",\n \"joblib/test/test_numpy_pickle.py::test_numpy_persistence_bufferred_array_compression\",\n \"joblib/test/test_numpy_pickle.py::test_memmap_persistence\",\n \"joblib/test/test_numpy_pickle.py::test_memmap_persistence_mixed_dtypes\",\n \"joblib/test/test_numpy_pickle.py::test_masked_array_persistence\",\n \"joblib/test/test_numpy_pickle.py::test_compress_mmap_mode_warning\",\n \"joblib/test/test_numpy_pickle.py::test_compressed_pickle_dump_and_load\",\n \"joblib/test/test_numpy_pickle.py::test_compress_tuple_argument\",\n \"joblib/test/test_numpy_pickle.py::test_joblib_compression_formats\",\n \"joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files\",\n \"joblib/test/test_numpy_pickle.py::test_compression_using_file_extension\",\n \"joblib/test/test_numpy_pickle.py::test_binary_zlibfile\",\n \"joblib/test/test_numpy_pickle.py::test_numpy_subclass\",\n \"joblib/test/test_numpy_pickle.py::test_pathlib\",\n \"joblib/test/test_numpy_pickle.py::test_non_contiguous_array_pickling\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD 3-Clause \"New\" or \"Revised\" License"},"__index_level_0__":{"kind":"number","value":595,"string":"595"}}},{"rowIdx":595,"cells":{"instance_id":{"kind":"string","value":"enthought__okonomiyaki-217"},"base_commit":{"kind":"string","value":"a23c1b4909741d649ebd22f30dc1268712e63c0f"},"created_at":{"kind":"string","value":"2016-06-24 10:22:10"},"environment_setup_commit":{"kind":"string","value":"5cbd87f7c349f999ac8d53fec18e44f5656bf5eb"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/okonomiyaki/file_formats/_egg_info.py b/okonomiyaki/file_formats/_egg_info.py\nindex ddc2e2f..afc373c 100644\n--- a/okonomiyaki/file_formats/_egg_info.py\n+++ b/okonomiyaki/file_formats/_egg_info.py\n@@ -663,6 +663,18 @@ def _normalized_info_from_string(spec_depend_string, epd_platform=None,\n return data, epd_platform\n \n \n+_JSON_METADATA_VERSION = \"metadata_version\"\n+_JSON__RAW_NAME = \"_raw_name\"\n+_JSON_VERSION = \"version\"\n+_JSON_EPD_PLATFORM = \"epd_platform\"\n+_JSON_PYTHON_TAG = \"python_tag\"\n+_JSON_ABI_TAG = \"abi_tag\"\n+_JSON_PLATFORM_TAG = \"platform_tag\"\n+_JSON_PLATFORM_ABI_TAG = \"platform_abi_tag\"\n+_JSON_RUNTIME_DEPENDENCIES = \"runtime_dependencies\"\n+_JSON_SUMMARY = \"summary\"\n+\n+\n class EggMetadata(object):\n \"\"\" Enthought egg metadata for format 1.x.\n \"\"\"\n@@ -707,6 +719,32 @@ class EggMetadata(object):\n sha256 = compute_sha256(path_or_file.fp)\n return cls._from_egg(path_or_file, sha256, strict)\n \n+ @classmethod\n+ def from_json_dict(cls, json_dict, pkg_info):\n+ version = EnpkgVersion.from_string(json_dict[_JSON_VERSION])\n+\n+ if json_dict[_JSON_PYTHON_TAG] is not None:\n+ python = PythonImplementation.from_string(json_dict[_JSON_PYTHON_TAG])\n+ else:\n+ python = None\n+\n+ if json_dict[_JSON_EPD_PLATFORM] is None:\n+ epd_platform = None\n+ else:\n+ epd_platform = EPDPlatform.from_epd_string(json_dict[_JSON_EPD_PLATFORM])\n+\n+ dependencies = Dependencies(tuple(json_dict[_JSON_RUNTIME_DEPENDENCIES]))\n+ metadata_version = MetadataVersion.from_string(\n+ json_dict[_JSON_METADATA_VERSION]\n+ )\n+\n+ return cls(\n+ json_dict[_JSON__RAW_NAME], version, epd_platform, python,\n+ json_dict[_JSON_ABI_TAG], json_dict[_JSON_PLATFORM_ABI_TAG],\n+ dependencies, pkg_info, json_dict[_JSON_SUMMARY],\n+ metadata_version=metadata_version\n+ )\n+\n @classmethod\n def _from_egg(cls, path_or_file, sha256, strict=True):\n def _read_summary(fp):\n@@ -1015,6 +1053,27 @@ class EggMetadata(object):\n if self.pkg_info:\n self.pkg_info._dump_as_zip(zp)\n \n+ def to_json_dict(self):\n+ if self.platform is None:\n+ epd_platform = None\n+ else:\n+ epd_platform = six.text_type(self.platform)\n+\n+ return {\n+ _JSON_METADATA_VERSION: six.text_type(self.metadata_version),\n+ _JSON__RAW_NAME: self._raw_name,\n+ _JSON_VERSION: six.text_type(self.version),\n+ _JSON_EPD_PLATFORM: epd_platform,\n+ _JSON_PYTHON_TAG: self.python_tag,\n+ _JSON_ABI_TAG: self.abi_tag,\n+ _JSON_PLATFORM_TAG: self.platform_tag,\n+ _JSON_PLATFORM_ABI_TAG: self.platform_abi_tag,\n+ _JSON_RUNTIME_DEPENDENCIES: [\n+ six.text_type(p) for p in self.runtime_dependencies\n+ ],\n+ _JSON_SUMMARY: self.summary,\n+ }\n+\n # Protocol implementations\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n"},"problem_statement":{"kind":"string","value":"Move EggMetadata json serialization from edm \nSee enthought/edm#719"},"repo":{"kind":"string","value":"enthought/okonomiyaki"},"test_patch":{"kind":"string","value":"diff --git a/okonomiyaki/file_formats/tests/test__egg_info.py b/okonomiyaki/file_formats/tests/test__egg_info.py\nindex 80dd58b..b658c36 100644\n--- a/okonomiyaki/file_formats/tests/test__egg_info.py\n+++ b/okonomiyaki/file_formats/tests/test__egg_info.py\n@@ -17,7 +17,9 @@ from ...errors import (\n InvalidEggName, InvalidMetadata, InvalidMetadataField, MissingMetadata,\n UnsupportedMetadata)\n from ...utils import tempdir\n-from ...utils.test_data import NOSE_1_3_4_OSX_X86_64\n+from ...utils.test_data import (\n+ MKL_10_3_RH5_X86_64, NOSE_1_3_4_OSX_X86_64, NOSE_1_3_4_RH5_X86_64\n+)\n from ...platforms import EPDPlatform, PlatformABI, PythonImplementation\n from ...platforms.legacy import LegacyEPDPlatform\n from ...versions import EnpkgVersion, MetadataVersion, RuntimeVersion\n@@ -1552,3 +1554,68 @@ class TestEggMetadata(unittest.TestCase):\n # Then\n metadata = EggMetadata.from_egg(path)\n self.assertEqual(metadata.platform_tag, \"win32\")\n+\n+ def test_to_json_dict(self):\n+ # Given\n+ egg = NOSE_1_3_4_RH5_X86_64\n+ metadata = EggMetadata.from_egg(egg)\n+\n+ r_json_dict = {\n+ \"metadata_version\": u\"1.3\",\n+ \"_raw_name\": u\"nose\",\n+ \"version\": u\"1.3.4-1\",\n+ \"epd_platform\": u\"rh5_x86_64\",\n+ \"python_tag\": u\"cp27\",\n+ \"abi_tag\": u\"cp27m\",\n+ \"platform_tag\": u\"linux_x86_64\",\n+ \"platform_abi_tag\": u\"gnu\",\n+ \"runtime_dependencies\": [],\n+ \"summary\": (\n+ u\"Extends the Python Unittest module with additional \"\n+ \"disocvery and running\\noptions\\n\"\n+ )\n+ }\n+\n+ # When\n+ json_dict = metadata.to_json_dict()\n+\n+ # Then\n+ self.assertEqual(json_dict, r_json_dict)\n+\n+ def test_from_json_dict(self):\n+ # Given\n+ egg = NOSE_1_3_4_RH5_X86_64\n+ r_metadata = EggMetadata.from_egg(egg)\n+\n+ json_dict = {\n+ \"metadata_version\": u\"1.3\",\n+ \"_raw_name\": u\"nose\",\n+ \"version\": u\"1.3.4-1\",\n+ \"epd_platform\": u\"rh5_x86_64\",\n+ \"python_tag\": u\"cp27\",\n+ \"abi_tag\": u\"cp27m\",\n+ \"platform_tag\": u\"linux_x86_64\",\n+ \"platform_abi_tag\": u\"gnu\",\n+ \"runtime_dependencies\": [],\n+ \"summary\": (\n+ u\"Extends the Python Unittest module with additional \"\n+ \"disocvery and running\\noptions\\n\"\n+ )\n+ }\n+\n+ # When\n+ metadata = EggMetadata.from_json_dict(json_dict, r_metadata.pkg_info)\n+\n+ # Then\n+ self.assertEqual(metadata, r_metadata)\n+\n+ def _test_roundtrip(self, egg):\n+ r_metadata = EggMetadata.from_egg(egg)\n+ metadata = EggMetadata.from_json_dict(\n+ r_metadata.to_json_dict(), r_metadata.pkg_info\n+ )\n+\n+ self.assertEqual(metadata, r_metadata)\n+\n+ def test_mkl_roundtrip(self):\n+ self._test_roundtrip(MKL_10_3_RH5_X86_64)\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 3,\n \"issue_text_score\": 3,\n \"test_score\": 3\n },\n \"num_modified_files\": 1\n}"},"version":{"kind":"string","value":"0.15"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"dev_requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"attrs==25.3.0\ncoverage==7.8.0\ndocutils==0.21.2\nenum34==1.1.10\nexceptiongroup==1.2.2\nflake8==7.2.0\nhaas==0.9.0\niniconfig==2.1.0\njsonschema==4.23.0\njsonschema-specifications==2024.10.1\nmccabe==0.7.0\nmock==1.0.1\n-e git+https://github.com/enthought/okonomiyaki.git@a23c1b4909741d649ebd22f30dc1268712e63c0f#egg=okonomiyaki\npackaging==24.2\npbr==6.1.1\npluggy==1.5.0\npycodestyle==2.13.0\npyflakes==3.3.2\npytest==8.3.5\nreferencing==0.36.2\nrpds-py==0.24.0\nsix==1.17.0\nstatistics==1.0.3.5\nstevedore==4.1.1\ntestfixtures==8.3.0\ntomli==2.2.1\ntyping_extensions==4.13.0\nzipfile2==0.0.12\n"},"environment":{"kind":"string","value":"name: okonomiyaki\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - attrs==25.3.0\n - coverage==7.8.0\n - docutils==0.21.2\n - enum34==1.1.10\n - exceptiongroup==1.2.2\n - flake8==7.2.0\n - haas==0.9.0\n - iniconfig==2.1.0\n - jsonschema==4.23.0\n - jsonschema-specifications==2024.10.1\n - mccabe==0.7.0\n - mock==1.0.1\n - packaging==24.2\n - pbr==6.1.1\n - pluggy==1.5.0\n - pycodestyle==2.13.0\n - pyflakes==3.3.2\n - pytest==8.3.5\n - referencing==0.36.2\n - rpds-py==0.24.0\n - six==1.17.0\n - statistics==1.0.3.5\n - stevedore==4.1.1\n - testfixtures==8.3.0\n - tomli==2.2.1\n - typing-extensions==4.13.0\n - zipfile2==0.0.12\nprefix: /opt/conda/envs/okonomiyaki\n"},"FAIL_TO_PASS":{"kind":"list like","value":["okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_json_dict","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_mkl_roundtrip","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_to_json_dict"],"string":"[\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_json_dict\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_mkl_roundtrip\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_to_json_dict\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_from_spec_string","okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_from_string","okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_str","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_blacklisted_platform","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_create_from_egg1","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_create_from_egg2","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_error_python_to_python_tag","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_format_1_3","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_format_1_4","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_from_string","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_missing_spec_depend","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_to_string","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_unsupported_metadata_version","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_windows_platform","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_extension_python_egg","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_no_python_egg","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_pure_python_egg","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_pure_python_egg_pypi","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_to_string","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_all_none","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_rh5_32","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_rh5_64","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_win_32","okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_win_64","okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_no_platform","okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_no_python_implementation","okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_27","okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_34","okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_35","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggName::test_split_egg_name","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggName::test_split_egg_name_invalid","okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_invalid_spec_strings","okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_1_1","okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_1_2","okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_unsupported","okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_with_dependencies","okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_with_none","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_pkg_info","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_platform","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_python_tag","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_blacklisted","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_blacklisted_platform","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_simple","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_fixed_requirement","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_cross_platform_egg","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_platform_egg","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_no_pkg_info","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_platform_abi","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_platform_abi_no_python","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_simple","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_simple_non_python_egg","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_strictness","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_support_higher_compatible_version","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_support_lower_compatible_version","okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_to_spec_string"],"string":"[\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_from_spec_string\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_from_string\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_str\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_blacklisted_platform\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_create_from_egg1\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_create_from_egg2\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_error_python_to_python_tag\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_format_1_3\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_format_1_4\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_from_string\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_missing_spec_depend\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_to_string\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_unsupported_metadata_version\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_windows_platform\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_extension_python_egg\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_no_python_egg\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_pure_python_egg\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_pure_python_egg_pypi\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_to_string\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_all_none\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_rh5_32\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_rh5_64\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_win_32\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_win_64\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_no_platform\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_no_python_implementation\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_27\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_34\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_35\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggName::test_split_egg_name\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggName::test_split_egg_name_invalid\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_invalid_spec_strings\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_1_1\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_1_2\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_unsupported\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_with_dependencies\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_with_none\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_pkg_info\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_platform\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_python_tag\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_blacklisted\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_blacklisted_platform\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_simple\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_fixed_requirement\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_cross_platform_egg\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_platform_egg\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_no_pkg_info\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_platform_abi\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_platform_abi_no_python\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_simple\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_simple_non_python_egg\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_strictness\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_support_higher_compatible_version\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_support_lower_compatible_version\",\n \"okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_to_spec_string\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD License"},"__index_level_0__":{"kind":"number","value":596,"string":"596"}}},{"rowIdx":596,"cells":{"instance_id":{"kind":"string","value":"ifosch__accloudtant-88"},"base_commit":{"kind":"string","value":"79e3cf915208ffd58a63412ffc87bd48f8bfb2dd"},"created_at":{"kind":"string","value":"2016-06-24 12:10:46"},"environment_setup_commit":{"kind":"string","value":"33f90ff0bc1639c9fe793afd837eee80170caf3e"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py\nindex d83c3dc..f360c03 100644\n--- a/accloudtant/aws/instance.py\n+++ b/accloudtant/aws/instance.py\n@@ -28,6 +28,9 @@ class Instance(object):\n 'best': 0.0,\n }\n \n+ def __repr__(self):\n+ return \"\".format(self.id)\n+\n @property\n def current(self):\n return self._prices['current']\ndiff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py\nindex 0bbbeb9..e8f2fc9 100644\n--- a/accloudtant/aws/reports.py\n+++ b/accloudtant/aws/reports.py\n@@ -25,9 +25,26 @@ class Reports(object):\n def __init__(self):\n ec2 = boto3.resource('ec2')\n ec2_client = boto3.client('ec2')\n+ instances_filters = [{\n+ 'Name': 'instance-state-name',\n+ 'Values': ['running', ],\n+ }, ]\n+ reserved_instances_filters = [{\n+ 'Name': 'state',\n+ 'Values': ['active', ],\n+ }, ]\n try:\n- self.instances = [Instance(i) for i in ec2.instances.all()]\n- self.reserved_instances = ec2_client.describe_reserved_instances()\n+ self.instances = [\n+ Instance(i)\n+ for i in ec2.instances.filter(Filters=instances_filters)\n+ ]\n+ # self.instances = [Instance(i) for i in ec2.instances.all()]\n+ self.reserved_instances = ec2_client.\\\n+ describe_reserved_instances(\n+ Filters=reserved_instances_filters\n+ )\n+ # self.reserved_instances = ec2_client\n+ # .describe_reserved_instances()\n except exceptions.NoCredentialsError:\n print(\"Error: no AWS credentials found\", file=sys.stderr)\n sys.exit(1)\n"},"problem_statement":{"kind":"string","value":"Iterate over appropriate subsets for performance improvement\nWhen generating reports, the code iterates over all instances, and all reserved instances, to get the links between these, the report should iterate over running instances and active reserved instances, only."},"repo":{"kind":"string","value":"ifosch/accloudtant"},"test_patch":{"kind":"string","value":"diff --git a/tests/aws/conftest.py b/tests/aws/conftest.py\nindex 0594830..5a97b58 100644\n--- a/tests/aws/conftest.py\n+++ b/tests/aws/conftest.py\n@@ -65,6 +65,14 @@ def ec2_resource():\n for instance in self.instances:\n yield MockEC2Instance(instance)\n \n+ def filter(self, Filters=None):\n+ if Filters is None:\n+ self.all()\n+ if Filters[0]['Name'] == 'instance-state-name':\n+ for instance in self.instances:\n+ if instance['state']['Name'] in Filters[0]['Values']:\n+ yield MockEC2Instance(instance)\n+\n class MockEC2Resource(object):\n def __init__(self, responses):\n self.responses = responses\n@@ -94,7 +102,19 @@ def ec2_client():\n def describe_instances(self):\n return self.instances\n \n- def describe_reserved_instances(self):\n+ def describe_reserved_instances(self, Filters=None):\n+ final_reserved = {'ReservedInstances': []}\n+ if Filters is None:\n+ final_reserved = self.reserved\n+ else:\n+ filter = Filters[0]\n+ if filter['Name'] == 'state':\n+ final_reserved['ReservedInstances'] = [\n+ reserved_instance\n+ for reserved_instance\n+ in self.reserved['ReservedInstances']\n+ if reserved_instance['State'] not in filter['Values']\n+ ]\n return self.reserved\n \n class MockEC2ClientCall(object):\ndiff --git a/tests/aws/report_running_expected.txt b/tests/aws/report_running_expected.txt\nnew file mode 100644\nindex 0000000..befecd0\n--- /dev/null\n+++ b/tests/aws/report_running_expected.txt\n@@ -0,0 +1,8 @@\n+Id Name Type AZ OS State Launch time Reserved Current hourly price Renewed hourly price\n+---------- --------- ---------- ---------- ------------------------ ------- ------------------- ---------- ---------------------- ----------------------\n+i-912a4392 web1 c3.8xlarge us-east-1c Windows running 2015-10-22 14:15:10 Yes 0.5121 0.3894\n+i-1840273e app1 r2.8xlarge us-east-1b Red Hat Enterprise Linux running 2015-10-22 14:15:10 Yes 0.3894 0.3794\n+i-9840273d app2 r2.8xlarge us-east-1c SUSE Linux running 2015-10-22 14:15:10 Yes 0.5225 0.389\n+i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379\n+i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379\n+i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No 0.767 0.3892\ndiff --git a/tests/aws/test_reports.py b/tests/aws/test_reports.py\nindex 35fd236..d0f6793 100644\n--- a/tests/aws/test_reports.py\n+++ b/tests/aws/test_reports.py\n@@ -17,6 +17,10 @@ from dateutil.tz import tzutc\n import accloudtant.aws.reports\n \n \n+def get_future_date(years=1):\n+ return datetime.datetime.now() + datetime.timedelta(years)\n+\n+\n def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n instances = {\n 'instances': [{\n@@ -232,16 +236,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- 494000,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320',\n@@ -266,16 +261,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- 494000,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233321',\n@@ -300,15 +286,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233322',\n@@ -333,15 +311,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n tzinfo=tzutc()\n ),\n 'RecurringCharges': [],\n- 'End': datetime.datetime(\n- 2016,\n- 6,\n- 5,\n- 6,\n- 20,\n- 10,\n- tzinfo=tzutc()\n- ),\n+ 'End': get_future_date(),\n 'CurrencyCode': 'USD',\n 'OfferingType': 'Medium Utilization',\n 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320',\n@@ -421,7 +391,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n },\n },\n },\n- 'od': '0.767',\n+ 'od': '0.867',\n 'memoryGiB': '15',\n 'vCPU': '8',\n },\n@@ -618,7 +588,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n 'best': 0.3892,\n },\n }\n- expected = open('tests/aws/report_expected.txt', 'r').read()\n+ expected = open('tests/aws/report_running_expected.txt', 'r').read()\n \n monkeypatch.setattr('boto3.resource', ec2_resource)\n ec2_resource.set_responses(instances)\n@@ -634,6 +604,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n print(reports)\n out, err = capsys.readouterr()\n \n+ assert(len(reports.instances) == 6)\n for mock in instances['instances']:\n mock['current'] = instances_prices[mock['id']]['current']\n mock['best'] = instances_prices[mock['id']]['best']\n@@ -641,5 +612,4 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2):\n if instance.id == mock['id']:\n assert(instance.current == mock['current'])\n assert(instance.best == mock['best'])\n- print(out)\n assert(out == expected)\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_many_modified_files\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 2,\n \"test_score\": 0\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"0.1"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"-e git+https://github.com/ifosch/accloudtant.git@79e3cf915208ffd58a63412ffc87bd48f8bfb2dd#egg=accloudtant\nboto3==1.1.4\nbotocore==1.2.10\nclick==4.1\ndocutils==0.21.2\nexceptiongroup==1.2.2\nfutures==2.2.0\niniconfig==2.1.0\njmespath==0.10.0\npackaging==24.2\npluggy==1.5.0\npytest==8.3.5\npython-dateutil==2.9.0.post0\nrequests==2.8.1\nsix==1.17.0\ntabulate==0.7.5\ntomli==2.2.1\n"},"environment":{"kind":"string","value":"name: accloudtant\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - boto3==1.1.4\n - botocore==1.2.10\n - click==4.1\n - docutils==0.21.2\n - exceptiongroup==1.2.2\n - futures==2.2.0\n - iniconfig==2.1.0\n - jmespath==0.10.0\n - packaging==24.2\n - pluggy==1.5.0\n - pytest==8.3.5\n - python-dateutil==2.9.0.post0\n - requests==2.8.1\n - six==1.17.0\n - tabulate==0.7.5\n - tomli==2.2.1\nprefix: /opt/conda/envs/accloudtant\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/aws/test_reports.py::test_reports"],"string":"[\n \"tests/aws/test_reports.py::test_reports\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"null"},"__index_level_0__":{"kind":"number","value":597,"string":"597"}}},{"rowIdx":597,"cells":{"instance_id":{"kind":"string","value":"ifosch__accloudtant-90"},"base_commit":{"kind":"string","value":"96ca7fbc89be0344db1af0ec2bc9fdecff6380eb"},"created_at":{"kind":"string","value":"2016-06-24 19:51:52"},"environment_setup_commit":{"kind":"string","value":"33f90ff0bc1639c9fe793afd837eee80170caf3e"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py\nindex f360c03..02ca135 100644\n--- a/accloudtant/aws/instance.py\n+++ b/accloudtant/aws/instance.py\n@@ -94,11 +94,11 @@ class Instance(object):\n def match_reserved_instance(self, reserved):\n return not (\n self.state != 'running' or\n- reserved['State'] != 'active' or\n- reserved['InstancesLeft'] == 0 or\n- reserved['ProductDescription'] != self.operating_system or\n- reserved['InstanceType'] != self.size or\n- reserved['AvailabilityZone'] != self.availability_zone\n+ reserved.state != 'active' or\n+ reserved.instances_left == 0 or\n+ reserved.product_description != self.operating_system or\n+ reserved.instance_type != self.size or\n+ reserved.az != self.availability_zone\n )\n \n \ndiff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py\nindex e8f2fc9..bcfe9c0 100644\n--- a/accloudtant/aws/reports.py\n+++ b/accloudtant/aws/reports.py\n@@ -17,6 +17,7 @@ import boto3\n from botocore import exceptions\n from tabulate import tabulate\n from accloudtant.aws.instance import Instance\n+from accloudtant.aws.reserved_instance import ReservedInstance\n from accloudtant.aws.prices import Prices\n import sys\n \n@@ -39,10 +40,12 @@ class Reports(object):\n for i in ec2.instances.filter(Filters=instances_filters)\n ]\n # self.instances = [Instance(i) for i in ec2.instances.all()]\n- self.reserved_instances = ec2_client.\\\n- describe_reserved_instances(\n+ self.reserved_instances = [\n+ ReservedInstance(i)\n+ for i in ec2_client.describe_reserved_instances(\n Filters=reserved_instances_filters\n- )\n+ )['ReservedInstances']\n+ ]\n # self.reserved_instances = ec2_client\n # .describe_reserved_instances()\n except exceptions.NoCredentialsError:\n@@ -60,13 +63,11 @@ class Reports(object):\n instance.current = 0.0\n instance_all_upfront = instance_size['ri']['yrTerm3']['allUpfront']\n instance.best = float(instance_all_upfront['effectiveHourly'])\n- for reserved in self.reserved_instances['ReservedInstances']:\n- if 'InstancesLeft' not in reserved.keys():\n- reserved['InstancesLeft'] = reserved['InstanceCount']\n+ for reserved in self.reserved_instances:\n if instance.match_reserved_instance(reserved):\n instance.reserved = 'Yes'\n- instance.current = reserved['UsagePrice']\n- reserved['InstancesLeft'] -= 1\n+ instance.current = reserved.usage_price\n+ reserved.link(instance)\n break\n \n def __repr__(self):\ndiff --git a/accloudtant/aws/reserved_instance.py b/accloudtant/aws/reserved_instance.py\nnew file mode 100644\nindex 0000000..4073a20\n--- /dev/null\n+++ b/accloudtant/aws/reserved_instance.py\n@@ -0,0 +1,86 @@\n+\n+# Copyright 2015-2016 See CONTRIBUTORS.md file\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+\n+class ReservedInstance(object):\n+ def __init__(self, data):\n+ self.reserved_instance = data\n+ if data['State'] != 'active':\n+ self.instances_left = 0\n+ else:\n+ self.instances_left = self.instance_count\n+\n+ @property\n+ def id(self):\n+ return self.reserved_instance['ReservedInstancesId']\n+\n+ @property\n+ def az(self):\n+ return self.reserved_instance['AvailabilityZone']\n+\n+ @property\n+ def instance_type(self):\n+ return self.reserved_instance['InstanceType']\n+\n+ @property\n+ def product_description(self):\n+ return self.reserved_instance['ProductDescription']\n+\n+ @property\n+ def start(self):\n+ return self.reserved_instance['Start']\n+\n+ @property\n+ def end(self):\n+ return self.reserved_instance['End']\n+\n+ @property\n+ def state(self):\n+ return self.reserved_instance['State']\n+\n+ @property\n+ def duration(self):\n+ return self.reserved_instance['Duration']\n+\n+ @property\n+ def offering_type(self):\n+ return self.reserved_instance['OfferingType']\n+\n+ @property\n+ def usage_price(self):\n+ return self.reserved_instance['UsagePrice']\n+\n+ @property\n+ def fixed_price(self):\n+ return self.reserved_instance['FixedPrice']\n+\n+ @property\n+ def currency_code(self):\n+ return self.reserved_instance['CurrencyCode']\n+\n+ @property\n+ def recurring_charges(self):\n+ return self.reserved_instance['RecurringCharges']\n+\n+ @property\n+ def instance_count(self):\n+ return self.reserved_instance['InstanceCount']\n+\n+ @property\n+ def instance_tenancy(self):\n+ return self.reserved_instance['InstanceTenancy']\n+\n+ def link(self, instance):\n+ self.instances_left -= 1\n"},"problem_statement":{"kind":"string","value":"Create a Reserved Instance type/class\nReserved instances are currently simple dictionaries. Implementing these as objects might help to use them."},"repo":{"kind":"string","value":"ifosch/accloudtant"},"test_patch":{"kind":"string","value":"diff --git a/tests/aws/test_instance.py b/tests/aws/test_instance.py\nindex 6f6d73c..fae2e82 100644\n--- a/tests/aws/test_instance.py\n+++ b/tests/aws/test_instance.py\n@@ -16,6 +16,7 @@ import datetime\n import pytest\n from dateutil.tz import tzutc\n import accloudtant.aws.instance\n+from accloudtant.aws.reserved_instance import ReservedInstance\n from conftest import MockEC2Instance\n \n \n@@ -261,7 +262,7 @@ def test_match_reserved_instance(benchmark):\n ),\n 'console_output': {'Output': 'RHEL Linux', },\n }\n- reserved_instance = {\n+ ri_data = {\n 'ProductDescription': 'Red Hat Enterprise Linux',\n 'InstanceTenancy': 'default',\n 'InstanceCount': 1,\n@@ -298,31 +299,36 @@ def test_match_reserved_instance(benchmark):\n \n ec2_instance = MockEC2Instance(instance_data)\n instance = accloudtant.aws.instance.Instance(ec2_instance)\n- reserved_instance['InstancesLeft'] = reserved_instance['InstanceCount']\n+ reserved_instance = ReservedInstance(ri_data)\n \n assert(instance.match_reserved_instance(reserved_instance))\n benchmark(instance.match_reserved_instance, reserved_instance)\n \n- reserved_instance['State'] = 'pending'\n+ ri_data['State'] = 'pending'\n+ reserved_instance = ReservedInstance(ri_data)\n \n assert(not instance.match_reserved_instance(reserved_instance))\n \n- reserved_instance['State'] = 'active'\n- reserved_instance['InstancesLeft'] = 0\n+ ri_data['State'] = 'active'\n+ reserved_instance = ReservedInstance(ri_data)\n+ reserved_instance.instances_left = 0\n \n assert(not instance.match_reserved_instance(reserved_instance))\n \n- reserved_instance['InstacesLeft'] = 1\n- reserved_instance['ProductDescription'] = 'Windows'\n+ ri_data['ProductDescription'] = 'Windows'\n+ reserved_instance = ReservedInstance(ri_data)\n+ reserved_instance.instances_left = 1\n \n assert(not instance.match_reserved_instance(reserved_instance))\n \n- reserved_instance['ProductionDescription'] = 'Red Hat Enterprise Linux'\n- reserved_instance['InstaceType'] = 't1.micro'\n+ ri_data['ProductionDescription'] = 'Red Hat Enterprise Linux'\n+ ri_data['InstaceType'] = 't1.micro'\n+ reserved_instance = ReservedInstance(ri_data)\n \n assert(not instance.match_reserved_instance(reserved_instance))\n \n- reserved_instance['InstaceType'] = 'r2.8xlarge'\n- reserved_instance['AvailabilityZone'] = 'us-east-1c'\n+ ri_data['InstaceType'] = 'r2.8xlarge'\n+ ri_data['AvailabilityZone'] = 'us-east-1c'\n+ reserved_instance = ReservedInstance(ri_data)\n \n assert(not instance.match_reserved_instance(reserved_instance))\ndiff --git a/tests/aws/test_reserved_instance.py b/tests/aws/test_reserved_instance.py\nnew file mode 100644\nindex 0000000..9627ebf\n--- /dev/null\n+++ b/tests/aws/test_reserved_instance.py\n@@ -0,0 +1,189 @@\n+# Copyright 2015-2016 See CONTRIBUTORS.md file\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import datetime\n+import pytest\n+from dateutil.tz import tzutc\n+import accloudtant.aws.reserved_instance\n+from conftest import MockEC2Instance\n+from test_reports import get_future_date\n+\n+\n+def test_retired_ri():\n+ az = 'us-east-1b'\n+ ri_data = {\n+ 'ProductDescription': 'Linux/UNIX',\n+ 'InstanceTenancy': 'default',\n+ 'InstanceCount': 29,\n+ 'InstanceType': 'm1.large',\n+ 'Start': datetime.datetime(\n+ 2011,\n+ 6,\n+ 5,\n+ 6,\n+ 20,\n+ 10,\n+ 494000,\n+ tzinfo=tzutc()\n+ ),\n+ 'RecurringCharges': [],\n+ 'End': datetime.datetime(\n+ 2011,\n+ 6,\n+ 5,\n+ 6,\n+ 20,\n+ 10,\n+ tzinfo=tzutc()\n+ ),\n+ 'CurrencyCode': 'USD',\n+ 'OfferingType': 'Medium Utilization',\n+ 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df1223331f',\n+ 'FixedPrice': 910.0,\n+ 'AvailabilityZone': az,\n+ 'UsagePrice': 0.12,\n+ 'Duration': 31536000,\n+ 'State': 'retired',\n+ }\n+\n+ ri = accloudtant.aws.reserved_instance.ReservedInstance(ri_data)\n+\n+ assert(ri.id == ri_data['ReservedInstancesId'])\n+ assert(ri.product_description == ri_data['ProductDescription'])\n+ assert(ri.instance_tenancy == ri_data['InstanceTenancy'])\n+ assert(ri.instance_count == ri_data['InstanceCount'])\n+ assert(ri.instance_type == ri_data['InstanceType'])\n+ assert(ri.start == ri_data['Start'])\n+ assert(ri.recurring_charges == ri_data['RecurringCharges'])\n+ assert(ri.end == ri_data['End'])\n+ assert(ri.currency_code == ri_data['CurrencyCode'])\n+ assert(ri.offering_type == ri_data['OfferingType'])\n+ assert(ri.fixed_price == ri_data['FixedPrice'])\n+ assert(ri.az == ri_data['AvailabilityZone'])\n+ assert(ri.usage_price == ri_data['UsagePrice'])\n+ assert(ri.duration == ri_data['Duration'])\n+ assert(ri.state == ri_data['State'])\n+ assert(ri.instances_left == 0)\n+\n+\n+def test_active_ri():\n+ az = 'us-east-1b'\n+ ri_data = {\n+ 'ProductDescription': 'Linux/UNIX',\n+ 'InstanceTenancy': 'default',\n+ 'InstanceCount': 1,\n+ 'InstanceType': 'm1.large',\n+ 'Start': datetime.datetime(\n+ 2011,\n+ 6,\n+ 5,\n+ 6,\n+ 20,\n+ 10,\n+ 494000,\n+ tzinfo=tzutc()\n+ ),\n+ 'RecurringCharges': [],\n+ 'End': get_future_date(),\n+ 'CurrencyCode': 'USD',\n+ 'OfferingType': 'Medium Utilization',\n+ 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df1223331f',\n+ 'FixedPrice': 910.0,\n+ 'AvailabilityZone': az,\n+ 'UsagePrice': 0.12,\n+ 'Duration': 31536000,\n+ 'State': 'active',\n+ }\n+\n+ ri = accloudtant.aws.reserved_instance.ReservedInstance(ri_data)\n+\n+ assert(ri.id == ri_data['ReservedInstancesId'])\n+ assert(ri.product_description == ri_data['ProductDescription'])\n+ assert(ri.instance_tenancy == ri_data['InstanceTenancy'])\n+ assert(ri.instance_count == ri_data['InstanceCount'])\n+ assert(ri.instance_type == ri_data['InstanceType'])\n+ assert(ri.start == ri_data['Start'])\n+ assert(ri.recurring_charges == ri_data['RecurringCharges'])\n+ assert(ri.end == ri_data['End'])\n+ assert(ri.currency_code == ri_data['CurrencyCode'])\n+ assert(ri.offering_type == ri_data['OfferingType'])\n+ assert(ri.fixed_price == ri_data['FixedPrice'])\n+ assert(ri.az == ri_data['AvailabilityZone'])\n+ assert(ri.usage_price == ri_data['UsagePrice'])\n+ assert(ri.duration == ri_data['Duration'])\n+ assert(ri.state == ri_data['State'])\n+ assert(ri.instances_left == ri_data['InstanceCount'])\n+\n+\n+def test_ri_link():\n+ az = 'us-east-1b'\n+ ri_data = {\n+ 'ProductDescription': 'Linux/UNIX',\n+ 'InstanceTenancy': 'default',\n+ 'InstanceCount': 1,\n+ 'InstanceType': 'm1.large',\n+ 'Start': datetime.datetime(\n+ 2015,\n+ 6,\n+ 5,\n+ 6,\n+ 20,\n+ 10,\n+ 494000,\n+ tzinfo=tzutc()\n+ ),\n+ 'RecurringCharges': [],\n+ 'End': get_future_date(),\n+ 'CurrencyCode': 'USD',\n+ 'OfferingType': 'Medium Utilization',\n+ 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df1223331f',\n+ 'FixedPrice': 910.0,\n+ 'AvailabilityZone': az,\n+ 'UsagePrice': 0.12,\n+ 'Duration': 31536000,\n+ 'State': 'active',\n+ }\n+ instance_data = {\n+ 'id': 'i-1840273e',\n+ 'tags': [{\n+ 'Key': 'Name',\n+ 'Value': 'app1',\n+ }, ],\n+ 'instance_type': 'm1.large',\n+ 'placement': {\n+ 'AvailabilityZone': az,\n+ },\n+ 'state': {\n+ 'Name': 'running',\n+ },\n+ 'launch_time': datetime.datetime(\n+ 2015,\n+ 10,\n+ 22,\n+ 14,\n+ 15,\n+ 10,\n+ tzinfo=tzutc()\n+ ),\n+ 'console_output': {'Output': 'Linux', },\n+ }\n+\n+ ri = accloudtant.aws.reserved_instance.ReservedInstance(ri_data)\n+ instance = MockEC2Instance(instance_data)\n+\n+ assert(ri.instances_left == 1)\n+\n+ ri.link(instance)\n+\n+ assert(ri.instances_left == 0)\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_short_problem_statement\",\n \"has_added_files\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 1,\n \"test_score\": 2\n },\n \"num_modified_files\": 2\n}"},"version":{"kind":"string","value":"0.1"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"-e git+https://github.com/ifosch/accloudtant.git@96ca7fbc89be0344db1af0ec2bc9fdecff6380eb#egg=accloudtant\nboto3==1.1.4\nbotocore==1.2.10\nclick==4.1\ndocutils==0.21.2\nexceptiongroup==1.2.2\nfutures==2.2.0\niniconfig==2.1.0\njmespath==0.10.0\npackaging==24.2\npluggy==1.5.0\npytest==8.3.5\npython-dateutil==2.9.0.post0\nrequests==2.8.1\nsix==1.17.0\ntabulate==0.7.5\ntomli==2.2.1\n"},"environment":{"kind":"string","value":"name: accloudtant\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - boto3==1.1.4\n - botocore==1.2.10\n - click==4.1\n - docutils==0.21.2\n - exceptiongroup==1.2.2\n - futures==2.2.0\n - iniconfig==2.1.0\n - jmespath==0.10.0\n - packaging==24.2\n - pluggy==1.5.0\n - pytest==8.3.5\n - python-dateutil==2.9.0.post0\n - requests==2.8.1\n - six==1.17.0\n - tabulate==0.7.5\n - tomli==2.2.1\nprefix: /opt/conda/envs/accloudtant\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/aws/test_instance.py::test_instance","tests/aws/test_instance.py::test_unnamed_instance","tests/aws/test_instance.py::test_guess_os","tests/aws/test_reserved_instance.py::test_retired_ri","tests/aws/test_reserved_instance.py::test_active_ri","tests/aws/test_reserved_instance.py::test_ri_link"],"string":"[\n \"tests/aws/test_instance.py::test_instance\",\n \"tests/aws/test_instance.py::test_unnamed_instance\",\n \"tests/aws/test_instance.py::test_guess_os\",\n \"tests/aws/test_reserved_instance.py::test_retired_ri\",\n \"tests/aws/test_reserved_instance.py::test_active_ri\",\n \"tests/aws/test_reserved_instance.py::test_ri_link\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"null"},"__index_level_0__":{"kind":"number","value":598,"string":"598"}}},{"rowIdx":598,"cells":{"instance_id":{"kind":"string","value":"sympy__sympy-11297"},"base_commit":{"kind":"string","value":"230b1bf3a3a67c0621a3b4a8f2a45e950f82393f"},"created_at":{"kind":"string","value":"2016-06-25 06:46:20"},"environment_setup_commit":{"kind":"string","value":"8bb5814067cfa0348fb8b708848f35dba2b55ff4"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/setup.py b/setup.py\nindex 097efc5f42..bee2324d13 100755\n--- a/setup.py\n+++ b/setup.py\n@@ -86,6 +86,7 @@\n 'sympy.functions.special',\n 'sympy.functions.special.benchmarks',\n 'sympy.geometry',\n+ 'sympy.holonomic',\n 'sympy.integrals',\n 'sympy.integrals.benchmarks',\n 'sympy.interactive',\n@@ -270,6 +271,7 @@ def run(self):\n 'sympy.functions.elementary.tests',\n 'sympy.functions.special.tests',\n 'sympy.geometry.tests',\n+ 'sympy.holonomic.tests',\n 'sympy.integrals.tests',\n 'sympy.interactive.tests',\n 'sympy.liealgebras.tests',\ndiff --git a/sympy/holonomic/holonomic.py b/sympy/holonomic/holonomic.py\nindex 2a2c1ef65e..3868cb4e80 100644\n--- a/sympy/holonomic/holonomic.py\n+++ b/sympy/holonomic/holonomic.py\n@@ -2,7 +2,8 @@\n \n from __future__ import print_function, division\n \n-from sympy import symbols, Symbol, diff, S, Dummy, Order, rf, meijerint, I, solve\n+from sympy import (symbols, Symbol, diff, S, Dummy, Order, rf, meijerint, I,\n+ solve, limit)\n from sympy.printing import sstr\n from .linearsolver import NewMatrix\n from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators\n@@ -323,6 +324,14 @@ def __eq__(self, other):\n else:\n return False\n \n+ def is_singular(self, x0=0):\n+ \"\"\"\n+ Checks if the differential equation is singular at x0.\n+ \"\"\"\n+\n+ domain = str(self.parent.base.domain)[0]\n+ return x0 in roots(self.listofpoly[-1].rep, filter=domain)\n+\n \n class HolonomicFunction(object):\n \"\"\"\n@@ -336,6 +345,21 @@ class HolonomicFunction(object):\n Given two Holonomic Functions f and g, their sum, product,\n integral and derivative is also a Holonomic Function.\n \n+ To plot a Holonomic Function, one can use `.evalf()` for numerical computation.\n+ Here's an example on `sin(x)**2/x` using numpy and matplotlib.\n+\n+ ``\n+ import sympy.holonomic\n+ from sympy import var, sin\n+ import matplotlib.pyplot as plt\n+ import numpy as np\n+ var(\"x\")\n+ r = np.linspace(1, 5, 100)\n+ y = sympy.holonomic.from_sympy(sin(x)**2/x, x0=1).evalf(r)\n+ plt.plot(r, y, label=\"holonomic function\")\n+ plt.show()\n+ ``\n+\n Examples\n ========\n \n@@ -482,6 +506,7 @@ def __add__(self, other):\n sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False)\n # solving initial conditions\n if self._have_init_cond and other._have_init_cond:\n+\n if self.x0 == other.x0:\n # try to extended the initial conditions\n # using the annihilator\n@@ -489,14 +514,29 @@ def __add__(self, other):\n y0_other = _extend_y0(other, sol.order)\n y0 = [a + b for a, b in zip(y0_self, y0_other)]\n return HolonomicFunction(sol, self.x, self.x0, y0)\n+\n else:\n- # initial conditions for different points\n- # to be implemented\n- pass\n+\n+ if self.x0 == 0 and not self.annihilator.is_singular() \\\n+ and not other.annihilator.is_singular():\n+ return self + other.change_ics(0)\n+\n+ elif other.x0 == 0 and not self.annihilator.is_singular() \\\n+ and not other.annihilator.is_singular():\n+ return self.change_ics(0) + other\n+\n+ else:\n+\n+ if not self.annihilator.is_singular(x0=self.x0) and \\\n+ not other.annihilator.is_singular(x0=self.x0):\n+ return self + other.change_ics(self.x0)\n+\n+ else:\n+ return self.change_ics(other.x0) + other\n \n return HolonomicFunction(sol, self.x)\n \n- def integrate(self, *args):\n+ def integrate(self, limits):\n \"\"\"\n Integrate the given holonomic function. Limits can be provided,\n Initial conditions can only be computed when limits are (x0, x).\n@@ -518,19 +558,126 @@ def integrate(self, *args):\n HolonomicFunction((1)Dx + (1)Dx**3, x), f(0) = 0, f'(0) = 1, f''(0) = 0\n \"\"\"\n \n- # just multiply by Dx from right\n+ # to get the annihilator, just multiply by Dx from right\n D = self.annihilator.parent.derivative_operator\n- if (not args) or (not self._have_init_cond):\n+\n+ # for indefinite integration\n+ if (not limits) or (not self._have_init_cond):\n return HolonomicFunction(self.annihilator * D, self.x)\n \n- # definite integral if limits are (x0, x)\n- if len(args) == 1 and len(args[0]) == 3 and args[0][1] == self.x0 and args[0][2] == self.x:\n+ # definite integral\n+ # initial conditions for the answer will be stored at point `a`,\n+ # where `a` is the lower limit of the integrand\n+ if hasattr(limits, \"__iter__\"):\n+\n+ if len(limits) == 3 and limits[0] == self.x:\n+ x0 = self.x0\n+ a = limits[1]\n+ b = limits[2]\n+\n+ else:\n+ x0 = self.x0\n+ a = self.x0\n+ b = self.x\n+\n+ if x0 == a:\n y0 = [S(0)]\n y0 += self.y0\n- return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)\n+\n+ # use evalf to get the values at `a`\n+ else:\n+ y0 = [S(0)]\n+ tempy0 = self.evalf(a, derivatives=True)\n+ y0 += tempy0\n+\n+ # if the upper limit is `x`, the answer will be a function\n+ if b == self.x:\n+ return HolonomicFunction(self.annihilator * D, self.x, a, y0)\n+\n+ # if the upper limits is a Number, a numerical value will be returned\n+ elif S(b).is_Number:\n+ return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b)\n \n return HolonomicFunction(self.annihilator * D, self.x)\n \n+ def diff(self, *args):\n+ \"\"\"\n+ Differentiation of the given Holonomic function.\n+\n+ Examples\n+ ========\n+\n+ >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators\n+ >>> from sympy.polys.domains import ZZ, QQ\n+ >>> from sympy import symbols\n+ >>> x = symbols('x')\n+ >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')\n+\n+ # derivative of sin(x)\n+ >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_sympy()\n+ cos(x)\n+\n+ # derivative of e^2*x\n+ >>> HolonomicFunction(Dx - 2, x, 0, 1).diff().to_sympy()\n+ 2*exp(2*x)\n+\n+ See Also\n+ =======\n+\n+ .integrate()\n+ \"\"\"\n+\n+ if args:\n+ if args[0] != self.x:\n+ return S(0)\n+ elif len(args) == 2:\n+ sol = self\n+ for i in range(args[1]):\n+ sol = sol.diff(args[0])\n+ return sol\n+\n+ ann = self.annihilator\n+ dx = ann.parent.derivative_operator\n+\n+ # if the function is constant.\n+ if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1:\n+ return S(0)\n+\n+ # if the coefficient of y in the differential equation is zero.\n+ # a shifting is done to compute the answer in this case.\n+ elif ann.listofpoly[0] == ann.parent.base.zero:\n+\n+ sol = DifferentialOperator(ann.listofpoly[1:], ann.parent)\n+\n+ if self._have_init_cond:\n+ return HolonomicFunction(sol, self.x, self.x0, self.y0[1:])\n+\n+ else:\n+ return HolonomicFunction(sol, self.x)\n+\n+ # the general algorithm\n+ R = ann.parent.base\n+ K = R.get_field()\n+\n+ seq_dmf = [K.new(i.rep) for i in ann.listofpoly]\n+\n+ # -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0\n+ rhs = [i / seq_dmf[0] for i in seq_dmf[1:]]\n+ rhs.insert(0, K.zero)\n+\n+ # differentiate both lhs and rhs\n+ sol = _derivate_diff_eq(rhs)\n+\n+ # add the term y' in lhs to rhs\n+ sol = _add_lists(sol, [K.zero, K.one])\n+\n+ sol = _normalize(sol[1:], self.annihilator.parent, negative=False)\n+\n+ if not self._have_init_cond:\n+ return HolonomicFunction(sol, self.x)\n+\n+ y0 = _extend_y0(self, sol.order + 1)[1:]\n+ return HolonomicFunction(sol, self.x, self.x0, y0)\n \n def __eq__(self, other):\n if self.annihilator == other.annihilator:\n@@ -635,6 +782,8 @@ def __mul__(self, other):\n sol_ann = _normalize(sol[0][0:], self.annihilator.parent, negative=False)\n \n if self._have_init_cond and other._have_init_cond:\n+\n+ # if both the conditions are at same point\n if self.x0 == other.x0:\n \n # try to find more inital conditions\n@@ -657,9 +806,28 @@ def __mul__(self, other):\n sol += coeff[j][k]* y0_self[j] * y0_other[k]\n \n y0.append(sol)\n+\n return HolonomicFunction(sol_ann, self.x, self.x0, y0)\n+\n+ # if the points are different, consider one\n else:\n- raise NotImplementedError\n+\n+ if self.x0 == 0 and not ann_self.is_singular() \\\n+ and not ann_other.is_singular():\n+ return self * other.change_ics(0)\n+\n+ elif other.x0 == 0 and not ann_self.is_singular() \\\n+ and not ann_other.is_singular():\n+ return self.change_ics(0) * other\n+\n+ else:\n+\n+ if not ann_self.is_singular(x0=self.x0) and \\\n+ not ann_other.is_singular(x0=self.x0):\n+ return self * other.change_ics(self.x0)\n+\n+ else:\n+ return self.change_ics(other.x0) * other\n \n return HolonomicFunction(sol_ann, self.x)\n \n@@ -770,10 +938,15 @@ def composition(self, expr, *args):\n def to_sequence(self, lb=True):\n \"\"\"\n Finds the recurrence relation in power series expansion\n- of the function.\n+ of the function about origin.\n+\n+ Returns a tuple (R, n0), with R being the Recurrence relation\n+ and a non-negative integer `n0` such that the recurrence relation\n+ holds for all n >= n0.\n \n- Returns a tuple of the recurrence relation and a value `n0` such that\n- the recurrence relation holds for all n >= n0.\n+ If it's not possible to numerically compute a initial condition,\n+ it is returned as a symbol C_j, denoting the coefficient of x^j\n+ in the power series about origin.\n \n Examples\n ========\n@@ -858,12 +1031,6 @@ def to_sequence(self, lb=True):\n # the recurrence relation\n sol = RecurrenceOperator(sol, R)\n \n- if not self._have_init_cond or self.x0 != 0:\n- if lb:\n- return (HolonomicSequence(sol), smallest_n)\n- else:\n- return HolonomicSequence(sol)\n-\n # computing the initial conditions for recurrence\n order = sol.order\n all_roots = roots(sol.listofpoly[-1].rep, filter='Z')\n@@ -884,34 +1051,61 @@ def to_sequence(self, lb=True):\n \n # if sufficient conditions can't be computed then\n # try to use the series method i.e.\n- # equate the coefficients of x^k in series to zero.\n+ # equate the coefficients of x^k in the equation formed by\n+ # substituting the series in differential equation, to zero.\n if len(u0) < order:\n \n for i in range(degree):\n eq = S(0)\n \n for j in dict1:\n- if i + j[0] < len(u0):\n+\n+ if i + j[0] < 0:\n+ dummys[i + j[0]] = S(0)\n+\n+ elif i + j[0] < len(u0):\n dummys[i + j[0]] = u0[i + j[0]]\n \n elif not i + j[0] in dummys:\n- dummys[i + j[0]] = Dummy('x_%s' %(i + j[0]))\n+ dummys[i + j[0]] = Symbol('C_%s' %(i + j[0]))\n \n if j[1] <= i:\n eq += dict1[j].subs(n, i) * dummys[i + j[0]]\n \n eqs.append(eq)\n \n+ # solve the system of equations formed\n soleqs = solve(eqs)\n \n+ if isinstance(soleqs, dict):\n+\n+ for i in range(len(u0), order):\n+\n+ if i not in dummys:\n+ dummys[i] = Symbol('C_%s' %i)\n+\n+ if dummys[i] in soleqs:\n+ u0.append(soleqs[dummys[i]])\n+\n+ else:\n+ u0.append(dummys[i])\n+\n+ if lb:\n+ return (HolonomicSequence(sol, u0), smallest_n)\n+ return HolonomicSequence(sol, u0)\n+\n for i in range(len(u0), order):\n+\n+ if i not in dummys:\n+ dummys[i] = Symbol('C_%s' %i)\n+\n s = False\n for j in soleqs:\n if dummys[i] in j:\n u0.append(j[dummys[i]])\n s = True\n if not s:\n- break\n+ u0.append(dummys[i])\n \n if lb:\n return (HolonomicSequence(sol, u0), smallest_n)\n@@ -1022,7 +1216,7 @@ def _pole_degree(poly):\n y *= x - i\n return roots(s.rep, filter='R').keys()\n \n- def evalf(self, points, method='RK4'):\n+ def evalf(self, points, method='RK4', h=0.05, derivatives=False):\n \"\"\"\n Finds numerical value of a holonomic function using numerical methods.\n (RK4 by default). A set of points (real or complex) must be provided\n@@ -1062,10 +1256,33 @@ def evalf(self, points, method='RK4'):\n \"\"\"\n \n from sympy.holonomic.numerical import _evalf\n+ lp = False\n+\n+ # if a point `b` is given instead of a mesh\n+ if not hasattr(points, \"__iter__\"):\n+ lp = True\n+ b = S(points)\n+ if self.x0 == b:\n+ return _evalf(self, [b], method=method, derivatives=derivatives)[-1]\n+\n+ if not b.is_Number:\n+ raise NotImplementedError\n+\n+ a = self.x0\n+ if a > b:\n+ h = -h\n+ n = int((b - a) / h)\n+ points = [a + h]\n+ for i in range(n - 1):\n+ points.append(points[-1] + h)\n+\n for i in roots(self.annihilator.listofpoly[-1].rep):\n if i == self.x0 or i in points:\n raise TypeError(\"Provided path contains a singularity\")\n- return _evalf(self, points, method=method)\n+\n+ if lp:\n+ return _evalf(self, points, method=method, derivatives=derivatives)[-1]\n+ return _evalf(self, points, method=method, derivatives=derivatives)\n \n def _subs(self, z):\n \"\"\"\n@@ -1123,6 +1340,18 @@ def to_hyper(self):\n # order of the recurrence relation\n m = r.order\n \n+ # when no recurrence exists, and the power series have finite terms\n+ if m == 0:\n+ nonzeroterms = roots(r.listofpoly[0].rep, filter='Z')\n+ if max(nonzeroterms) >= len(u0):\n+ raise NotImplementedError(\"Initial conditions aren't sufficient\")\n+ sol = S(0)\n+ for i in nonzeroterms:\n+ if i >= 0:\n+ sol += u0[i] * x**i\n+ return sol\n+\n+\n if smallest_n + m > len(u0):\n raise NotImplementedError(\"Can't compute sufficient Initial Conditions\")\n \n@@ -1135,7 +1364,7 @@ def to_hyper(self):\n is_hyper = False\n break\n \n- if not is_hyper or m == 0:\n+ if not is_hyper:\n raise TypeError(\"The series is not Hypergeometric\")\n \n a = r.listofpoly[0]\n@@ -1214,6 +1443,37 @@ def to_sympy(self):\n \n return hyperexpand(self.to_hyper()).simplify()\n \n+ def change_ics(self, b):\n+ \"\"\"\n+ Changes the point `x0` to `b` for initial conditions.\n+\n+ Examples\n+ ========\n+\n+ >>> from sympy.holonomic import from_sympy\n+ >>> from sympy import symbols, sin, cos, exp\n+ >>> x = symbols('x')\n+\n+ >>> from_sympy(sin(x)).change_ics(1)\n+ HolonomicFunction((1) + (1)Dx**2, x), f(1) = sin(1), f'(1) = cos(1)\n+\n+ >>> from_sympy(exp(x)).change_ics(2)\n+ HolonomicFunction((-1) + (1)Dx, x), f(2) = exp(2)\n+ \"\"\"\n+\n+ symbolic = True\n+\n+ try:\n+ sol = from_sympy(self.to_sympy(), x0=b)\n+ except:\n+ symbolic = False\n+\n+ if symbolic:\n+ return sol\n+\n+ y0 = self.evalf(b, derivatives=True)\n+ return HolonomicFunction(self.annihilator, self.x, b, y0)\n+\n \n def from_hyper(func, x0=0, evalf=False):\n \"\"\"\n@@ -1376,7 +1636,7 @@ def _find_conditions(simp, x, x0, order, evalf=False):\n from sympy.integrals.meijerint import _mytype\n \n \n-def from_sympy(func, x=None, initcond=True):\n+def from_sympy(func, x=None, initcond=True, x0=0):\n \"\"\"\n Uses `meijerint._rewrite1` to convert to `meijerg` function and then\n eventually to Holonomic Functions. Only works when `meijerint._rewrite1`\n@@ -1404,7 +1664,7 @@ def from_sympy(func, x=None, initcond=True):\n x = func.atoms(Symbol).pop()\n \n # try to convert if the function is polynomial or rational\n- solpoly = _convert_poly_rat(func, x, initcond=initcond)\n+ solpoly = _convert_poly_rat(func, x, initcond=initcond, x0=x0)\n if solpoly:\n return solpoly\n \n@@ -1425,7 +1685,6 @@ def from_sympy(func, x=None, initcond=True):\n sol = _convert_meijerint(func, x, initcond=False)\n if not sol:\n raise NotImplementedError\n- x0 = 0\n y0 = _find_conditions(func, x, x0, sol.annihilator.order)\n while not y0:\n x0 += 1\n@@ -1435,7 +1694,6 @@ def from_sympy(func, x=None, initcond=True):\n if not initcond:\n return sol.composition(func.args[0])\n \n- x0 = 0\n y0 = _find_conditions(func, x, x0, sol.annihilator.order)\n while not y0:\n x0 += 1\n@@ -1464,7 +1722,6 @@ def from_sympy(func, x=None, initcond=True):\n if not initcond:\n return sol\n \n- x0 = 0\n y0 = _find_conditions(func, x, x0, sol.annihilator.order)\n while not y0:\n x0 += 1\n@@ -1484,8 +1741,7 @@ def _normalize(list_of, parent, negative=True):\n denom = []\n base = parent.base\n K = base.get_field()\n- R = ZZ.old_poly_ring(base.gens[0])\n- lcm_denom = R.from_sympy(S(1))\n+ lcm_denom = base.from_sympy(S(1))\n list_of_coeff = []\n \n # convert polynomials to the elements of associated\n@@ -1499,15 +1755,10 @@ def _normalize(list_of, parent, negative=True):\n list_of_coeff.append(j)\n \n # corresponding numerators of the sequence of polynomials\n- num.append(base(list_of_coeff[i].num))\n+ num.append(list_of_coeff[i].numer())\n \n # corresponding denominators\n- den = list_of_coeff[i].den\n- if isinstance(den[0], PythonRational):\n- for i, j in enumerate(den):\n- den[i] = j.p\n-\n- denom.append(R(den))\n+ denom.append(list_of_coeff[i].denom())\n \n # lcm of denominators in the coefficients\n for i in denom:\n@@ -1522,7 +1773,7 @@ def _normalize(list_of, parent, negative=True):\n for i, j in enumerate(list_of_coeff):\n list_of_coeff[i] = j * lcm_denom\n \n- gcd_numer = base.from_FractionField(list_of_coeff[-1], K)\n+ gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep)\n \n # gcd of numerators in the coefficients\n for i in num:\n@@ -1532,7 +1783,8 @@ def _normalize(list_of, parent, negative=True):\n \n # divide all the coefficients by the gcd\n for i, j in enumerate(list_of_coeff):\n- list_of_coeff[i] = base.from_FractionField(j / gcd_numer, K)\n+ frac_ans = j / gcd_numer\n+ list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep)\n \n return DifferentialOperator(list_of_coeff, parent)\n \n@@ -1618,7 +1870,7 @@ def DMFdiff(frac):\n return K((sol_num.rep, sol_denom.rep))\n \n \n-def DMFsubs(frac, x0):\n+def DMFsubs(frac, x0, mpm=False):\n # substitute the point x0 in DMF object of the form p/q\n if not isinstance(frac, DMF):\n return frac\n@@ -1628,20 +1880,23 @@ def DMFsubs(frac, x0):\n sol_p = S(0)\n sol_q = S(0)\n \n+ if mpm:\n+ from mpmath import mp\n+\n for i, j in enumerate(reversed(p)):\n- if isinstance(j, PythonRational):\n- j = sympify(j)\n+ if mpm:\n+ j = sympify(j)._to_mpmath(mp.prec)\n sol_p += j * x0**i\n \n for i, j in enumerate(reversed(q)):\n- if isinstance(j, PythonRational):\n- j = sympify(j)\n+ if mpm:\n+ j = sympify(j)._to_mpmath(mp.prec)\n sol_q += j * x0**i\n \n return sol_p / sol_q\n \n \n-def _convert_poly_rat(func, x, initcond=True):\n+def _convert_poly_rat(func, x, initcond=True, x0=0):\n \"\"\"Converts Polynomials and Rationals to Holonomic.\n \"\"\"\n \n@@ -1657,6 +1912,10 @@ def _convert_poly_rat(func, x, initcond=True):\n R = QQ.old_poly_ring(x)\n _, Dx = DifferentialOperators(R, 'Dx')\n \n+ # if the function is constant\n+ if not func.has(x):\n+ return HolonomicFunction(Dx, x, 0, func)\n+\n if ispoly:\n # differential equation satisfied by polynomial\n sol = func * Dx - func.diff()\n@@ -1672,7 +1931,6 @@ def _convert_poly_rat(func, x, initcond=True):\n if not initcond:\n return HolonomicFunction(sol, x)\n \n- x0 = 0\n y0 = _find_conditions(func, x, x0, sol.order)\n while not y0:\n x0 += 1\n@@ -1771,6 +2029,8 @@ def _find_conditions(func, x, x0, order):\n y0 = []\n for i in range(order):\n val = func.subs(x, x0)\n+ if isinstance(val, NaN):\n+ val = limit(func, x, x0)\n if (val.is_finite is not None and not val.is_finite) or isinstance(val, NaN):\n return None\n y0.append(val)\ndiff --git a/sympy/holonomic/numerical.py b/sympy/holonomic/numerical.py\nindex c91b6836f5..afbcd1b242 100644\n--- a/sympy/holonomic/numerical.py\n+++ b/sympy/holonomic/numerical.py\n@@ -58,7 +58,7 @@ def _euler(red, x0, x1, y0, a):\n f_0_n = 0\n \n for i in range(a):\n- f_0_n += sympify(DMFsubs(red[i], A))._to_mpmath(mp.prec) * y_0[i]\n+ f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]\n f_0.append(f_0_n)\n \n sol = []\n@@ -85,22 +85,22 @@ def _rk4(red, x0, x1, y0, a):\n \n f_0 = y_0[1:]\n for i in range(a):\n- f_0_n += sympify(DMFsubs(red[i], A))._to_mpmath(mp.prec) * y_0[i]\n+ f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]\n f_0.append(f_0_n)\n \n f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)]\n for i in range(a):\n- f_1_n += sympify(DMFsubs(red[i], A + h/2))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2)\n+ f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2)\n f_1.append(f_1_n)\n \n f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)]\n for i in range(a):\n- f_2_n += sympify(DMFsubs(red[i], A + h/2))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2)\n+ f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2)\n f_2.append(f_2_n)\n \n f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)]\n for i in range(a):\n- f_3_n += sympify(DMFsubs(red[i], A + h))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h)\n+ f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h)\n f_3.append(f_3_n)\n \n sol = []\n"},"problem_statement":{"kind":"string","value":"Add a docstring how to plot a holonomic function\nSomething like this:\r\n```\r\nimport sympy.holonomic\r\nimport numpy as np\r\nr = np.linspace(1, 5, 100)\r\ny = sympy.holonomic.from_sympy(sin(x)**2/x).evalf(r)\r\nplot(r, y)\r\n```\r\n\r\nThis should be part of some larger docstring, or part of a tutorial for the holonomic module. Here is a jupyter notebook showing that it works:\r\n\r\nhttp://nbviewer.jupyter.org/gist/certik/849a62d23f615d89dd37585b76159e78\r\n\r\ncc @shubhamtibra ."},"repo":{"kind":"string","value":"sympy/sympy"},"test_patch":{"kind":"string","value":"diff --git a/sympy/holonomic/tests/test_holonomic.py b/sympy/holonomic/tests/test_holonomic.py\nindex d917e4c9f7..643df52114 100644\n--- a/sympy/holonomic/tests/test_holonomic.py\n+++ b/sympy/holonomic/tests/test_holonomic.py\n@@ -2,7 +2,7 @@\n DifferentialOperators, from_hyper, from_meijerg, from_sympy)\n from sympy.holonomic.recurrence import RecurrenceOperators, HolonomicSequence\n from sympy import (symbols, hyper, S, sqrt, pi, exp, erf, erfc, sstr,\n- O, I, meijerg, sin, cos, log, cosh, besselj, hyperexpand)\n+ O, I, meijerg, sin, cos, log, cosh, besselj, hyperexpand, Ci, EulerGamma, Si)\n from sympy import ZZ, QQ\n \n \n@@ -91,8 +91,8 @@ def test_addition_initial_condition():\n assert p + q == r\n p = HolonomicFunction(Dx - x + Dx**2, x, 0, [1, 2])\n q = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])\n- r = HolonomicFunction((-4*x**4 - x**3 - 4*x**2 + 1) + (4*x**3 + x**2 + 3*x + 4)*Dx + \\\n- (-6*x + 7)*Dx**2 + (4*x**2 - 7*x + 1)*Dx**3 + (4*x**2 + x + 2)*Dx**4, x, 0, [2, 2, -2, 2])\n+ r = HolonomicFunction((-x**4 - x**3/4 - x**2 + 1/4) + (x**3 + x**2/4 + 3*x/4 + 1)*Dx + \\\n+ (-3*x/2 + 7/4)*Dx**2 + (x**2 - 7*x/4 + 1/4)*Dx**3 + (x**2 + x/4 + 1/2)*Dx**4, x, 0, [2, 2, -2, 2])\n assert p + q == r\n p = HolonomicFunction(Dx**2 + 4*x*Dx + x**2, x, 0, [3, 4])\n q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1])\n@@ -105,6 +105,11 @@ def test_addition_initial_condition():\n r = HolonomicFunction((-x**2 - x + 1) + (x**2 + x)*Dx + (-x - 2)*Dx**3 + \\\n (x + 1)*Dx**4, x, 2, [4, 1, 2, -5 ])\n assert p + q == r\n+ p = from_sympy(sin(x))\n+ q = from_sympy(1/x)\n+ r = HolonomicFunction((x**2 + 6) + (x**3 + 2*x)*Dx + (x**2 + 6)*Dx**2 + (x**3 + 2*x)*Dx**3, \\\n+ x, 1, [sin(1) + 1, -1 + cos(1), -sin(1) + 2])\n+ assert p + q == r\n \n def test_multiplication_initial_condition():\n x = symbols('x')\n@@ -116,12 +121,12 @@ def test_multiplication_initial_condition():\n assert p * q == r\n p = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])\n q = HolonomicFunction(Dx**3 - x**2, x, 0, [3, 3, 3])\n- r = HolonomicFunction((27*x**8 - 37*x**7 - 10*x**6 - 492*x**5 - 552*x**4 + 160*x**3 + \\\n- 1212*x**2 + 216*x + 360) + (162*x**7 - 384*x**6 - 294*x**5 - 84*x**4 + 24*x**3 + \\\n- 756*x**2 + 120*x - 1080)*Dx + (81*x**6 - 246*x**5 + 228*x**4 + 36*x**3 + \\\n- 660*x**2 - 720*x)*Dx**2 + (-54*x**6 + 128*x**5 - 18*x**4 - 240*x**2 + 600)*Dx**3 + \\\n- (81*x**5 - 192*x**4 - 84*x**3 + 162*x**2 - 60*x - 180)*Dx**4 + (-108*x**3 + \\\n- 192*x**2 + 72*x)*Dx**5 + (27*x**4 - 64*x**3 - 36*x**2 + 60)*Dx**6, x, 0, [3, 3, 3, -3, -12, -24])\n+ r = HolonomicFunction((x**8 - 37*x**7/27 - 10*x**6/27 - 164*x**5/9 - 184*x**4/9 + \\\n+ 160*x**3/27 + 404*x**2/9 + 8*x + 40/3) + (6*x**7 - 128*x**6/9 - 98*x**5/9 - 28*x**4/9 + \\\n+ 8*x**3/9 + 28*x**2 + 40*x/9 - 40)*Dx + (3*x**6 - 82*x**5/9 + 76*x**4/9 + 4*x**3/3 + \\\n+ 220*x**2/9 - 80*x/3)*Dx**2 + (-2*x**6 + 128*x**5/27 - 2*x**4/3 -80*x**2/9 + 200/9)*Dx**3 + \\\n+ (3*x**5 - 64*x**4/9 - 28*x**3/9 + 6*x**2 - 20*x/9 - 20/3)*Dx**4 + (-4*x**3 + 64*x**2/9 + \\\n+ 8*x/3)*Dx**5 + (x**4 - 64*x**3/27 - 4*x**2/3 + 20/9)*Dx**6, x, 0, [3, 3, 3, -3, -12, -24])\n assert p * q == r\n p = HolonomicFunction(Dx - 1, x, 0, [2])\n q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])\n@@ -134,6 +139,10 @@ def test_multiplication_initial_condition():\n q = HolonomicFunction(Dx**3 + 1, x, 0, [1, 2, 1])\n r = HolonomicFunction(6*Dx + 3*Dx**2 + 2*Dx**3 - 3*Dx**4 + Dx**6, x, 0, [1, 5, 14, 17, 17, 2])\n assert p * q == r\n+ p = from_sympy(sin(x))\n+ q = from_sympy(1/x)\n+ r = HolonomicFunction(x + 2*Dx + x*Dx**2, x, 1, [sin(1), -sin(1) + cos(1)])\n+ assert p * q == r\n \n def test_HolonomicFunction_composition():\n x = symbols('x')\n@@ -168,7 +177,7 @@ def test_from_hyper():\n r = from_hyper(p)\n assert r == q\n p = from_hyper(hyper([1], [S(3)/2], x**2/4))\n- q = HolonomicFunction(-2*x + (-x**2 + 4)*Dx + 2*x*Dx**2, x)\n+ q = HolonomicFunction(-x + (-x**2/2 + 2)*Dx + x*Dx**2, x)\n x0 = 1\n y0 = '[sqrt(pi)*exp(1/4)*erf(1/2), -sqrt(pi)*exp(1/4)*erf(1/2)/2 + 1]'\n assert sstr(p.y0) == y0\n@@ -178,14 +187,14 @@ def test_from_meijerg():\n x = symbols('x')\n R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')\n p = from_meijerg(meijerg(([], [S(3)/2]), ([S(1)/2], [S(1)/2, 1]), x))\n- q = HolonomicFunction(2*x - 1 + (-4*x**2 + x)*Dx + 4*x**2*Dx**2 + 4*x**3*Dx**3, x, 1, \\\n+ q = HolonomicFunction(x/2 - 1/4 + (-x**2 + x/4)*Dx + x**2*Dx**2 + x**3*Dx**3, x, 1, \\\n [1/sqrt(pi), 1/(2*sqrt(pi)), -1/(4*sqrt(pi))])\n assert p == q\n p = from_meijerg(meijerg(([], []), ([0], []), x))\n q = HolonomicFunction(1 + Dx, x, 0, 1)\n assert p == q\n p = from_meijerg(meijerg(([1], []), ([S(1)/2], [0]), x))\n- q = HolonomicFunction((2*x + 1)*Dx + 2*x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)])\n+ q = HolonomicFunction((x + 1/2)*Dx + x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)])\n assert p == q\n p = from_meijerg(meijerg(([0], [1]), ([0], []), 2*x**2))\n q = HolonomicFunction((3*x**2 - 1)*Dx + x**3*Dx**2, x, 1, [-exp(-S(1)/2) + 1, -exp(-S(1)/2)])\n@@ -200,13 +209,13 @@ def test_to_Sequence():\n q = (HolonomicSequence(1 + (n + 2)*Sn**2 + (n**4 + 6*n**3 + 11*n**2 + 6*n)*Sn**3), 1)\n assert p == q\n p = HolonomicFunction(x**2*Dx**4 + x**3 + Dx**2, x).to_sequence()\n- q = (HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5, n), 0)\n+ q = (HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5), 0)\n assert p == q\n p = HolonomicFunction(x**3*Dx**4 + 1 + Dx**2, x).to_sequence()\n- q = (HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2, n), 3)\n+ q = (HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2), 3)\n assert p == q\n p = HolonomicFunction(3*x**3*Dx**4 + 2*x*Dx + x*Dx**3, x).to_sequence()\n- q = (HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2, n), 3)\n+ q = (HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2), 3)\n assert p == q\n \n def test_to_Sequence_Initial_Coniditons():\n@@ -226,6 +235,16 @@ def test_to_Sequence_Initial_Coniditons():\n p = HolonomicFunction(x**3*Dx**5 + 1 + Dx, x).to_sequence()\n q = (HolonomicSequence(1 + (n + 1)*Sn + (n**5 - 5*n**3 + 4*n)*Sn**2), 3)\n assert p == q\n+ C_1, C_2, C_3 = symbols('C_1, C_2, C_3')\n+ p = from_sympy(log(1+x**2))\n+ q = (HolonomicSequence(n**2 + (n**2 + 2*n)*Sn**2, [0, 0, C_2, 0]), 2)\n+ assert p.to_sequence() == q\n+ p = p.diff()\n+ q = (HolonomicSequence((n + 1) + (n + 1)*Sn**2, [0, C_1, 0]), 1)\n+ assert p.to_sequence() == q\n+ p = from_sympy(erf(x) + x).to_sequence()\n+ q = (HolonomicSequence((2*n**2 - 2*n) + (n**3 + 2*n**2 - n - 2)*Sn**2, [0, 1 + 2/sqrt(pi), 0, C_3]), 2)\n+ assert p == q\n \n def test_series():\n x = symbols('x')\n@@ -251,6 +270,10 @@ def test_series():\n (4-6*x**3+2*x**4)*Dx**2, x, 0, [1, 0]).series(n=7)\n q = 1 - 3*x**2/4 - x**3/4 - 5*x**4/32 - 3*x**5/40 - 17*x**6/384 + O(x**7)\n assert p == q\n+ p = from_sympy(erf(x) + x).series(n=10)\n+ C_3 = symbols('C_3')\n+ q = (erf(x) + x).series(n=10)\n+ assert p.subs(C_3, -2/(3*sqrt(pi))) == q\n \n def test_evalf_euler():\n x = symbols('x')\n@@ -410,17 +433,17 @@ def test_from_sympy():\n x = symbols('x')\n R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')\n p = from_sympy((sin(x)/x)**2)\n- q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 1, \\\n- [sin(1)**2, -2*sin(1)**2 + 2*sin(1)*cos(1), -8*sin(1)*cos(1) + 2*cos(1)**2 + 4*sin(1)**2])\n+ q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \\\n+ [1, 0, -2/3])\n assert p == q\n p = from_sympy(1/(1+x**2)**2)\n q = HolonomicFunction(4*x + (x**2 + 1)*Dx, x, 0, 1)\n assert p == q\n p = from_sympy(exp(x)*sin(x)+x*log(1+x))\n- q = HolonomicFunction((4*x**3 + 20*x**2 + 40*x + 36) + (-4*x**4 - 20*x**3 - 40*x**2 \\\n- - 36*x)*Dx + (4*x**5 + 12*x**4 + 14*x**3 + 16*x**2 + 20*x - 8)*Dx**2 + \\\n- (-4*x**5 - 10*x**4 - 4*x**3 + 4*x**2 - 2*x + 8)*Dx**3 + (2*x**5 + 4*x**4 - 2*x**3 - \\\n- 7*x**2 + 2*x + 5)*Dx**4, x, 0, [0, 1, 4, -1])\n+ q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \\\n+ - 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \\\n+ (-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \\\n+ 7*x**2/2 + x + 5/2)*Dx**4, x, 0, [0, 1, 4, -1])\n assert p == q\n p = from_sympy(x*exp(x)+cos(x)+1)\n q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \\\n@@ -431,8 +454,8 @@ def test_from_sympy():\n q = HolonomicFunction(Dx + (3*x + 3)*Dx**2 + (x**2 + 2*x + 1)*Dx**3, x, 0, [1, 0, 2])\n assert p == q\n p = from_sympy(erf(x)**2 + x)\n- q = HolonomicFunction((32*x**4 - 8*x**2 + 8)*Dx**2 + (24*x**3 - 2*x)*Dx**3 + \\\n- (4*x**2+ 1)*Dx**4, x, 0, [0, 1, 8/pi, 0])\n+ q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \\\n+ (x**2+ 1/4)*Dx**4, x, 0, [0, 1, 8/pi, 0])\n assert p == q\n p = from_sympy(cosh(x)*x)\n q = HolonomicFunction((-x**2 + 2) -2*x*Dx + x**2*Dx**2, x, 0, [0, 1])\n@@ -441,9 +464,24 @@ def test_from_sympy():\n q = HolonomicFunction((x**2 - 4) + x*Dx + x**2*Dx**2, x, 0, [0, 0])\n assert p == q\n p = from_sympy(besselj(0, x) + exp(x))\n- q = HolonomicFunction((-2*x**2 - x + 1) + (2*x**2 - x - 3)*Dx + (-2*x**2 + x + 2)*Dx**2 +\\\n- (2*x**2 + x)*Dx**3, x, 0, [2, 1, 1/2])\n+ q = HolonomicFunction((-x**2 - x/2 + 1/2) + (x**2 - x/2 - 3/2)*Dx + (-x**2 + x/2 + 1)*Dx**2 +\\\n+ (x**2 + x/2)*Dx**3, x, 0, [2, 1, 1/2])\n+ assert p == q\n+ p = from_sympy(sin(x)**2/x)\n+ q = HolonomicFunction(4 + 4*x*Dx + 3*Dx**2 + x*Dx**3, x, 0, [0, 1, 0])\n assert p == q\n+ p = from_sympy(sin(x)**2/x, x0=2)\n+ q = HolonomicFunction((4) + (4*x)*Dx + (3)*Dx**2 + (x)*Dx**3, x, 2, [sin(2)**2/2,\n+ sin(2)*cos(2) - sin(2)**2/4, -3*sin(2)**2/4 + cos(2)**2 - sin(2)*cos(2)])\n+ assert p == q\n+ p = from_sympy(log(x)/2 - Ci(2*x)/2 + Ci(2)/2)\n+ q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \\\n+ [-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0])\n+ assert p == q\n+ p = p.to_sympy()\n+ q = log(x)/2 - Ci(2*x)/2 + Ci(2)/2\n+ assert p == q\n+\n \n def test_to_hyper():\n x = symbols('x')\n@@ -487,3 +525,51 @@ def test_to_sympy():\n (x**2 - x)*Dx**2, x, 0, [1, 2]).to_sympy()\n q = 1/(x**2 - 2*x + 1)\n assert p == q\n+ p = from_sympy(sin(x)**2/x).integrate((x, 0, x)).to_sympy()\n+ q = (sin(x)**2/x).integrate((x, 0, x))\n+ assert p == q\n+ C_1, C_2, C_3 = symbols('C_1, C_2, C_3')\n+ p = from_sympy(log(1+x**2)).to_sympy()\n+ q = C_2*log(x**2 + 1)\n+ assert p == q\n+ p = from_sympy(log(1+x**2)).diff().to_sympy()\n+ q = C_1*x/(x**2 + 1)\n+ assert p == q\n+ p = from_sympy(erf(x) + x).to_sympy()\n+ q = 3*C_3*x - 3*sqrt(pi)*C_3*erf(x)/2 + x + 2*x/sqrt(pi)\n+ assert p == q\n+\n+def test_integrate():\n+ x = symbols('x')\n+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')\n+ p = from_sympy(sin(x)**2/x, x0=1).integrate((x, 2, 3))\n+ q = '0.166270406994788'\n+ assert sstr(p) == q\n+ p = from_sympy(sin(x)).integrate((x, 0, x)).to_sympy()\n+ q = 1 - cos(x)\n+ assert p == q\n+ p = from_sympy(sin(x)).integrate((x, 0, 3))\n+ q = '1.98999246812687'\n+ assert sstr(p) == q\n+ p = from_sympy(sin(x)/x, x0=1).integrate((x, 1, 2))\n+ q = '0.659329913368450'\n+ assert sstr(p) == q\n+ p = from_sympy(sin(x)**2/x, x0=1).integrate((x, 1, 0))\n+ q = '-0.423690480850035'\n+ assert sstr(p) == q\n+\n+def test_diff():\n+ x, y = symbols('x, y')\n+ R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')\n+ p = HolonomicFunction(x*Dx**2 + 1, x, 0, [0, 1])\n+ assert p.diff().to_sympy() == p.to_sympy().diff().simplify()\n+ p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0])\n+ assert p.diff(x, 2).to_sympy() == p.to_sympy()\n+ p = from_sympy(Si(x))\n+ assert p.diff().to_sympy() == sin(x)/x\n+ assert p.diff(y) == 0\n+ C_1, C_2, C_3 = symbols('C_1, C_2, C_3')\n+ q = Si(x)\n+ assert p.diff(x).to_sympy() == q.diff()\n+ assert p.diff(x, 2).to_sympy().subs(C_1, -S(1)/3) == q.diff(x, 2).simplify()\n+ assert p.diff(x, 3).series().subs(C_2, S(1)/10) == q.diff(x, 3).series()\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_hyperlinks\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 1,\n \"issue_text_score\": 0,\n \"test_score\": 3\n },\n \"num_modified_files\": 3\n}"},"version":{"kind":"string","value":"1.0"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"mpmath>=0.19\",\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y gcc\"\n ],\n \"python\": \"3.7\",\n \"reqs_path\": [\n \"requirements/base.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"certifi @ file:///croot/certifi_1671487769961/work/certifi\nexceptiongroup==1.2.2\nimportlib-metadata==6.7.0\niniconfig==2.0.0\nmpmath==1.3.0\npackaging==24.0\npluggy==1.2.0\npytest==7.4.4\n-e git+https://github.com/sympy/sympy.git@230b1bf3a3a67c0621a3b4a8f2a45e950f82393f#egg=sympy\ntomli==2.0.1\ntyping_extensions==4.7.1\nzipp==3.15.0\n"},"environment":{"kind":"string","value":"name: sympy\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - certifi=2022.12.7=py37h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=1.1.1w=h7f8727e_0\n - pip=22.3.1=py37h06a4308_0\n - python=3.7.16=h7a1cb2a_0\n - readline=8.2=h5eee18b_0\n - setuptools=65.6.3=py37h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - wheel=0.38.4=py37h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - exceptiongroup==1.2.2\n - importlib-metadata==6.7.0\n - iniconfig==2.0.0\n - mpmath==1.3.0\n - packaging==24.0\n - pluggy==1.2.0\n - pytest==7.4.4\n - tomli==2.0.1\n - typing-extensions==4.7.1\n - zipp==3.15.0\nprefix: /opt/conda/envs/sympy\n"},"FAIL_TO_PASS":{"kind":"list like","value":["sympy/holonomic/tests/test_holonomic.py::test_addition_initial_condition","sympy/holonomic/tests/test_holonomic.py::test_multiplication_initial_condition","sympy/holonomic/tests/test_holonomic.py::test_from_hyper","sympy/holonomic/tests/test_holonomic.py::test_from_meijerg","sympy/holonomic/tests/test_holonomic.py::test_to_Sequence_Initial_Coniditons","sympy/holonomic/tests/test_holonomic.py::test_series","sympy/holonomic/tests/test_holonomic.py::test_from_sympy","sympy/holonomic/tests/test_holonomic.py::test_to_sympy","sympy/holonomic/tests/test_holonomic.py::test_integrate","sympy/holonomic/tests/test_holonomic.py::test_diff"],"string":"[\n \"sympy/holonomic/tests/test_holonomic.py::test_addition_initial_condition\",\n \"sympy/holonomic/tests/test_holonomic.py::test_multiplication_initial_condition\",\n \"sympy/holonomic/tests/test_holonomic.py::test_from_hyper\",\n \"sympy/holonomic/tests/test_holonomic.py::test_from_meijerg\",\n \"sympy/holonomic/tests/test_holonomic.py::test_to_Sequence_Initial_Coniditons\",\n \"sympy/holonomic/tests/test_holonomic.py::test_series\",\n \"sympy/holonomic/tests/test_holonomic.py::test_from_sympy\",\n \"sympy/holonomic/tests/test_holonomic.py::test_to_sympy\",\n \"sympy/holonomic/tests/test_holonomic.py::test_integrate\",\n \"sympy/holonomic/tests/test_holonomic.py::test_diff\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":["sympy/holonomic/tests/test_holonomic.py::test_to_hyper"],"string":"[\n \"sympy/holonomic/tests/test_holonomic.py::test_to_hyper\"\n]"},"PASS_TO_PASS":{"kind":"list like","value":["sympy/holonomic/tests/test_holonomic.py::test_DifferentialOperator","sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_addition","sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_multiplication","sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_composition","sympy/holonomic/tests/test_holonomic.py::test_to_Sequence","sympy/holonomic/tests/test_holonomic.py::test_evalf_euler","sympy/holonomic/tests/test_holonomic.py::test_evalf_rk4"],"string":"[\n \"sympy/holonomic/tests/test_holonomic.py::test_DifferentialOperator\",\n \"sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_addition\",\n \"sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_multiplication\",\n \"sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_composition\",\n \"sympy/holonomic/tests/test_holonomic.py::test_to_Sequence\",\n \"sympy/holonomic/tests/test_holonomic.py::test_evalf_euler\",\n \"sympy/holonomic/tests/test_holonomic.py::test_evalf_rk4\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD"},"__index_level_0__":{"kind":"number","value":599,"string":"599"}}},{"rowIdx":599,"cells":{"instance_id":{"kind":"string","value":"simphony__simphony-remote-21"},"base_commit":{"kind":"string","value":"ca4d029fe1edd54e62a20809aba651401ed6f587"},"created_at":{"kind":"string","value":"2016-06-27 10:40:39"},"environment_setup_commit":{"kind":"string","value":"d7657fa7d4297b4c922a900ba9a8a337184113ef"},"hints_text":{"kind":"string","value":""},"patch":{"kind":"string","value":"diff --git a/remoteappmanager/docker/container.py b/remoteappmanager/docker/container.py\nindex f4e8677..6123205 100644\n--- a/remoteappmanager/docker/container.py\n+++ b/remoteappmanager/docker/container.py\n@@ -23,7 +23,7 @@ class Container(HasTraits):\n ip = Unicode()\n \n #: ...and port where the container service will be listening\n- port = Int()\n+ port = Int(None, allow_none=True)\n \n @property\n def url(self):\n@@ -38,3 +38,44 @@ class Container(HasTraits):\n ip=self.ip,\n port=self.port,\n )\n+\n+ def __repr__(self):\n+ return ('').format(\n+ self.docker_id, self.name,\n+ self.image_name, self.image_id,\n+ self.ip, self.port)\n+\n+ @classmethod\n+ def from_docker_dict(cls, docker_dict):\n+ \"\"\"Returns a Container object with the info given by a\n+ docker Client.\n+\n+ Parameters\n+ ----------\n+ docker_dict : dict\n+ One item from the result of docker.Client.containers\n+\n+ Returns\n+ -------\n+ container : Container\n+\n+ Examples\n+ --------\n+ >>> # containers is a list of dict\n+ >>> containers = docker.Client().containers()\n+\n+ >>> Container.from_docker_dict(containers[0])\n+ \"\"\"\n+ if docker_dict.get('Ports'):\n+ ip = docker_dict['Ports'][0].get('IP', \"\")\n+ port = docker_dict['Ports'][0].get('PublicPort')\n+ else:\n+ ip = \"\"\n+ port = None\n+\n+ return cls(docker_id=docker_dict.get('Id', ''),\n+ name=docker_dict.get('Names', ('',))[0],\n+ image_name=docker_dict.get('Image', ''),\n+ image_id=docker_dict.get('ImageID', ''),\n+ ip=ip, port=port)\ndiff --git a/remoteappmanager/docker/container_manager.py b/remoteappmanager/docker/container_manager.py\nindex 19559cf..94b7b39 100644\n--- a/remoteappmanager/docker/container_manager.py\n+++ b/remoteappmanager/docker/container_manager.py\n@@ -93,26 +93,44 @@ class ContainerManager(LoggingMixin):\n self._stop_pending.remove(container_id)\n \n @gen.coroutine\n- def containers_for_image(self, image_id):\n- \"\"\"Returns the containers for a given image that are managed\n- by this object.\n+ def containers_for_image(self, image_id_or_name, user_name=None):\n+ \"\"\"Returns the currently running containers for a given image.\n+\n+ If `user_name` is given, only returns containers started by the\n+ given user name.\n \n It is a coroutine because we might want to run an inquire to the docker\n service if not present.\n \n Parameters\n ----------\n- image_id: str\n- The image id\n+ image_id_or_name: str\n+ The image id or name\n+\n+ Optional parameters\n+ -------------------\n+ user_name : str\n+ Name of the user who started the container\n \n Return\n ------\n A list of container objects, or an empty list if not present.\n \"\"\"\n- try:\n- return self._containers_for_image[image_id]\n- except KeyError:\n- return []\n+ if user_name:\n+ user_labels = _get_container_labels(user_name)\n+ if user_labels:\n+ filters = {'label': '{0}={1}'.format(*user_labels.popitem())}\n+ else:\n+ filters = {}\n+\n+ filters['ancestor'] = image_id_or_name\n+\n+ containers = yield self.docker_client.containers(filters=filters)\n+ return [Container.from_docker_dict(container)\n+ for container in containers\n+ # Require further filtering as ancestor include grandparents\n+ if (container.get('Image') == image_id_or_name or\n+ container.get('ImageID') == image_id_or_name)]\n \n @gen.coroutine\n def all_images(self):\ndiff --git a/remoteappmanager/handlers/home_handler.py b/remoteappmanager/handlers/home_handler.py\nindex c940fe4..a9fa728 100644\n--- a/remoteappmanager/handlers/home_handler.py\n+++ b/remoteappmanager/handlers/home_handler.py\n@@ -11,6 +11,7 @@ from tornado.httpclient import AsyncHTTPClient, HTTPError\n from tornado.log import app_log\n \n from remoteappmanager.handlers.base_handler import BaseHandler\n+from remoteappmanager.docker.container import Container\n \n \n # FIXME: replace these with ORM objects\n@@ -31,7 +32,7 @@ class HomeHandler(BaseHandler):\n \n for image in all_images:\n containers = yield container_manager.containers_for_image(\n- image.docker_id)\n+ image.docker_id, self.current_user)\n container = (containers[0] if len(containers) > 0 else None)\n # For now we assume we have only one.\n images_info.append({\n@@ -65,37 +66,47 @@ class HomeHandler(BaseHandler):\n exc_info=True)\n return\n \n- yield handler(self.current_user, options)\n-\n- # Subhandling after post\n-\n- @gen.coroutine\n- def _actionhandler_start(self, user_name, options):\n- \"\"\"Sub handling. Acts in response to a \"start\" request from\n- the user.\"\"\"\n- # Start the single-user server\n-\n try:\n- image_name = options[\"image_name\"][0]\n- container = yield self._start_container(user_name, image_name)\n+ yield handler(self.current_user, options)\n except Exception as e:\n # Create a random reference number for support\n ref = str(uuid.uuid1())\n- self.log.exception(\"Failed to spawn docker image. %s \"\n- \"Ref: %s\",\n- str(e), ref)\n+ self.log.exception(\"Failed with POST action: {0}. {1} \"\n+ \"Ref: {2}\".format(\n+ action, str(e), ref))\n \n images_info = yield self._get_images_info()\n \n # Render the home page again with the error message\n # User-facing error message (less info)\n- message = ('Failed to start \"{image_name}\". Reason: {error_type} '\n+ message = ('Failed to {action} \"{image_name}\". '\n+ 'Reason: {error_type} '\n '(Ref: {ref})')\n self.render('home.html', images_info=images_info,\n error_message=message.format(\n- image_name=image_name,\n+ action=action,\n+ image_name=options[\"image_name\"][0],\n error_type=type(e).__name__,\n ref=ref))\n+\n+ # Subhandling after post\n+\n+ @gen.coroutine\n+ def _actionhandler_start(self, user_name, options):\n+ \"\"\"Sub handling. Acts in response to a \"start\" request from\n+ the user.\"\"\"\n+ # Start the single-user server\n+\n+ try:\n+ # FIXME: too many operations in one try block, should be separated\n+ # for better error handling\n+ image_name = options[\"image_name\"][0]\n+ container = yield self._start_container(user_name, image_name)\n+ yield self._wait_for_container_ready(container)\n+ except Exception as e:\n+ # Clean up, if the container is running\n+ yield self._stop_and_remove_container(user_name, image_name)\n+ raise e\n else:\n # The server is up and running. Now contact the proxy and add\n # the container url to it.\n@@ -112,10 +123,16 @@ class HomeHandler(BaseHandler):\n It is not different from pasting the appropriate URL in the\n web browser, but we validate the container id first.\n \"\"\"\n- container = self._container_from_options(options)\n+ container = yield self._container_from_options(options)\n if not container:\n+ self.finish(\"Unable to view the application\")\n return\n \n+ yield self._wait_for_container_ready(container)\n+\n+ # in case the reverse proxy is not already set up\n+ yield self.application.reverse_proxy_add_container(container)\n+\n url = self.application.container_url_abspath(container)\n self.log.info('Redirecting to ' + url)\n self.redirect(url)\n@@ -127,11 +144,18 @@ class HomeHandler(BaseHandler):\n app = self.application\n container_manager = app.container_manager\n \n- container = self._container_from_options(options)\n+ container = yield self._container_from_options(options)\n if not container:\n+ self.finish(\"Unable to view the application\")\n return\n \n- yield app.reverse_proxy_remove_container(container)\n+ try:\n+ yield app.reverse_proxy_remove_container(container)\n+ except HTTPError as http_error:\n+ # The reverse proxy may be absent to start with\n+ if http_error.code != 404:\n+ raise http_error\n+\n yield container_manager.stop_and_remove_container(container.docker_id)\n \n # We don't have fancy stuff at the moment to change the button, so\n@@ -140,31 +164,35 @@ class HomeHandler(BaseHandler):\n \n # private\n \n+ @gen.coroutine\n def _container_from_options(self, options):\n \"\"\"Support routine to reduce duplication.\n Retrieves and returns the container if valid and present.\n- If not present, performs the http response and returns None.\n+\n+ If not present, returns None\n \"\"\"\n \n container_manager = self.application.container_manager\n+\n try:\n container_id = options[\"container_id\"][0]\n except (KeyError, IndexError):\n self.log.exception(\n \"Failed to retrieve valid container_id from form\"\n )\n- self.finish(\"Unable to retrieve valid container_id value\")\n return None\n \n- try:\n- container = container_manager.containers[container_id]\n- except KeyError:\n- self.log.error(\"Unable to find container_id {} in manager\".format(\n- container_id))\n- self.finish(\"Unable to find specified container_id\")\n- return None\n+ container_dict = yield container_manager.docker_client.containers(\n+ filters={'id': container_id})\n \n- return container\n+ if container_dict:\n+ return Container.from_docker_dict(container_dict[0])\n+ else:\n+ self.log.exception(\n+ \"Failed to retrieve valid container from container id: %s\",\n+ container_id\n+ )\n+ return None\n \n @gen.coroutine\n def _start_container(self, user_name, image_name):\n@@ -212,46 +240,21 @@ class HomeHandler(BaseHandler):\n e.reason = 'error'\n raise e\n \n- # Note, we use the jupyterhub ORM server, but we don't use it for\n- # any database activity.\n- # Note: the end / is important. We want to get a 200 from the actual\n- # websockify server, not the nginx (which presents the redirection\n- # page).\n- server_url = \"http://{}:{}{}/\".format(\n- container.ip,\n- container.port,\n- self.application.container_url_abspath(container))\n+ return container\n \n- try:\n- yield _wait_for_http_server_2xx(\n- server_url,\n- self.application.config.network_timeout)\n- except TimeoutError as e:\n- # Note: Using TimeoutError instead of gen.TimeoutError as above\n- # is not a mistake.\n- self.log.warning(\n- \"{user}'s container never showed up at {url} \"\n- \"after {http_timeout} seconds. Giving up.\".format(\n- user=user_name,\n- url=server_url,\n- http_timeout=self.application.config.network_timeout,\n- )\n- )\n- e.reason = 'timeout'\n- raise e\n- except Exception as e:\n- self.log.exception(\n- \"Unhandled error waiting for {user}'s server \"\n- \"to show up at {url}: {error}\".format(\n- user=user_name,\n- url=server_url,\n- error=e,\n- )\n- )\n- e.reason = 'error'\n- raise e\n+ @gen.coroutine\n+ def _stop_and_remove_container(self, user_name, image_name):\n+ \"\"\" Stop and remove the container associated with the given\n+ user name and image name, if exists.\n+ \"\"\"\n+ container_manager = self.application.container_manager\n+ containers = yield container_manager.containers_for_image(\n+ image_name, user_name)\n \n- return container\n+ # Assume only one container per image\n+ if containers:\n+ container_id = containers[0].docker_id\n+ yield container_manager.stop_and_remove_container(container_id)\n \n def _parse_form(self):\n \"\"\"Extract the form options from the form and return them\n@@ -262,6 +265,29 @@ class HomeHandler(BaseHandler):\n \n return form_options\n \n+ @gen.coroutine\n+ def _wait_for_container_ready(self, container):\n+ \"\"\" Wait until the container is ready to be connected\n+\n+ Parameters\n+ ----------\n+ container: Container\n+ The container to be connected\n+ \"\"\"\n+ # Note, we use the jupyterhub ORM server, but we don't use it for\n+ # any database activity.\n+ # Note: the end / is important. We want to get a 200 from the actual\n+ # websockify server, not the nginx (which presents the redirection\n+ # page).\n+ server_url = \"http://{}:{}{}/\".format(\n+ container.ip,\n+ container.port,\n+ self.application.container_url_abspath(container))\n+\n+ yield _wait_for_http_server_2xx(\n+ server_url,\n+ self.application.config.network_timeout)\n+\n \n @gen.coroutine\n def _wait_for_http_server_2xx(url, timeout=10):\n"},"problem_statement":{"kind":"string","value":"Running containers not in cache when container is started without a public port\nStart any incompatible image not exposing a port (e.g. `quay.io/travisci/travis-python:latest`), the container is up and running but we do not keep it in our cache of running containers because the port is unavailable (an exception is raised).\r\n\r\nFrom the user point of view, there is no View/Stop button which makes sense.\r\nFrom the admin point of view, the container has to be stopped and removed automatically.\r\n\r\nNeeded for #6 \r\n"},"repo":{"kind":"string","value":"simphony/simphony-remote"},"test_patch":{"kind":"string","value":"diff --git a/tests/docker/test_container.py b/tests/docker/test_container.py\nindex 7d1cbae..faea36f 100644\n--- a/tests/docker/test_container.py\n+++ b/tests/docker/test_container.py\n@@ -1,6 +1,7 @@\n from unittest import TestCase\n \n from remoteappmanager.docker.container import Container\n+from tests.utils import assert_containers_equal\n \n \n class TestContainer(TestCase):\n@@ -18,3 +19,64 @@ class TestContainer(TestCase):\n )\n \n self.assertEqual(container.host_url, \"http://123.45.67.89:31337\")\n+\n+ def test_from_docker_dict_with_public_port(self):\n+ '''Test convertion from \"docker ps\" to Container with public port'''\n+ # With public port\n+ container_dict = {\n+ 'Command': '/startup.sh',\n+ 'Created': 1466756760,\n+ 'HostConfig': {'NetworkMode': 'default'},\n+ 'Id': '248e45e717cd740ae763a1c565',\n+ 'Image': 'empty-ubuntu:latest',\n+ 'ImageID': 'sha256:f4610c7580b8f0a9a25086b6287d0069fb8a',\n+ 'Labels': {'eu.simphony-project.docker.ui_name': 'Empty Ubuntu',\n+ 'eu.simphony-project.docker.user': 'user'},\n+ 'Names': ['/remoteexec-user-empty-ubuntu_3Alatest'],\n+ 'Ports': [{'IP': '0.0.0.0',\n+ 'PrivatePort': 8888,\n+ 'PublicPort': 32823,\n+ 'Type': 'tcp'}],\n+ 'State': 'running',\n+ 'Status': 'Up 56 minutes'}\n+\n+ # Container with public port\n+ actual = Container.from_docker_dict(container_dict)\n+ expected = Container(\n+ docker_id='248e45e717cd740ae763a1c565',\n+ name='/remoteexec-user-empty-ubuntu_3Alatest',\n+ image_name='empty-ubuntu:latest',\n+ image_id='sha256:f4610c7580b8f0a9a25086b6287d0069fb8a',\n+ ip='0.0.0.0', port=32823)\n+\n+ assert_containers_equal(self, actual, expected)\n+\n+ def test_from_docker_dict_without_public_port(self):\n+ '''Test convertion from \"docker ps\" to Container with public port'''\n+ # With public port\n+ container_dict = {\n+ 'Command': '/startup.sh',\n+ 'Created': 1466756760,\n+ 'HostConfig': {'NetworkMode': 'default'},\n+ 'Id': '812c765d0549be0ab831ae8348',\n+ 'Image': 'novnc-ubuntu:latest',\n+ 'ImageID': 'sha256:f4610c75d3c0dfa25d3c0dfa25d3c0dfa2',\n+ 'Labels': {'eu.simphony-project.docker.ui_name': 'Empty Ubuntu',\n+ 'eu.simphony-project.docker.user': 'user'},\n+ 'Names': ['/remoteexec-user-empty-ubuntu_3Alatest'],\n+ 'Ports': [{'IP': '0.0.0.0',\n+ 'PrivatePort': 8888,\n+ 'Type': 'tcp'}],\n+ 'State': 'running',\n+ 'Status': 'Up 56 minutes'}\n+\n+ # Container without public port\n+ actual = Container.from_docker_dict(container_dict)\n+ expected = Container(\n+ docker_id='812c765d0549be0ab831ae8348',\n+ name='/remoteexec-user-empty-ubuntu_3Alatest',\n+ image_name='novnc-ubuntu:latest',\n+ image_id='sha256:f4610c75d3c0dfa25d3c0dfa25d3c0dfa2',\n+ ip='0.0.0.0', port=None)\n+\n+ assert_containers_equal(self, actual, expected)\ndiff --git a/tests/docker/test_container_manager.py b/tests/docker/test_container_manager.py\nindex f878bb1..5ed4774 100644\n--- a/tests/docker/test_container_manager.py\n+++ b/tests/docker/test_container_manager.py\n@@ -33,24 +33,63 @@ class TestContainerManager(AsyncTestCase):\n self.assertTrue(mock_client.remove_container.called)\n \n @gen_test\n- def test_container_for_image(self):\n- result = yield self.manager.containers_for_image(\"imageid\")\n- self.assertEqual(len(result), 0)\n+ def test_containers_for_image_results(self):\n+ ''' Test containers_for_image returns a list of Container '''\n+ # The mock client mocks the output of docker Client.containers\n+ docker_client = utils.mock_docker_client_with_running_containers()\n+ self.mock_docker_client = docker_client\n+ self.manager.docker_client.client = docker_client\n+\n+ # The output should be a list of Container\n+ results = yield self.manager.containers_for_image(\"imageid\")\n+ expected = [Container(docker_id='someid',\n+ name='/remoteexec-image_3Alatest_user',\n+ image_name='simphony/mayavi-4.4.4:latest', # noqa\n+ image_id='imageid', ip='0.0.0.0', port=None),\n+ Container(docker_id='someid',\n+ name='/remoteexec-image_3Alatest_user2',\n+ image_name='simphony/mayavi-4.4.4:latest', # noqa\n+ image_id='imageid', ip='0.0.0.0', port=None),\n+ Container(docker_id='someid',\n+ name='/remoteexec-image_3Alatest_user3',\n+ image_name='simphony/mayavi-4.4.4:latest', # noqa\n+ image_id='imageid', ip='', port=None)]\n+\n+ for result, expected_container in zip(results, expected):\n+ utils.assert_containers_equal(self, result, expected_container)\n \n- yield self.manager.start_container(\"username\", \"imageid\")\n+ @gen_test\n+ def test_containers_for_image_client_api_without_user(self):\n+ ''' Test containers_for_images(image_id) use of Client API'''\n+ # The mock client mocks the output of docker Client.containers\n+ docker_client = utils.mock_docker_client_with_running_containers()\n+ self.manager.docker_client.client = docker_client\n \n- result = yield self.manager.containers_for_image(\"imageid\")\n- self.assertEqual(len(result), 1)\n+ # We assume the client.containers(filters=...) is tested by docker-py\n+ # Instead we test if the correct arguments are passed to the Client API\n+ yield self.manager.containers_for_image(\"imageid\")\n+ call_args = self.manager.docker_client.client.containers.call_args\n \n- expected = {'name': 'remoteexec-username-imageid',\n- 'image_id': 'imageid',\n- 'image_name': 'imageid',\n- 'ip': '127.0.0.1',\n- 'port': 666,\n- 'docker_id': 'containerid'}\n+ # filters is one of the keyword argument\n+ self.assertIn('filters', call_args[1])\n+ self.assertEqual(call_args[1]['filters']['ancestor'], \"imageid\")\n \n- for key, value in expected.items():\n- self.assertEqual(getattr(result[0], key), value)\n+ @gen_test\n+ def test_containers_for_image_client_api_with_user(self):\n+ ''' Test containers_for_images(image_id, user) use of Client API'''\n+ # The mock client mocks the output of docker Client.containers\n+ docker_client = utils.mock_docker_client_with_running_containers()\n+ self.manager.docker_client.client = docker_client\n+\n+ # We assume the client.containers(filters=...) is tested by docker-py\n+ # Instead we test if the correct arguments are passed to the Client API\n+ yield self.manager.containers_for_image(\"imageid\", \"userABC\")\n+ call_args = self.manager.docker_client.client.containers.call_args\n+\n+ # filters is one of the keyword argument\n+ self.assertIn('filters', call_args[1])\n+ self.assertEqual(call_args[1]['filters']['ancestor'], \"imageid\")\n+ self.assertIn(\"userABC\", call_args[1]['filters']['label'])\n \n @gen_test\n def test_race_condition_spawning(self):\ndiff --git a/tests/utils.py b/tests/utils.py\nindex ed44914..f957a35 100644\n--- a/tests/utils.py\n+++ b/tests/utils.py\n@@ -47,6 +47,56 @@ def mock_docker_client():\n return docker_client\n \n \n+def mock_docker_client_with_running_containers():\n+ \"\"\"Same as above, but it behaves as if one of the images have two\n+ containers running for different users.\"\"\"\n+ client = mock_docker_client()\n+ client.containers.return_value = [\n+ # user\n+ {'Command': '/sbin/init -D',\n+ 'Created': 1466766499,\n+ 'HostConfig': {'NetworkMode': 'default'},\n+ 'Id': 'someid',\n+ 'Image': 'simphony/mayavi-4.4.4:latest',\n+ 'ImageID': 'imageid',\n+ 'Labels': {'eu.simphony-project.docker.user': 'user'},\n+ 'Names': ['/remoteexec-image_3Alatest_user'],\n+ 'Ports': [{'IP': '0.0.0.0',\n+ 'PublicIP': 34567,\n+ 'PrivatePort': 22,\n+ 'Type': 'tcp'}],\n+ 'State': 'running',\n+ 'Status': 'Up About an hour'},\n+ # user2\n+ {'Command': '/sbin/init -D',\n+ 'Created': 1466766499,\n+ 'HostConfig': {'NetworkMode': 'default'},\n+ 'Id': 'someid',\n+ 'Image': 'simphony/mayavi-4.4.4:latest',\n+ 'ImageID': 'imageid',\n+ 'Labels': {'eu.simphony-project.docker.user': 'user2'},\n+ 'Names': ['/remoteexec-image_3Alatest_user2'],\n+ 'Ports': [{'IP': '0.0.0.0',\n+ 'PublicIP': 34567,\n+ 'PrivatePort': 22,\n+ 'Type': 'tcp'}],\n+ 'State': 'running',\n+ 'Status': 'Up About an hour'},\n+ # user3 (somehow there is no port\n+ {'Command': '/sbin/init -D',\n+ 'Created': 1466766499,\n+ 'HostConfig': {'NetworkMode': 'default'},\n+ 'Id': 'someid',\n+ 'Image': 'simphony/mayavi-4.4.4:latest',\n+ 'ImageID': 'imageid',\n+ 'Labels': {'eu.simphony-project.docker.user': 'user3'},\n+ 'Names': ['/remoteexec-image_3Alatest_user3'],\n+ 'State': 'running',\n+ 'Status': 'Up About an hour'}]\n+\n+ return client\n+\n+\n def mock_docker_client_with_existing_stopped_container():\n \"\"\"Same as above, but it behaves as if one of the containers is already\n started.\"\"\"\n@@ -167,3 +217,14 @@ def invocation_argv():\n yield\n \n sys.argv[:] = saved_argv\n+\n+\n+def assert_containers_equal(test_case, actual, expected):\n+ if (expected.docker_id != actual.docker_id or\n+ expected.name != actual.name or\n+ expected.image_name != actual.image_name or\n+ expected.image_id != actual.image_id or\n+ expected.ip != actual.ip or\n+ expected.port != actual.port):\n+ message = '{!r} is not identical to the expected {!r}'\n+ test_case.fail(message.format(actual, expected))\n"},"meta":{"kind":"string","value":"{\n \"commit_name\": \"head_commit\",\n \"failed_lite_validators\": [\n \"has_issue_reference\",\n \"has_many_modified_files\",\n \"has_many_hunks\"\n ],\n \"has_test_patch\": true,\n \"is_lite\": false,\n \"llm_score\": {\n \"difficulty_score\": 2,\n \"issue_text_score\": 1,\n \"test_score\": 0\n },\n \"num_modified_files\": 3\n}"},"version":{"kind":"string","value":"0.1"},"install_config":{"kind":"string","value":"{\n \"env_vars\": null,\n \"env_yml_path\": null,\n \"install\": \"pip install -e .[dev]\",\n \"log_parser\": \"parse_log_pytest\",\n \"no_use_env\": null,\n \"packages\": \"requirements.txt\",\n \"pip_packages\": [\n \"flake8\",\n \"sphinx\",\n \"pytest\"\n ],\n \"pre_install\": [\n \"apt-get update\",\n \"apt-get install -y docker.io\"\n ],\n \"python\": \"3.9\",\n \"reqs_path\": [\n \"requirements.txt\"\n ],\n \"test_cmd\": \"pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning\"\n}"},"requirements":{"kind":"string","value":"alabaster==0.7.16\nalembic==1.15.2\nannotated-types==0.7.0\narrow==1.3.0\nasync-generator==1.10\nattrs==25.3.0\nbabel==2.17.0\ncertifi==2025.1.31\ncertipy==0.2.2\ncffi==1.17.1\ncharset-normalizer==3.4.1\ncryptography==44.0.2\ndocker-py==1.10.6\ndocker-pycreds==0.4.0\ndocutils==0.21.2\nescapism==1.0.1\nexceptiongroup==1.2.2\nflake8==7.2.0\nfqdn==1.5.1\ngreenlet==3.1.1\nidna==3.10\nimagesize==1.4.1\nimportlib_metadata==8.6.1\niniconfig==2.1.0\nisoduration==20.11.0\nJinja2==3.1.6\njsonpointer==3.0.0\njsonschema==4.23.0\njsonschema-specifications==2024.10.1\njupyter-events==0.12.0\njupyter_client==8.6.3\njupyter_core==5.7.2\njupyterhub==5.2.1\nMako==1.3.9\nMarkupSafe==3.0.2\nmccabe==0.7.0\noauthlib==3.2.2\npackaging==24.2\npamela==1.2.0\nplatformdirs==4.3.7\npluggy==1.5.0\nprometheus_client==0.21.1\npycodestyle==2.13.0\npycparser==2.22\npydantic==2.11.1\npydantic_core==2.33.0\npyflakes==3.3.1\nPygments==2.19.1\npytest==8.3.5\npython-dateutil==2.9.0.post0\npython-json-logger==3.3.0\nPyYAML==6.0.2\npyzmq==26.3.0\nreferencing==0.36.2\n-e git+https://github.com/simphony/simphony-remote.git@ca4d029fe1edd54e62a20809aba651401ed6f587#egg=remoteappmanager\nrequests==2.32.3\nrfc3339-validator==0.1.4\nrfc3986-validator==0.1.1\nrpds-py==0.24.0\nsix==1.17.0\nsnowballstemmer==2.2.0\nSphinx==7.4.7\nsphinxcontrib-applehelp==2.0.0\nsphinxcontrib-devhelp==2.0.0\nsphinxcontrib-htmlhelp==2.1.0\nsphinxcontrib-jsmath==1.0.1\nsphinxcontrib-qthelp==2.0.0\nsphinxcontrib-serializinghtml==2.0.0\nSQLAlchemy==2.0.40\ntomli==2.2.1\ntornado==6.4.2\ntraitlets==5.14.3\ntypes-python-dateutil==2.9.0.20241206\ntyping-inspection==0.4.0\ntyping_extensions==4.13.0\nuri-template==1.3.0\nurllib3==2.3.0\nwebcolors==24.11.1\nwebsocket-client==1.8.0\nzipp==3.21.0\n"},"environment":{"kind":"string","value":"name: simphony-remote\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com/pkgs/r\n - conda-forge\ndependencies:\n - _libgcc_mutex=0.1=main\n - _openmp_mutex=5.1=1_gnu\n - ca-certificates=2025.2.25=h06a4308_0\n - ld_impl_linux-64=2.40=h12ee557_0\n - libffi=3.4.4=h6a678d5_1\n - libgcc-ng=11.2.0=h1234567_1\n - libgomp=11.2.0=h1234567_1\n - libstdcxx-ng=11.2.0=h1234567_1\n - ncurses=6.4=h6a678d5_0\n - openssl=3.0.16=h5eee18b_0\n - pip=25.0=py39h06a4308_0\n - python=3.9.21=he870216_1\n - readline=8.2=h5eee18b_0\n - setuptools=75.8.0=py39h06a4308_0\n - sqlite=3.45.3=h5eee18b_0\n - tk=8.6.14=h39e8969_0\n - tzdata=2025a=h04d1e81_0\n - wheel=0.45.1=py39h06a4308_0\n - xz=5.6.4=h5eee18b_1\n - zlib=1.2.13=h5eee18b_1\n - pip:\n - alabaster==0.7.16\n - alembic==1.15.2\n - annotated-types==0.7.0\n - arrow==1.3.0\n - async-generator==1.10\n - attrs==25.3.0\n - babel==2.17.0\n - certifi==2025.1.31\n - certipy==0.2.2\n - cffi==1.17.1\n - charset-normalizer==3.4.1\n - cryptography==44.0.2\n - docker-py==1.10.6\n - docker-pycreds==0.4.0\n - docutils==0.21.2\n - escapism==1.0.1\n - exceptiongroup==1.2.2\n - flake8==7.2.0\n - fqdn==1.5.1\n - greenlet==3.1.1\n - idna==3.10\n - imagesize==1.4.1\n - importlib-metadata==8.6.1\n - iniconfig==2.1.0\n - isoduration==20.11.0\n - jinja2==3.1.6\n - jsonpointer==3.0.0\n - jsonschema==4.23.0\n - jsonschema-specifications==2024.10.1\n - jupyter-client==8.6.3\n - jupyter-core==5.7.2\n - jupyter-events==0.12.0\n - jupyterhub==5.2.1\n - mako==1.3.9\n - markupsafe==3.0.2\n - mccabe==0.7.0\n - oauthlib==3.2.2\n - packaging==24.2\n - pamela==1.2.0\n - platformdirs==4.3.7\n - pluggy==1.5.0\n - prometheus-client==0.21.1\n - pycodestyle==2.13.0\n - pycparser==2.22\n - pydantic==2.11.1\n - pydantic-core==2.33.0\n - pyflakes==3.3.1\n - pygments==2.19.1\n - pytest==8.3.5\n - python-dateutil==2.9.0.post0\n - python-json-logger==3.3.0\n - pyyaml==6.0.2\n - pyzmq==26.3.0\n - referencing==0.36.2\n - requests==2.32.3\n - rfc3339-validator==0.1.4\n - rfc3986-validator==0.1.1\n - rpds-py==0.24.0\n - six==1.17.0\n - snowballstemmer==2.2.0\n - sphinx==7.4.7\n - sphinxcontrib-applehelp==2.0.0\n - sphinxcontrib-devhelp==2.0.0\n - sphinxcontrib-htmlhelp==2.1.0\n - sphinxcontrib-jsmath==1.0.1\n - sphinxcontrib-qthelp==2.0.0\n - sphinxcontrib-serializinghtml==2.0.0\n - sqlalchemy==2.0.40\n - tomli==2.2.1\n - tornado==6.4.2\n - traitlets==5.14.3\n - types-python-dateutil==2.9.0.20241206\n - typing-extensions==4.13.0\n - typing-inspection==0.4.0\n - uri-template==1.3.0\n - urllib3==2.3.0\n - webcolors==24.11.1\n - websocket-client==1.8.0\n - zipp==3.21.0\nprefix: /opt/conda/envs/simphony-remote\n"},"FAIL_TO_PASS":{"kind":"list like","value":["tests/docker/test_container.py::TestContainer::test_from_docker_dict_with_public_port","tests/docker/test_container.py::TestContainer::test_from_docker_dict_without_public_port","tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_client_api_with_user","tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_client_api_without_user","tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_results"],"string":"[\n \"tests/docker/test_container.py::TestContainer::test_from_docker_dict_with_public_port\",\n \"tests/docker/test_container.py::TestContainer::test_from_docker_dict_without_public_port\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_client_api_with_user\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_client_api_without_user\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_results\"\n]"},"FAIL_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"PASS_TO_PASS":{"kind":"list like","value":["tests/docker/test_container.py::TestContainer::test_host_url","tests/docker/test_container.py::TestContainer::test_url","tests/docker/test_container_manager.py::TestContainerManager::test_instantiation","tests/docker/test_container_manager.py::TestContainerManager::test_race_condition_spawning","tests/docker/test_container_manager.py::TestContainerManager::test_start_already_present_container","tests/docker/test_container_manager.py::TestContainerManager::test_start_container_with_nonexisting_volume_source","tests/docker/test_container_manager.py::TestContainerManager::test_start_stop"],"string":"[\n \"tests/docker/test_container.py::TestContainer::test_host_url\",\n \"tests/docker/test_container.py::TestContainer::test_url\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_instantiation\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_race_condition_spawning\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_start_already_present_container\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_start_container_with_nonexisting_volume_source\",\n \"tests/docker/test_container_manager.py::TestContainerManager::test_start_stop\"\n]"},"PASS_TO_FAIL":{"kind":"list like","value":[],"string":"[]"},"license_name":{"kind":"string","value":"BSD 3-Clause \"New\" or \"Revised\" License"},"__index_level_0__":{"kind":"number","value":600,"string":"600"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":5,"numItemsPerPage":100,"numTotalItems":21336,"offset":500,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1ODMxMjg0Niwic3ViIjoiL2RhdGFzZXRzL25lYml1cy9TV0UtcmViZW5jaCIsImV4cCI6MTc1ODMxNjQ0NiwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.XAfb1nx-414Xiyvfk4AfES9IkPlnBXG3GUts-p1kLn_QVGjZiT0ddYJ_72gjN9zhCm7zRQEm1avMCH0V97a2Bg","displayUrls":true},"discussionsStats":{"closed":3,"open":5,"total":8},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[{"views":[{"key":"default/test","displayName":"test","viewName":"test"}],"sql":"SELECT DISTINCT repo FROM test;","title":"Unique Repositories in Tests","createdAt":"2025-09-14T18:04:37.719Z","slug":"-PidJjw","private":false,"justification":"Lists unique repository names from the dataset, providing a basic overview of the repositories present.","viewNames":["test"]},{"views":[{"key":"default/test","displayName":"test","viewName":"test"}],"sql":"-- The SQL console is powered by DuckDB WASM and runs entirely in the browser.\n-- Get started by typing a query or selecting a view from the options below.\nSELECT * FROM test where instance_id = 'oemof__tespy-653'","title":"Filter Test Data by Instance ID","createdAt":"2025-05-30T02:20:23.351Z","slug":"Mlmmb3M","private":false,"justification":"Retrieves all records for a specific instance, providing limited insight into the data structure but no broader analytical value.","viewNames":["test"]}],"user":[]}}">
instance_id
stringlengths
10
57
base_commit
stringlengths
40
40
created_at
stringdate
2014-04-30 14:58:36
2025-04-30 20:14:11
environment_setup_commit
stringlengths
40
40
hints_text
stringlengths
0
273k
patch
stringlengths
251
7.06M
problem_statement
stringlengths
11
52.5k
repo
stringlengths
7
53
test_patch
stringlengths
231
997k
meta
dict
version
stringclasses
864 values
install_config
dict
requirements
stringlengths
93
34.2k
environment
stringlengths
760
20.5k
FAIL_TO_PASS
listlengths
1
9.39k
FAIL_TO_FAIL
listlengths
0
2.69k
PASS_TO_PASS
listlengths
0
7.87k
PASS_TO_FAIL
listlengths
0
192
license_name
stringclasses
56 values
__index_level_0__
int64
0
21.4k
juju-solutions__charms.reactive-65
3540030b9b142787f3f7fd16a14ed33d18b4d7a1
2016-04-12 16:08:23
59b07bd9447d8a4cb027ea2515089216b8d20549
diff --git a/charms/reactive/bus.py b/charms/reactive/bus.py index 9676244..885e498 100644 --- a/charms/reactive/bus.py +++ b/charms/reactive/bus.py @@ -267,7 +267,10 @@ class Handler(object): """ Lazily evaluate the args. """ - return list(chain.from_iterable(self._args)) + if not hasattr(self, '_args_evaled'): + # cache the args in case handler is re-invoked due to states change + self._args_evaled = list(chain.from_iterable(self._args)) + return self._args_evaled def invoke(self): """
Handler args are dropped if called more than once per hook Because the args are implemented as generators, any time the list is evaluated after the first it ends up being empty, leading to an "missing arg" error: ``` 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined Traceback (most recent call last): 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/var/lib/juju/agents/unit-nn-0/charm/hooks/namenode-cluster-relation-joined", line 19, in <module> 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined main() 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/__init__.py", line 73, in main 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined bus.dispatch() 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/bus.py", line 418, in dispatch 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined _invoke(other_handlers) 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/bus.py", line 401, in _invoke 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined handler.invoke() 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/bus.py", line 277, in invoke 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined self._action(*args) 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined TypeError: report_status() missing 1 required positional argument: 'datanode' ```
juju-solutions/charms.reactive
diff --git a/tests/test_decorators.py b/tests/test_decorators.py index 836753a..fdbb512 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -103,6 +103,11 @@ class TestReactiveDecorators(unittest.TestCase): action.assert_called_once_with('rel') self.assertEqual(reactive.bus.Handler._CONSUMED_STATES, set(['foo', 'bar', 'qux'])) + action.reset_mock() + assert handler.test() + handler.invoke() + action.assert_called_once_with('rel') + @mock.patch.object(reactive.decorators, 'when_all') def test_when(self, when_all): @reactive.when('foo', 'bar', 'qux')
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "flake8", "ipython", "ipdb", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backcall==0.2.0 certifi==2021.5.30 charmhelpers==1.2.1 -e git+https://github.com/juju-solutions/charms.reactive.git@3540030b9b142787f3f7fd16a14ed33d18b4d7a1#egg=charms.reactive coverage==6.2 decorator==5.1.1 flake8==5.0.4 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 ipdb==0.13.13 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 MarkupSafe==2.0.1 mccabe==0.7.0 mock==5.2.0 netaddr==0.10.1 nose==1.3.7 packaging==21.3 parso==0.7.1 pbr==6.1.1 pexpect==4.9.0 pickleshare==0.7.5 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pyaml==23.5.8 pycodestyle==2.9.1 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 tomli==1.2.3 traitlets==4.3.3 typing_extensions==4.1.1 wcwidth==0.2.13 zipp==3.6.0
name: charms.reactive channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backcall==0.2.0 - charmhelpers==1.2.1 - coverage==6.2 - decorator==5.1.1 - flake8==5.0.4 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - ipdb==0.13.13 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - markupsafe==2.0.1 - mccabe==0.7.0 - mock==5.2.0 - netaddr==0.10.1 - nose==1.3.7 - packaging==21.3 - parso==0.7.1 - pbr==6.1.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pyaml==23.5.8 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - traitlets==4.3.3 - typing-extensions==4.1.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/charms.reactive
[ "tests/test_decorators.py::TestReactiveDecorators::test_when_all" ]
[]
[ "tests/test_decorators.py::TestReactiveDecorators::test_multi", "tests/test_decorators.py::TestReactiveDecorators::test_not_unless", "tests/test_decorators.py::TestReactiveDecorators::test_only_once", "tests/test_decorators.py::TestReactiveDecorators::test_when", "tests/test_decorators.py::TestReactiveDecorators::test_when_any", "tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed", "tests/test_decorators.py::TestReactiveDecorators::test_when_none", "tests/test_decorators.py::TestReactiveDecorators::test_when_not", "tests/test_decorators.py::TestReactiveDecorators::test_when_not_all" ]
[ "tests/test_decorators.py::TestReactiveDecorators::test_hook" ]
Apache License 2.0
501
nickstenning__honcho-174
5af4cf1d98926fa63eae711e6a89f8e2ef5d8539
2016-04-13 06:21:38
5af4cf1d98926fa63eae711e6a89f8e2ef5d8539
diff --git a/honcho/command.py b/honcho/command.py index 3796a39..9a7323d 100644 --- a/honcho/command.py +++ b/honcho/command.py @@ -39,6 +39,7 @@ def _add_common_args(parser, with_defaults=False): help='procfile directory (default: .)') parser.add_argument('-f', '--procfile', metavar='FILE', + default=suppress, help='procfile path (default: Procfile)') parser.add_argument('-v', '--version', action='version',
-f argument before command is suppressed System information: Mac OS X, 10.11.1 Honcho version: 0.7.0 With the latest release of honcho (0.7.0), I've noticed that the -f argument is processed properly **after** a command, but not **before** a command. -e and -d arguments don't exhibit this order-dependent behavior. Examples: ``` $ honcho -f my_procfile check 2016-04-12 23:49:22 [45546] [ERROR] Procfile does not exist or is not a file $ honcho check -f my_procfile 2016-04-12 23:49:24 [45548] [INFO] Valid procfile detected (postgres, rabbit, redis, flower) ```
nickstenning/honcho
diff --git a/tests/integration/test_start.py b/tests/integration/test_start.py index 2388bda..73c8693 100644 --- a/tests/integration/test_start.py +++ b/tests/integration/test_start.py @@ -53,6 +53,39 @@ def test_start_env_procfile(testenv): assert 'mongoose' in out [email protected]('testenv', [{ + 'Procfile': 'foo: {0} test.py'.format(python_bin), + 'Procfile.dev': 'bar: {0} test_dev.py'.format(python_bin), + 'test.py': script, + 'test_dev.py': textwrap.dedent(""" + from __future__ import print_function + print("mongoose") + """) +}], indirect=True) +def test_start_procfile_after_command(testenv): + # Regression test for #173: Ensure that -f argument can be provided after + # command + ret, out, err = testenv.run_honcho(['start', '-f', 'Procfile.dev']) + + assert 'mongoose' in out + + [email protected]('testenv', [{ + 'Procfile': 'foo: {0} test.py'.format(python_bin), + 'Procfile.dev': 'bar: {0} test_dev.py'.format(python_bin), + 'test.py': script, + 'test_dev.py': textwrap.dedent(""" + from __future__ import print_function + print("mongoose") + """) +}], indirect=True) +def test_start_procfile_before_command(testenv): + # Test case for #173: Ensure that -f argument can be provided before command + ret, out, err = testenv.run_honcho(['-f', 'Procfile.dev', 'start']) + + assert 'mongoose' in out + + @pytest.mark.parametrize('testenv', [{ 'Procfile': 'foo: {0} test.py'.format(python_bin), 'test.py': 'import sys; sys.exit(42)',
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[export]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "jinja2", "flake8" ], "pre_install": [], "python": "3.5", "reqs_path": [], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2021.5.30 flake8==5.0.4 -e git+https://github.com/nickstenning/honcho.git@5af4cf1d98926fa63eae711e6a89f8e2ef5d8539#egg=honcho importlib-metadata==4.2.0 Jinja2==2.7.3 MarkupSafe==2.0.1 mccabe==0.7.0 pycodestyle==2.9.1 pyflakes==2.5.0 typing_extensions==4.1.1 zipp==3.6.0
name: honcho channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - flake8==5.0.4 - importlib-metadata==4.2.0 - jinja2==2.7.3 - markupsafe==2.0.1 - mccabe==0.7.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/honcho
[ "tests/integration/test_start.py::test_start_procfile_before_command[testenv0]" ]
[]
[ "tests/integration/test_start.py::test_start[testenv0]", "tests/integration/test_start.py::test_start_env[testenv0]", "tests/integration/test_start.py::test_start_env_procfile[testenv0]", "tests/integration/test_start.py::test_start_procfile_after_command[testenv0]", "tests/integration/test_start.py::test_start_returncode[testenv0]" ]
[]
MIT License
502
guykisel__inline-plz-129
a7c89d5b65df2486ccf78f43fcffdc18dff76bd7
2016-04-15 01:05:40
a7c89d5b65df2486ccf78f43fcffdc18dff76bd7
raphaelcastaneda: Hmm... https://travis-ci.org/guykisel/inline-plz/jobs/123219118#L726 ` File "/home/travis/build/guykisel/inline-plz/inlineplz/linters/__init__.py", line 364, in lint linter_messages = config.get('parser')().parse(output) File "/home/travis/build/guykisel/inline-plz/inlineplz/parsers/rflint.py", line 14, in parse for line in lint_data.split('\n'): AttributeError: 'list' object has no attribute 'split'`
diff --git a/inlineplz/linters/__init__.py b/inlineplz/linters/__init__.py index 16cce9f..5cafd13 100644 --- a/inlineplz/linters/__init__.py +++ b/inlineplz/linters/__init__.py @@ -175,13 +175,13 @@ LINTERS = { 'rflint': { 'install': [['pip', 'install', 'robotframework-lint']], 'help': ['rflint', '--help'], - 'run': ['rflint', '.'], - 'rundefault': ['rflint', '-A', '{config_dir}/.rflint', '.'], + 'run': ['rflint'], + 'rundefault': ['rflint', '-A', '{config_dir}/.rflint'], 'dotfiles': ['.rflint'], 'parser': parsers.RobotFrameworkLintParser, 'language': 'robotframework', 'autorun': True, - 'run_per_file': False + 'run_per_file': True }, } diff --git a/inlineplz/parsers/rflint.py b/inlineplz/parsers/rflint.py index 56206ae..c4e8500 100644 --- a/inlineplz/parsers/rflint.py +++ b/inlineplz/parsers/rflint.py @@ -11,16 +11,17 @@ class RobotFrameworkLintParser(ParserBase): def parse(self, lint_data): messages = set() current_file = None - for line in lint_data.split('\n'): - try: - if line.startswith('+'): - current_file = line.split(' ')[1].strip() - continue - else: - _, position, message = line.split(':') - line_number, _ = position.split(',') - messages.add((current_file, int(line_number), message.strip())) - except ValueError: - pass + for _, output in lint_data: + for line in output.split('\n'): + try: + if line.startswith('+'): + current_file = line[2:] + continue + else: + _, position, message = line.split(':') + line_number, _ = position.split(',') + messages.add((current_file, int(line_number), message.strip())) + except ValueError: + pass return messages
rflint is running against all file types ``` Message: Path: node_modules/stylint/node_modules/yargs/node_modules/cliui/node_modules/wordwrap/test/idleness.txt Line number: 19 Content: set([u'rflint: Line is too long (exceeds 250 characters) (LineTooLong)']) ``` fyi @raphaelcastaneda
guykisel/inline-plz
diff --git a/tests/parsers/test_rflint.py b/tests/parsers/test_rflint.py index fcee628..7d164ea 100644 --- a/tests/parsers/test_rflint.py +++ b/tests/parsers/test_rflint.py @@ -17,7 +17,14 @@ rflint_path = os.path.join( def test_rflint(): with codecs.open(rflint_path, encoding='utf-8', errors='replace') as inputfile: - messages = sorted(list(rflint.RobotFrameworkLintParser().parse(inputfile.read()))) - assert messages[-1][2] == 'Too few steps (1) in keyword (TooFewKeywordSteps)' - assert messages[-1][1] == 30 - assert messages[-1][0] == './Functional_Requirements/keywords.robot' + test_data = inputfile.readlines() + test_filename = '' + test_input = [] + for line in test_data: + if line.startswith('+'): + test_filename = line.split(' ')[-1].strip() + test_input.append((test_filename, line)) + messages = sorted(list(rflint.RobotFrameworkLintParser().parse(test_input))) + assert messages[-1][2] == 'Too few steps (1) in keyword (TooFewKeywordSteps)' + assert messages[-1][1] == 30 + assert messages[-1][0] == './Functional_Requirements/keywords.robot'
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 cryptography==44.0.2 exceptiongroup==1.2.2 github3.py==4.0.1 idna==3.10 iniconfig==2.1.0 -e git+https://github.com/guykisel/inline-plz.git@a7c89d5b65df2486ccf78f43fcffdc18dff76bd7#egg=inlineplz packaging==24.2 pluggy==1.5.0 pycparser==2.22 PyJWT==2.10.1 pytest==8.3.5 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 scandir==1.10.0 six==1.17.0 tomli==2.2.1 unidiff==0.7.5 uritemplate==4.1.1 urllib3==2.3.0 xmltodict==0.14.2
name: inline-plz channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - cryptography==44.0.2 - exceptiongroup==1.2.2 - github3-py==4.0.1 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pycparser==2.22 - pyjwt==2.10.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - scandir==1.10.0 - six==1.17.0 - tomli==2.2.1 - unidiff==0.7.5 - uritemplate==4.1.1 - urllib3==2.3.0 - xmltodict==0.14.2 prefix: /opt/conda/envs/inline-plz
[ "tests/parsers/test_rflint.py::test_rflint" ]
[]
[]
[]
ISC License
503
pysmt__pysmt-243
2abfb4538fa93379f9b2671bce30f27967dedbcf
2016-04-15 16:24:27
2abfb4538fa93379f9b2671bce30f27967dedbcf
diff --git a/pysmt/formula.py b/pysmt/formula.py index 0a4dcd3..4fdcbfe 100644 --- a/pysmt/formula.py +++ b/pysmt/formula.py @@ -477,7 +477,7 @@ class FormulaManager(object): A -> !(B \/ C) B -> !(C) """ - args = list(*args) + args = self._polymorph_args_to_tuple(args) return self.And(self.Or(*args), self.AtMostOne(*args))
issue in processing arguments for ExactlyOne() Hi, I noticed that instantiating shortcuts.ExactlyOne() throws e.g. TypeError: list() takes at most 1 argument (3 given) at formula.py, line 480. I believe args shouldn't be unpacked in the list constructor. Martin
pysmt/pysmt
diff --git a/pysmt/test/test_formula.py b/pysmt/test/test_formula.py index 0ddbec4..924328a 100644 --- a/pysmt/test/test_formula.py +++ b/pysmt/test/test_formula.py @@ -494,6 +494,16 @@ class TestFormulaManager(TestCase): self.assertEqual(c, self.mgr.Bool(False), "ExactlyOne should not allow 2 symbols to be True") + s1 = self.mgr.Symbol("x") + s2 = self.mgr.Symbol("x") + f1 = self.mgr.ExactlyOne((s for s in [s1,s2])) + f2 = self.mgr.ExactlyOne([s1,s2]) + f3 = self.mgr.ExactlyOne(s1,s2) + + self.assertEqual(f1,f2) + self.assertEqual(f2,f3) + + @skipIfNoSolverForLogic(QF_BOOL) def test_exactly_one_is_sat(self): symbols = [ self.mgr.Symbol("s%d"%i, BOOL) for i in range(5) ] diff --git a/pysmt/test/test_regressions.py b/pysmt/test/test_regressions.py index 2fecd04..67bfc3d 100644 --- a/pysmt/test/test_regressions.py +++ b/pysmt/test/test_regressions.py @@ -311,6 +311,14 @@ class TestRegressions(TestCase): close_l = get_closer_smtlib_logic(logics.BOOL) self.assertEqual(close_l, logics.LRA) + def test_exactly_one_unpacking(self): + s1,s2 = Symbol("x"), Symbol("y") + f1 = ExactlyOne((s for s in [s1,s2])) + f2 = ExactlyOne([s1,s2]) + f3 = ExactlyOne(s1,s2) + + self.assertEqual(f1,f2) + self.assertEqual(f2,f3) if __name__ == "__main__": main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "nose", "nose-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cov-core==1.15.0 coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.7 nose-cov==1.6 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/pysmt/pysmt.git@2abfb4538fa93379f9b2671bce30f27967dedbcf#egg=PySMT pytest==8.3.5 pytest-cov==6.0.0 six==1.17.0 tomli==2.2.1
name: pysmt channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cov-core==1.15.0 - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - nose-cov==1.6 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/pysmt
[ "pysmt/test/test_formula.py::TestFormulaManager::test_exactly_one", "pysmt/test/test_regressions.py::TestRegressions::test_exactly_one_unpacking" ]
[ "pysmt/test/test_regressions.py::TestRegressions::test_parse_define_fun", "pysmt/test/test_regressions.py::TestRegressions::test_parse_define_fun_bind" ]
[ "pysmt/test/test_formula.py::TestFormulaManager::test_0arity_function", "pysmt/test/test_formula.py::TestFormulaManager::test_all_different", "pysmt/test/test_formula.py::TestFormulaManager::test_and_node", "pysmt/test/test_formula.py::TestFormulaManager::test_at_most_one", "pysmt/test/test_formula.py::TestFormulaManager::test_bconstant", "pysmt/test/test_formula.py::TestFormulaManager::test_constant", "pysmt/test/test_formula.py::TestFormulaManager::test_div_node", "pysmt/test/test_formula.py::TestFormulaManager::test_div_non_linear", "pysmt/test/test_formula.py::TestFormulaManager::test_equals", "pysmt/test/test_formula.py::TestFormulaManager::test_equals_or_iff", "pysmt/test/test_formula.py::TestFormulaManager::test_formula_in_formula_manager", "pysmt/test/test_formula.py::TestFormulaManager::test_function", "pysmt/test/test_formula.py::TestFormulaManager::test_ge_node", "pysmt/test/test_formula.py::TestFormulaManager::test_ge_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_get_or_create_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_get_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_gt_node", "pysmt/test/test_formula.py::TestFormulaManager::test_gt_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_iff_node", "pysmt/test/test_formula.py::TestFormulaManager::test_implies_node", "pysmt/test/test_formula.py::TestFormulaManager::test_infix", "pysmt/test/test_formula.py::TestFormulaManager::test_infix_extended", "pysmt/test/test_formula.py::TestFormulaManager::test_is_term", "pysmt/test/test_formula.py::TestFormulaManager::test_ite", "pysmt/test/test_formula.py::TestFormulaManager::test_le_node", "pysmt/test/test_formula.py::TestFormulaManager::test_le_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_lt_node", "pysmt/test/test_formula.py::TestFormulaManager::test_lt_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_max", "pysmt/test/test_formula.py::TestFormulaManager::test_min", "pysmt/test/test_formula.py::TestFormulaManager::test_minus_node", "pysmt/test/test_formula.py::TestFormulaManager::test_new_fresh_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_not_node", "pysmt/test/test_formula.py::TestFormulaManager::test_or_node", "pysmt/test/test_formula.py::TestFormulaManager::test_pickling", "pysmt/test/test_formula.py::TestFormulaManager::test_plus_node", "pysmt/test/test_formula.py::TestFormulaManager::test_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_times_node", "pysmt/test/test_formula.py::TestFormulaManager::test_toReal", "pysmt/test/test_formula.py::TestFormulaManager::test_typing", "pysmt/test/test_formula.py::TestFormulaManager::test_xor", "pysmt/test/test_formula.py::TestShortcuts::test_shortcut_is_using_global_env", "pysmt/test/test_regressions.py::TestRegressions::test_cnf_as_set", "pysmt/test/test_regressions.py::TestRegressions::test_dependencies_not_includes_toreal", "pysmt/test/test_regressions.py::TestRegressions::test_determinism", "pysmt/test/test_regressions.py::TestRegressions::test_empty_string_symbol", "pysmt/test/test_regressions.py::TestRegressions::test_exactlyone_w_generator", "pysmt/test/test_regressions.py::TestRegressions::test_infix_notation_wrong_le", "pysmt/test/test_regressions.py::TestRegressions::test_is_one", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_declaration_w_same_functiontype", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_exit", "pysmt/test/test_regressions.py::TestRegressions::test_qf_bool_smt2", "pysmt/test/test_regressions.py::TestRegressions::test_simplifying_int_plus_changes_type_of_expression", "pysmt/test/test_regressions.py::TestRegressions::test_smtlib_info_quoting", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_memoization", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_to_real" ]
[]
Apache License 2.0
504
pystorm__pystorm-31
506568d7033169811423a08f3af83c15abe5fd3e
2016-04-15 18:03:37
7f0d6b320e9943082bcdfd6de93d161a3b174e12
diff --git a/pystorm/bolt.py b/pystorm/bolt.py index 4e60879..c6a1538 100644 --- a/pystorm/bolt.py +++ b/pystorm/bolt.py @@ -128,7 +128,7 @@ class Bolt(Component): pass def emit(self, tup, stream=None, anchors=None, direct_task=None, - need_task_ids=True): + need_task_ids=False): """Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only @@ -146,13 +146,13 @@ class Bolt(Component): :param direct_task: the task to send the Tuple to. :type direct_task: int :param need_task_ids: indicate whether or not you'd like the task IDs - the Tuple was emitted (default: ``True``). + the Tuple was emitted (default: ``False``). :type need_task_ids: bool - :returns: a ``list`` of task IDs that the Tuple was sent to. Note that - when specifying direct_task, this will be equal to - ``[direct_task]``. If you specify ``need_task_ids=False``, - this function will return ``None``. + :returns: ``None``, unless ``need_task_ids=True``, in which case it will + be a ``list`` of task IDs that the Tuple was sent to if. Note + that when specifying direct_task, this will be equal to + ``[direct_task]``. """ if anchors is None: anchors = self._current_tups if self.auto_anchor else [] diff --git a/pystorm/component.py b/pystorm/component.py index e4b3764..757767f 100644 --- a/pystorm/component.py +++ b/pystorm/component.py @@ -364,7 +364,7 @@ class Component(object): 'level': level}) def emit(self, tup, tup_id=None, stream=None, anchors=None, - direct_task=None, need_task_ids=True): + direct_task=None, need_task_ids=False): """Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only @@ -385,13 +385,13 @@ class Component(object): :param direct_task: the task to send the Tuple to. :type direct_task: int :param need_task_ids: indicate whether or not you'd like the task IDs - the Tuple was emitted (default: ``True``). + the Tuple was emitted (default: ``False``). :type need_task_ids: bool - :returns: a ``list`` of task IDs that the Tuple was sent to. Note that - when specifying direct_task, this will be equal to - ``[direct_task]``. If you specify ``need_task_ids=False``, - this function will return ``None``. + :returns: ``None``, unless ``need_task_ids=True``, in which case it will + be a ``list`` of task IDs that the Tuple was sent to if. Note + that when specifying direct_task, this will be equal to + ``[direct_task]``. """ if not isinstance(tup, (list, tuple)): raise TypeError('All Tuples must be either lists or tuples, ' diff --git a/pystorm/spout.py b/pystorm/spout.py index 5290c9a..cc21903 100644 --- a/pystorm/spout.py +++ b/pystorm/spout.py @@ -54,7 +54,7 @@ class Spout(Component): raise NotImplementedError() def emit(self, tup, tup_id=None, stream=None, direct_task=None, - need_task_ids=True): + need_task_ids=False): """Emit a spout Tuple message. :param tup: the Tuple to send to Storm, should contain only @@ -70,14 +70,13 @@ class Spout(Component): direct emit. :type direct_task: int :param need_task_ids: indicate whether or not you'd like the task IDs - the Tuple was emitted (default: - ``True``). + the Tuple was emitted (default: ``False``). :type need_task_ids: bool - :returns: a ``list`` of task IDs that the Tuple was sent to. Note that - when specifying direct_task, this will be equal to - ``[direct_task]``. If you specify ``need_task_ids=False``, - this function will return ``None``. + :returns: ``None``, unless ``need_task_ids=True``, in which case it will + be a ``list`` of task IDs that the Tuple was sent to if. Note + that when specifying direct_task, this will be equal to + ``[direct_task]``. """ return super(Spout, self).emit(tup, tup_id=tup_id, stream=stream, direct_task=direct_task,
need_task_ids should default to False We currently default to True for backward compatibility reasons, but I would venture to guess that vast majority of users do not care about the IDs of the tasks that their emitted tuples went to. Disabling is a nice free speedup, but if we made it disabled by default, we would be cutting out extra work for most users.
pystorm/pystorm
diff --git a/test/pystorm/test_bolt.py b/test/pystorm/test_bolt.py index 277ac1a..24cb868 100644 --- a/test/pystorm/test_bolt.py +++ b/test/pystorm/test_bolt.py @@ -110,7 +110,8 @@ class BoltTests(unittest.TestCase): send_message_mock.assert_called_with(self.bolt, {'command': 'emit', 'anchors': [], 'tuple': [1, 2, 3], - 'task': 'other_bolt'}) + 'task': 'other_bolt', + 'need_task_ids': False}) @patch.object(Bolt, 'send_message', autospec=True) def test_ack_id(self, send_message_mock): diff --git a/test/pystorm/test_spout.py b/test/pystorm/test_spout.py index 2b4e1a9..a3d7a15 100644 --- a/test/pystorm/test_spout.py +++ b/test/pystorm/test_spout.py @@ -49,7 +49,8 @@ class SpoutTests(unittest.TestCase): self.spout.emit([1, 2, 3], direct_task='other_spout') send_message_mock.assert_called_with(self.spout, {'command': 'emit', 'tuple': [1, 2, 3], - 'task': 'other_spout'}) + 'task': 'other_spout', + 'need_task_ids': False}) # Reliable emit self.spout.emit([1, 2, 3], tup_id='foo', need_task_ids=False) send_message_mock.assert_called_with(self.spout, {'command': 'emit', @@ -62,7 +63,8 @@ class SpoutTests(unittest.TestCase): send_message_mock.assert_called_with(self.spout, {'command': 'emit', 'tuple': [1, 2, 3], 'task': 'other_spout', - 'id': 'foo'}) + 'id': 'foo', + 'need_task_ids': False}) @patch.object(Spout, 'read_command', autospec=True, return_value={'command': 'ack', 'id': 1234})
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 3 }
2.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mock", "pytest", "unittest2" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 linecache2==1.0.0 mock==5.2.0 msgpack-python==0.5.6 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/pystorm/pystorm.git@506568d7033169811423a08f3af83c15abe5fd3e#egg=pystorm pytest==8.3.5 pytest-timeout==2.3.1 simplejson==3.20.1 six==1.17.0 tomli==2.2.1 traceback2==1.4.0 unittest2==1.1.0
name: pystorm channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - linecache2==1.0.0 - mock==5.2.0 - msgpack-python==0.5.6 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-timeout==2.3.1 - simplejson==3.20.1 - six==1.17.0 - tomli==2.2.1 - traceback2==1.4.0 - unittest2==1.1.0 prefix: /opt/conda/envs/pystorm
[ "test/pystorm/test_bolt.py::BoltTests::test_emit_direct", "test/pystorm/test_spout.py::SpoutTests::test_emit" ]
[]
[ "test/pystorm/test_bolt.py::BoltTests::test_ack_id", "test/pystorm/test_bolt.py::BoltTests::test_ack_tuple", "test/pystorm/test_bolt.py::BoltTests::test_auto_ack_off", "test/pystorm/test_bolt.py::BoltTests::test_auto_ack_on", "test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_off", "test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_on", "test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_override", "test/pystorm/test_bolt.py::BoltTests::test_auto_fail_off", "test/pystorm/test_bolt.py::BoltTests::test_auto_fail_on", "test/pystorm/test_bolt.py::BoltTests::test_emit_basic", "test/pystorm/test_bolt.py::BoltTests::test_emit_stream_anchors", "test/pystorm/test_bolt.py::BoltTests::test_fail_id", "test/pystorm/test_bolt.py::BoltTests::test_fail_tuple", "test/pystorm/test_bolt.py::BoltTests::test_heartbeat_response", "test/pystorm/test_bolt.py::BoltTests::test_process_tick", "test/pystorm/test_bolt.py::BoltTests::test_read_tuple", "test/pystorm/test_bolt.py::BoltTests::test_read_tuple_named_fields", "test/pystorm/test_bolt.py::BoltTests::test_run", "test/pystorm/test_bolt.py::BoltTests::test_setup_component", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_off", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_on", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_off", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_on", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_partial", "test/pystorm/test_bolt.py::BatchingBoltTests::test_batching", "test/pystorm/test_bolt.py::BatchingBoltTests::test_group_key", "test/pystorm/test_bolt.py::BatchingBoltTests::test_heartbeat_response", "test/pystorm/test_bolt.py::BatchingBoltTests::test_process_tick", "test/pystorm/test_spout.py::SpoutTests::test_ack", "test/pystorm/test_spout.py::SpoutTests::test_fail", "test/pystorm/test_spout.py::SpoutTests::test_next_tuple" ]
[]
Apache License 2.0
505
falconry__falcon-755
f44fba57ef88ec9c11223c2765d49fb3573305a0
2016-04-16 22:54:49
67d61029847cbf59e4053c8a424df4f9f87ad36f
fxfitz: LGTM; needs update. jmvrbanac: :+1:
diff --git a/falcon/api.py b/falcon/api.py index 5b51de0..7957ca0 100644 --- a/falcon/api.py +++ b/falcon/api.py @@ -483,7 +483,18 @@ class API(object): path = req.path method = req.method - resource, method_map, params = self._router.find(path) + + route = self._router.find(path) + + if route is not None: + resource, method_map, params = route + else: + # NOTE(kgriffs): Older routers may indicate that no route + # was found by returning (None, None, None). Therefore, we + # normalize resource as the flag to indicate whether or not + # a route was found, for the sake of backwards-compat. + resource = None + if resource is not None: try: responder = method_map[method] @@ -491,7 +502,6 @@ class API(object): responder = falcon.responders.bad_request else: params = {} - resource = None for pattern, sink in self._sinks: m = pattern.match(path) diff --git a/falcon/routing/compiled.py b/falcon/routing/compiled.py index 9177edb..057cf6e 100644 --- a/falcon/routing/compiled.py +++ b/falcon/routing/compiled.py @@ -93,7 +93,7 @@ class CompiledRouter(object): if node is not None: return node.resource, node.method_map, params else: - return None, None, None + return None def _compile_tree(self, nodes, indent=1, level=0, fast_return=True): """Generates Python code for a routing tree or subtree."""
router.find() cannot return None Contrary to http://falcon.readthedocs.org/en/latest/api/routing.html it seems like custom routers `.find()` method cannot return None. AFAICT, `_get_responder()` unpacks `self._router.find(path)` without checking for a None return value and thus an exception occurs. However, returning `(None, None, None)` seems to work. I don't know if the docstring is wrong or the method.
falconry/falcon
diff --git a/tests/test_custom_router.py b/tests/test_custom_router.py index 8ddb824..cbe1b48 100644 --- a/tests/test_custom_router.py +++ b/tests/test_custom_router.py @@ -24,13 +24,31 @@ class TestCustomRouter(testing.TestBase): resp.body = '{"status": "ok"}' class CustomRouter(object): - def find(self, *args, **kwargs): - return resource, {'GET': resource}, {} + def __init__(self): + self.reached_backwards_compat = False - self.api = falcon.API(router=CustomRouter()) + def find(self, uri): + if uri == '/test': + return resource, {'GET': resource}, {} + + if uri == '/404/backwards-compat': + self.reached_backwards_compat = True + return (None, None, None) + + return None + + router = CustomRouter() + self.api = falcon.API(router=router) body = self.simulate_request('/test') self.assertEqual(body, [b'{"status": "ok"}']) + for uri in ('/404', '/404/backwards-compat'): + body = self.simulate_request(uri) + self.assertFalse(body) + self.assertEqual(self.srmock.status, falcon.HTTP_404) + + self.assertTrue(router.reached_backwards_compat) + def test_can_pass_additional_params_to_add_route(self): check = [] diff --git a/tests/test_default_router.py b/tests/test_default_router.py index 84af78f..dec8a8e 100644 --- a/tests/test_default_router.py +++ b/tests/test_default_router.py @@ -38,8 +38,8 @@ class TestRegressionCases(testing.TestBase): resource, method_map, params = self.router.find('/v1/messages') self.assertEqual(resource.resource_id, 2) - resource, method_map, params = self.router.find('/v1') - self.assertIs(resource, None) + route = self.router.find('/v1') + self.assertIs(route, None) def test_recipes(self): self.router.add_route( @@ -53,8 +53,8 @@ class TestRegressionCases(testing.TestBase): resource, method_map, params = self.router.find('/recipes/baking') self.assertEqual(resource.resource_id, 2) - resource, method_map, params = self.router.find('/recipes/grilling') - self.assertIs(resource, None) + route = self.router.find('/recipes/grilling') + self.assertIs(route, None) @ddt.ddt @@ -166,8 +166,8 @@ class TestComplexRouting(testing.TestBase): resource, method_map, params = self.router.find('/emojis/signs/42/small') self.assertEqual(resource.resource_id, 14.1) - resource, method_map, params = self.router.find('/emojis/signs/1/small') - self.assertEqual(resource, None) + route = self.router.find('/emojis/signs/1/small') + self.assertEqual(route, None) @ddt.data( '/teams', @@ -176,17 +176,17 @@ class TestComplexRouting(testing.TestBase): '/gists/42', ) def test_dead_segment(self, template): - resource, method_map, params = self.router.find(template) - self.assertIs(resource, None) + route = self.router.find(template) + self.assertIs(route, None) def test_malformed_pattern(self): - resource, method_map, params = self.router.find( + route = self.router.find( '/repos/racker/falcon/compare/foo') - self.assertIs(resource, None) + self.assertIs(route, None) - resource, method_map, params = self.router.find( + route = self.router.find( '/repos/racker/falcon/compare/foo/full') - self.assertIs(resource, None) + self.assertIs(route, None) def test_literal(self): resource, method_map, params = self.router.find('/user/memberships') @@ -248,12 +248,12 @@ class TestComplexRouting(testing.TestBase): '/emojis/signs/78/undefined', ) def test_not_found(self, path): - resource, method_map, params = self.router.find(path) - self.assertIs(resource, None) + route = self.router.find(path) + self.assertIs(route, None) def test_subsegment_not_found(self): - resource, method_map, params = self.router.find('/emojis/signs/0/x') - self.assertIs(resource, None) + route = self.router.find('/emojis/signs/0/x') + self.assertIs(route, None) def test_multivar(self): resource, method_map, params = self.router.find(
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "coveralls", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "tools/test-requires" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi charset-normalizer==3.4.1 coverage==6.5.0 coveralls==3.3.1 ddt==1.7.2 docopt==0.6.2 exceptiongroup==1.2.2 -e git+https://github.com/falconry/falcon.git@f44fba57ef88ec9c11223c2765d49fb3573305a0#egg=falcon idna==3.10 importlib-metadata==6.7.0 iniconfig==2.0.0 nose==1.3.7 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 python-mimeparse==1.6.0 PyYAML==6.0.1 requests==2.31.0 six==1.17.0 testtools==2.7.1 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - charset-normalizer==3.4.1 - coverage==6.5.0 - coveralls==3.3.1 - ddt==1.7.2 - docopt==0.6.2 - exceptiongroup==1.2.2 - idna==3.10 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - nose==1.3.7 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - python-mimeparse==1.6.0 - pyyaml==6.0.1 - requests==2.31.0 - six==1.17.0 - testtools==2.7.1 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/falcon
[ "tests/test_custom_router.py::TestCustomRouter::test_custom_router_find_should_be_used", "tests/test_default_router.py::TestRegressionCases::test_recipes", "tests/test_default_router.py::TestRegressionCases::test_versioned_url", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_1__teams", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_2__emojis_signs", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_3__gists", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_4__gists_42", "tests/test_default_router.py::TestComplexRouting::test_literal_segment", "tests/test_default_router.py::TestComplexRouting::test_malformed_pattern", "tests/test_default_router.py::TestComplexRouting::test_not_found_01__this_does_not_exist", "tests/test_default_router.py::TestComplexRouting::test_not_found_02__user_bogus", "tests/test_default_router.py::TestComplexRouting::test_not_found_03__repos_racker_falcon_compare_johndoe_master___janedoe_dev_bogus", "tests/test_default_router.py::TestComplexRouting::test_not_found_04__teams", "tests/test_default_router.py::TestComplexRouting::test_not_found_05__teams_42_members_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_06__teams_42_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_07__teams_42_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_08__teams_default_members_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_09__teams_default_members_thing_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_10__teams_default_members_thing_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_11__teams_default_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_12__teams_default_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_13__emojis_signs", "tests/test_default_router.py::TestComplexRouting::test_not_found_14__emojis_signs_0_small", "tests/test_default_router.py::TestComplexRouting::test_not_found_15__emojis_signs_0_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_16__emojis_signs_0_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_17__emojis_signs_20_small", "tests/test_default_router.py::TestComplexRouting::test_not_found_18__emojis_signs_20_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_19__emojis_signs_42_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_20__emojis_signs_78_undefined", "tests/test_default_router.py::TestComplexRouting::test_subsegment_not_found" ]
[]
[ "tests/test_custom_router.py::TestCustomRouter::test_can_pass_additional_params_to_add_route", "tests/test_custom_router.py::TestCustomRouter::test_custom_router_add_route_should_be_used", "tests/test_default_router.py::TestComplexRouting::test_collision_1__teams__collision_", "tests/test_default_router.py::TestComplexRouting::test_collision_2__emojis_signs__id_too_", "tests/test_default_router.py::TestComplexRouting::test_collision_3__repos__org___repo__compare__complex___vs_____complex2___collision_", "tests/test_default_router.py::TestComplexRouting::test_complex_1______5_", "tests/test_default_router.py::TestComplexRouting::test_complex_2____full___10_", "tests/test_default_router.py::TestComplexRouting::test_complex_3____part___15_", "tests/test_default_router.py::TestComplexRouting::test_complex_alt_1______16_", "tests/test_default_router.py::TestComplexRouting::test_complex_alt_2____full___17_", "tests/test_default_router.py::TestComplexRouting::test_dump", "tests/test_default_router.py::TestComplexRouting::test_literal", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_01____teams_default___19_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_02____teams_default_members___7_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_03____teams_foo___6_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_04____teams_foo_members___7_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_05____gists_first___20_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_06____gists_first_raw___18_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_07____gists_first_pdf___21_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_08____gists_1776_pdf___21_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_09____emojis_signs_78___13_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_10____emojis_signs_78_small___22_", "tests/test_default_router.py::TestComplexRouting::test_multivar", "tests/test_default_router.py::TestComplexRouting::test_non_collision_1__repos__org___repo__compare__simple_vs_complex_", "tests/test_default_router.py::TestComplexRouting::test_non_collision_2__repos__complex___vs___simple_", "tests/test_default_router.py::TestComplexRouting::test_non_collision_3__repos__org___repo__compare__complex___vs_____complex2__full", "tests/test_default_router.py::TestComplexRouting::test_override", "tests/test_default_router.py::TestComplexRouting::test_variable" ]
[]
Apache License 2.0
506
Shopify__shopify_python_api-136
a78109e725cf9e400f955062399767f36f3a1f44
2016-04-18 03:46:33
c29e0ecbed9de67dd923f980a3ac053922dab75e
diff --git a/shopify/mixins.py b/shopify/mixins.py index 9d3c179..c7806a0 100644 --- a/shopify/mixins.py +++ b/shopify/mixins.py @@ -11,8 +11,15 @@ class Countable(object): class Metafields(object): - def metafields(self): - return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id) + def metafields(self, _options=None, **kwargs): + if _options is None: + _options = kwargs + return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id, **_options) + + def metafields_count(self, _options=None, **kwargs): + if _options is None: + _options = kwargs + return int(self.get("metafields/count", **_options)) def add_metafield(self, metafield): if self.is_new():
metafields() method should be able to take options parameters for limit and page ``` import shopify product = shopify.Product.find(5972485446) metafields = product.metafields() print(len(metafields)) > 50 metafields = product.metafields(limit=250) > TypeError: metafields() got an unexpected keyword argument 'limit' ``` I looked into the code, and it seems like it may be a simple fix. If I come up with something I'll submit a pull request, if I can't I'll let it be known here so somebody else can try tackling it.
Shopify/shopify_python_api
diff --git a/test/fixtures/metafields_count.json b/test/fixtures/metafields_count.json new file mode 100644 index 0000000..a113c32 --- /dev/null +++ b/test/fixtures/metafields_count.json @@ -0,0 +1,1 @@ +{"count":2} diff --git a/test/product_test.py b/test/product_test.py index c48962a..dcc9ae7 100644 --- a/test/product_test.py +++ b/test/product_test.py @@ -28,6 +28,26 @@ class ProductTest(TestCase): for field in metafields: self.assertTrue(isinstance(field, shopify.Metafield)) + def test_get_metafields_for_product_with_params(self): + self.fake("products/632910392/metafields.json?limit=2", extension=False, body=self.load_fixture('metafields')) + + metafields = self.product.metafields(limit=2) + self.assertEqual(2, len(metafields)) + for field in metafields: + self.assertTrue(isinstance(field, shopify.Metafield)) + + def test_get_metafields_for_product_count(self): + self.fake("products/632910392/metafields/count", body=self.load_fixture('metafields_count')) + + metafields_count = self.product.metafields_count() + self.assertEqual(2, metafields_count) + + def test_get_metafields_for_product_count_with_params(self): + self.fake("products/632910392/metafields/count.json?value_type=string", extension=False, body=self.load_fixture('metafields_count')) + + metafields_count = self.product.metafields_count(value_type="string") + self.assertEqual(2, metafields_count) + def test_update_loaded_variant(self): self.fake("products/632910392/variants/808950810", method='PUT', code=200, body=self.load_fixture('variant'))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "mock>=1.0.1", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mock==5.2.0 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pyactiveresource==2.2.2 pytest @ file:///croot/pytest_1738938843180/work PyYAML==6.0.2 -e git+https://github.com/Shopify/shopify_python_api.git@a78109e725cf9e400f955062399767f36f3a1f44#egg=ShopifyAPI six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: shopify_python_api channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - mock==5.2.0 - pyactiveresource==2.2.2 - pyyaml==6.0.2 - six==1.17.0 prefix: /opt/conda/envs/shopify_python_api
[ "test/product_test.py::ProductTest::test_get_metafields_for_product_count", "test/product_test.py::ProductTest::test_get_metafields_for_product_count_with_params", "test/product_test.py::ProductTest::test_get_metafields_for_product_with_params" ]
[]
[ "test/product_test.py::ProductTest::test_add_metafields_to_product", "test/product_test.py::ProductTest::test_add_variant_to_product", "test/product_test.py::ProductTest::test_get_metafields_for_product", "test/product_test.py::ProductTest::test_update_loaded_variant" ]
[]
MIT License
507
networkx__networkx-2092
d26d5e4de3a7a7fa609f56295dd8537bccffccd9
2016-04-18 16:08:11
3f4fd85765bf2d88188cfd4c84d0707152e6cd1e
diff --git a/doc/source/reference/algorithms.rst b/doc/source/reference/algorithms.rst index e9a3b1f99..dd3958cfe 100644 --- a/doc/source/reference/algorithms.rst +++ b/doc/source/reference/algorithms.rst @@ -30,7 +30,6 @@ Algorithms algorithms.distance_regular algorithms.dominance algorithms.dominating - algorithms.efficiency algorithms.euler algorithms.flow algorithms.graphical diff --git a/networkx/algorithms/assortativity/correlation.py b/networkx/algorithms/assortativity/correlation.py index d6b34f3dc..6c56678e1 100644 --- a/networkx/algorithms/assortativity/correlation.py +++ b/networkx/algorithms/assortativity/correlation.py @@ -190,15 +190,13 @@ def numeric_assortativity_coefficient(G, attribute, nodes=None): Assortativity measures the similarity of connections in the graph with respect to the given numeric attribute. - The numeric attribute must be an integer. - + Parameters ---------- G : NetworkX graph attribute : string - Node attribute key. The corresponding attribute value must be an - integer. + Node attribute key nodes: list or iterable (optional) Compute numeric assortativity only for attributes of nodes in diff --git a/networkx/algorithms/assortativity/mixing.py b/networkx/algorithms/assortativity/mixing.py index 09886c749..2c0e4f02b 100644 --- a/networkx/algorithms/assortativity/mixing.py +++ b/networkx/algorithms/assortativity/mixing.py @@ -166,15 +166,13 @@ def degree_mixing_matrix(G, x='out', y='in', weight=None, def numeric_mixing_matrix(G,attribute,nodes=None,normalized=True): """Return numeric mixing matrix for attribute. - The attribute must be an integer. - Parameters ---------- G : graph NetworkX graph object. attribute : string - Node attribute key. The corresponding attribute must be an integer. + Node attribute key. nodes: list or iterable (optional) Build the matrix only with nodes in container. The default is all nodes. diff --git a/networkx/algorithms/community/__init__.py b/networkx/algorithms/community/__init__.py index 1d0fbbdf1..aa9a9b1a4 100644 --- a/networkx/algorithms/community/__init__.py +++ b/networkx/algorithms/community/__init__.py @@ -1,6 +1,6 @@ from networkx.algorithms.community.asyn_lpa import * from networkx.algorithms.community.centrality import * -from networkx.algorithms.community.community_generators import * +from networkx.algorithms.community.generators import * from networkx.algorithms.community.kclique import * from networkx.algorithms.community.kernighan_lin import * from networkx.algorithms.community.quality import * diff --git a/networkx/algorithms/community/community_generators.py b/networkx/algorithms/community/generators.py similarity index 100% rename from networkx/algorithms/community/community_generators.py rename to networkx/algorithms/community/generators.py diff --git a/networkx/algorithms/components/attracting.py b/networkx/algorithms/components/attracting.py index ae805903a..aa7971b7c 100644 --- a/networkx/algorithms/components/attracting.py +++ b/networkx/algorithms/components/attracting.py @@ -1,23 +1,22 @@ # -*- coding: utf-8 -*- +""" +Attracting components. +""" # Copyright (C) 2004-2016 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. -# -# Authors: Christopher Ellison -"""Attracting components.""" import networkx as nx from networkx.utils.decorators import not_implemented_for - -__all__ = ['number_attracting_components', +__authors__ = "\n".join(['Christopher Ellison']) +__all__ = ['number_attracting_components', 'attracting_components', - 'is_attracting_component', + 'is_attracting_component', 'attracting_component_subgraphs', ] - @not_implemented_for('undirected') def attracting_components(G): """Generates a list of attracting components in `G`. @@ -40,15 +39,10 @@ def attracting_components(G): attractors : generator of sets A generator of sets of nodes, one for each attracting component of G. - Raises - ------ - NetworkXNotImplemented : - If the input graph is undirected. - See Also -------- number_attracting_components - is_attracting_component + is_attracting_component attracting_component_subgraphs """ @@ -58,7 +52,6 @@ def attracting_components(G): if cG.out_degree(n) == 0: yield scc[n] - @not_implemented_for('undirected') def number_attracting_components(G): """Returns the number of attracting components in `G`. @@ -73,11 +66,6 @@ def number_attracting_components(G): n : int The number of attracting components in G. - Raises - ------ - NetworkXNotImplemented : - If the input graph is undirected. - See Also -------- attracting_components @@ -103,11 +91,6 @@ def is_attracting_component(G): attracting : bool True if `G` has a single attracting component. Otherwise, False. - Raises - ------ - NetworkXNotImplemented : - If the input graph is undirected. - See Also -------- attracting_components @@ -138,14 +121,9 @@ def attracting_component_subgraphs(G, copy=True): A list of node-induced subgraphs of the attracting components of `G`. copy : bool - If copy is True, graph, node, and edge attributes are copied to the + If copy is True, graph, node, and edge attributes are copied to the subgraphs. - Raises - ------ - NetworkXNotImplemented : - If the input graph is undirected. - See Also -------- attracting_components diff --git a/networkx/algorithms/components/biconnected.py b/networkx/algorithms/components/biconnected.py index 53a96cafc..762e10b60 100644 --- a/networkx/algorithms/components/biconnected.py +++ b/networkx/algorithms/components/biconnected.py @@ -1,19 +1,21 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2011-2016 by +""" +Biconnected components and articulation points. +""" +# Copyright (C) 2011-2013 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. -# -# Authors: Jordi Torrents ([email protected]) -# Dan Schult ([email protected]) -# Aric Hagberg ([email protected]) -"""Biconnected components and articulation points.""" from itertools import chain import networkx as nx from networkx.utils.decorators import not_implemented_for +__author__ = '\n'.join(['Jordi Torrents <[email protected]>', + 'Dan Schult <[email protected]>', + 'Aric Hagberg <[email protected]>']) + __all__ = [ 'biconnected_components', 'biconnected_component_edges', @@ -28,7 +30,7 @@ def is_biconnected(G): """Return True if the graph is biconnected, False otherwise. A graph is biconnected if, and only if, it cannot be disconnected by - removing only one node (and all edges incident on that node). If + removing only one node (and all edges incident on that node). If removing a node increases the number of disconnected components in the graph, that node is called an articulation point, or cut vertex. A biconnected graph has no articulation points. @@ -63,20 +65,16 @@ def is_biconnected(G): articulation_points biconnected_component_edges biconnected_component_subgraphs - components.is_strongly_connected - components.is_weakly_connected - components.is_connected - components.is_semiconnected Notes ----- The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach - in the DFS tree. A node `n` is an articulation point if, and only + in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of - `n` in the DFS tree. By keeping track of all the edges traversed + `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points. @@ -89,7 +87,7 @@ def is_biconnected(G): """ bcc = list(biconnected_components(G)) - if not bcc: # No bicomponents (it could be an empty graph) + if not bcc: # No bicomponents (it could be an empty graph) return False return len(bcc[0]) == len(G) @@ -101,9 +99,9 @@ def biconnected_component_edges(G): Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that node) will not disconnect the - subgraph. Note that nodes may be part of more than one biconnected - component. Those nodes are articulation points, or cut vertices. - However, each edge belongs to one, and only one, biconnected component. + subgraph. Note that nodes may be part of more than one biconnected + component. Those nodes are articulation points, or cut vertices. However, + each edge belongs to one, and only one, biconnected component. Notice that by convention a dyad is considered a biconnected component. @@ -149,10 +147,10 @@ def biconnected_component_edges(G): The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach - in the DFS tree. A node `n` is an articulation point if, and only + in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of - `n` in the DFS tree. By keeping track of all the edges traversed + `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points. @@ -176,7 +174,7 @@ def biconnected_components(G): Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected - component. Those nodes are articulation points, or cut vertices. The + component. Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number of connected components of the graph. @@ -226,9 +224,9 @@ def biconnected_components(G): See Also -------- - is_biconnected - articulation_points - biconnected_component_edges + is_biconnected, + articulation_points, + biconnected_component_edges, biconnected_component_subgraphs Notes @@ -236,10 +234,10 @@ def biconnected_components(G): The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach - in the DFS tree. A node `n` is an articulation point if, and only + in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of - `n` in the DFS tree. By keeping track of all the edges traversed + `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points. @@ -254,7 +252,6 @@ def biconnected_components(G): for comp in _biconnected_dfs(G, components=True): yield set(chain.from_iterable(comp)) - @not_implemented_for('directed') def biconnected_component_subgraphs(G, copy=True): """Return a generator of graphs, one graph for each biconnected component @@ -262,8 +259,8 @@ def biconnected_component_subgraphs(G, copy=True): Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that node) will not disconnect the - subgraph. Note that nodes may be part of more than one biconnected - component. Those nodes are articulation points, or cut vertices. The + subgraph. Note that nodes may be part of more than one biconnected + component. Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number of connected components of the graph. @@ -315,9 +312,9 @@ def biconnected_component_subgraphs(G, copy=True): See Also -------- - is_biconnected - articulation_points - biconnected_component_edges + is_biconnected, + articulation_points, + biconnected_component_edges, biconnected_components Notes @@ -325,10 +322,10 @@ def biconnected_component_subgraphs(G, copy=True): The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach - in the DFS tree. A node `n` is an articulation point if, and only + in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of - `n` in the DFS tree. By keeping track of all the edges traversed + `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points. @@ -355,7 +352,7 @@ def articulation_points(G): An articulation point or cut vertex is any node whose removal (along with all its incident edges) increases the number of connected components of - a graph. An undirected connected graph without articulation points is + a graph. An undirected connected graph without articulation points is biconnected. Articulation points belong to more than one biconnected component of a graph. @@ -392,9 +389,9 @@ def articulation_points(G): See Also -------- - is_biconnected - biconnected_components - biconnected_component_edges + is_biconnected, + biconnected_components, + biconnected_component_edges, biconnected_component_subgraphs Notes @@ -402,10 +399,10 @@ def articulation_points(G): The algorithm to find articulation points and biconnected components is implemented using a non-recursive depth-first-search (DFS) that keeps track of the highest level that back edges reach - in the DFS tree. A node `n` is an articulation point if, and only + in the DFS tree. A node `n` is an articulation point if, and only if, there exists a subtree rooted at `n` such that there is no back edge from any successor of `n` that links to a predecessor of - `n` in the DFS tree. By keeping track of all the edges traversed + `n` in the DFS tree. By keeping track of all the edges traversed by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed consecutively between articulation points. @@ -428,8 +425,8 @@ def _biconnected_dfs(G, components=True): for start in G: if start in visited: continue - discovery = {start: 0} # time of first discovery of node during search - low = {start: 0} + discovery = {start:0} # "time" of first discovery of node during search + low = {start:0} root_children = 0 visited.add(start) edge_stack = [] @@ -441,31 +438,31 @@ def _biconnected_dfs(G, components=True): if grandparent == child: continue if child in visited: - if discovery[child] <= discovery[parent]: # back edge - low[parent] = min(low[parent], discovery[child]) + if discovery[child] <= discovery[parent]: # back edge + low[parent] = min(low[parent],discovery[child]) if components: - edge_stack.append((parent, child)) + edge_stack.append((parent,child)) else: low[child] = discovery[child] = len(discovery) visited.add(child) stack.append((parent, child, iter(G[child]))) if components: - edge_stack.append((parent, child)) + edge_stack.append((parent,child)) except StopIteration: stack.pop() if len(stack) > 1: if low[parent] >= discovery[grandparent]: if components: - ind = edge_stack.index((grandparent, parent)) + ind = edge_stack.index((grandparent,parent)) yield edge_stack[ind:] - edge_stack = edge_stack[:ind] + edge_stack=edge_stack[:ind] else: yield grandparent low[grandparent] = min(low[parent], low[grandparent]) - elif stack: # length 1 so grandparent is root + elif stack: # length 1 so grandparent is root root_children += 1 if components: - ind = edge_stack.index((grandparent, parent)) + ind = edge_stack.index((grandparent,parent)) yield edge_stack[ind:] if not components: # root node is articulation point if it has more than 1 child diff --git a/networkx/algorithms/components/connected.py b/networkx/algorithms/components/connected.py index 5e90da716..dc17d34da 100644 --- a/networkx/algorithms/components/connected.py +++ b/networkx/algorithms/components/connected.py @@ -1,19 +1,20 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2004-2016 by +""" +Connected components. +""" +# Copyright (C) 2004-2013 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. -# -# Authors: Eben Kenah -# Aric Hagberg ([email protected]) -# Christopher Ellison -"""Connected components.""" import networkx as nx from networkx.utils.decorators import not_implemented_for from ...utils import arbitrary_element +__authors__ = "\n".join(['Eben Kenah', + 'Aric Hagberg <[email protected]>' + 'Christopher Ellison']) __all__ = [ 'number_connected_components', 'connected_components', @@ -37,11 +38,6 @@ def connected_components(G): comp : generator of sets A generator of sets of nodes, one for each component of G. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - Examples -------- Generate a sorted list of connected components, largest first. @@ -58,8 +54,7 @@ def connected_components(G): See Also -------- - components.strongly_connected_components - components.weakly_connected_components + strongly_connected_components Notes ----- @@ -91,11 +86,6 @@ def connected_component_subgraphs(G, copy=True): comp : generator A generator of graphs, one for each connected component of G. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - Examples -------- >>> G = nx.path_graph(4) @@ -103,15 +93,13 @@ def connected_component_subgraphs(G, copy=True): >>> graphs = list(nx.connected_component_subgraphs(G)) If you only want the largest connected component, it's more - efficient to use max instead of sort: + efficient to use max than sort. >>> Gc = max(nx.connected_component_subgraphs(G), key=len) See Also -------- connected_components - components.strongly_connected_component_subgraphs - components.weakly_connected_component_subgraphs Notes ----- @@ -142,8 +130,6 @@ def number_connected_components(G): See Also -------- connected_components - components.number_weakly_connected_components - components.number_strongly_connected_components Notes ----- @@ -167,11 +153,6 @@ def is_connected(G): connected : bool True if the graph is connected, false otherwise. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - Examples -------- >>> G = nx.path_graph(4) @@ -180,10 +161,6 @@ def is_connected(G): See Also -------- - components.is_strongly_connected - components.is_weakly_connected - components.is_semiconnected - components.is_biconnected connected_components Notes @@ -214,11 +191,6 @@ def node_connected_component(G, n): comp : set A set of nodes in the component of G containing node n. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - See Also -------- connected_components diff --git a/networkx/algorithms/components/semiconnected.py b/networkx/algorithms/components/semiconnected.py index a9766024a..07cc05dd5 100644 --- a/networkx/algorithms/components/semiconnected.py +++ b/networkx/algorithms/components/semiconnected.py @@ -1,19 +1,18 @@ # -*- coding: utf-8 -*- -# Copyright (C) 2004-2016 by -# Aric Hagberg <[email protected]> -# Dan Schult <[email protected]> -# Pieter Swart <[email protected]> -# All rights reserved. -# BSD license. -# -# Authors: ysitu ([email protected]) -"""Semiconnectedness.""" +""" +Semiconnectedness. +""" + +__author__ = """ysitu <[email protected]>""" +# Copyright (C) 2014 ysitu <[email protected]> +# All rights reserved. +# BSD license. + import networkx as nx from networkx.utils import not_implemented_for, pairwise __all__ = ['is_semiconnected'] - @not_implemented_for('undirected') def is_semiconnected(G): """Return True if the graph is semiconnected, False otherwise. @@ -34,7 +33,7 @@ def is_semiconnected(G): Raises ------ NetworkXNotImplemented : - If the input graph is undirected. + If the input graph is not directed. NetworkXPointlessConcept : If the graph is empty. @@ -50,10 +49,8 @@ def is_semiconnected(G): See Also -------- - components.is_strongly_connected - components.is_weakly_connected - components.is_connected - components.is_biconnected + is_strongly_connected, + is_weakly_connected """ if len(G) == 0: raise nx.NetworkXPointlessConcept( diff --git a/networkx/algorithms/components/strongly_connected.py b/networkx/algorithms/components/strongly_connected.py index 9fcfd1de5..98e57f5de 100644 --- a/networkx/algorithms/components/strongly_connected.py +++ b/networkx/algorithms/components/strongly_connected.py @@ -1,19 +1,20 @@ # -*- coding: utf-8 -*- +"""Strongly connected components. +""" # Copyright (C) 2004-2016 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. -# -# Authors: Eben Kenah -# Aric Hagberg ([email protected]) -# Christopher Ellison -# Ben Edwards ([email protected]) -"""Strongly connected components.""" import networkx as nx from networkx.utils.decorators import not_implemented_for +__authors__ = "\n".join(['Eben Kenah', + 'Aric Hagberg ([email protected])' + 'Christopher Ellison', + 'Ben Edwards ([email protected])']) + __all__ = ['number_strongly_connected_components', 'strongly_connected_components', 'strongly_connected_component_subgraphs', @@ -40,7 +41,7 @@ def strongly_connected_components(G): Raises ------ - NetworkXNotImplemented : + NetworkXNotImplemented: If G is undirected. Examples @@ -60,13 +61,12 @@ def strongly_connected_components(G): See Also -------- - components.connected_components - components.weakly_connected_components - kosaraju_strongly_connected_components + connected_components, + weakly_connected_components Notes ----- - Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_. + Uses Tarjan's algorithm with Nuutila's modifications. Nonrecursive version of algorithm. References @@ -157,7 +157,8 @@ def kosaraju_strongly_connected_components(G, source=None): See Also -------- - strongly_connected_components + connected_components + weakly_connected_components Notes ----- @@ -197,8 +198,8 @@ def strongly_connected_components_recursive(G): Raises ------ - NetworkXNotImplemented : - If G is undirected. + NetworkXNotImplemented: + If G is undirected Examples -------- @@ -221,7 +222,7 @@ def strongly_connected_components_recursive(G): Notes ----- - Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_. + Uses Tarjan's algorithm with Nuutila's modifications. References ---------- @@ -283,11 +284,6 @@ def strongly_connected_component_subgraphs(G, copy=True): comp : generator of graphs A generator of graphs, one for each strongly connected component of G. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - Examples -------- Generate a sorted list of strongly connected components, largest first. @@ -305,9 +301,8 @@ def strongly_connected_component_subgraphs(G, copy=True): See Also -------- - strongly_connected_components - components.connected_component_subgraphs - components.weakly_connected_component_subgraphs + connected_component_subgraphs + weakly_connected_component_subgraphs """ for comp in strongly_connected_components(G): @@ -331,16 +326,9 @@ def number_strongly_connected_components(G): n : integer Number of strongly connected components - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - See Also -------- - strongly_connected_components - components.number_connected_components - components.number_weakly_connected_components + connected_components Notes ----- @@ -363,17 +351,8 @@ def is_strongly_connected(G): connected : bool True if the graph is strongly connected, False otherwise. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - See Also -------- - components.is_weakly_connected - components.is_semiconnected - components.is_connected - components.is_biconnected strongly_connected_components Notes @@ -407,18 +386,18 @@ def condensation(G, scc=None): Returns ------- C : NetworkX DiGraph - The condensation graph C of G. The node labels are integers + The condensation graph C of G. The node labels are integers corresponding to the index of the component in the list of - strongly connected components of G. C has a graph attribute named + strongly connected components of G. C has a graph attribute named 'mapping' with a dictionary mapping the original nodes to the - nodes in C to which they belong. Each node in C also has a node + nodes in C to which they belong. Each node in C also has a node attribute 'members' with the set of original nodes in G that form the SCC that the node in C represents. Raises ------ NetworkXNotImplemented: - If G is undirected. + If G is not directed Notes ----- diff --git a/networkx/algorithms/components/weakly_connected.py b/networkx/algorithms/components/weakly_connected.py index ff2b06421..05df0166a 100644 --- a/networkx/algorithms/components/weakly_connected.py +++ b/networkx/algorithms/components/weakly_connected.py @@ -1,17 +1,19 @@ # -*- coding: utf-8 -*- +"""Weakly connected components. +""" # Copyright (C) 2004-2016 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. -# -# Authors: Aric Hagberg ([email protected]) -# Christopher Ellison -"""Weakly connected components.""" + import networkx as nx from networkx.utils.decorators import not_implemented_for +__authors__ = "\n".join(['Aric Hagberg ([email protected])' + 'Christopher Ellison']) + __all__ = [ 'number_weakly_connected_components', 'weakly_connected_components', @@ -35,11 +37,6 @@ def weakly_connected_components(G): A generator of sets of nodes, one for each weakly connected component of G. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - Examples -------- Generate a sorted list of weakly connected components, largest first. @@ -51,14 +48,13 @@ def weakly_connected_components(G): [4, 3] If you only want the largest component, it's more efficient to - use max instead of sort: + use max instead of sort. >>> largest_cc = max(nx.weakly_connected_components(G), key=len) See Also -------- - components.connected_components - components.strongly_connected_components + strongly_connected_components Notes ----- @@ -87,16 +83,9 @@ def number_weakly_connected_components(G): n : integer Number of weakly connected components - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - See Also -------- - weakly_connected_components - components.number_connected_components - components.number_strongly_connected_components + connected_components Notes ----- @@ -123,11 +112,6 @@ def weakly_connected_component_subgraphs(G, copy=True): comp : generator A generator of graphs, one for each weakly connected component of G. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - Examples -------- Generate a sorted list of weakly connected components, largest first. @@ -139,15 +123,14 @@ def weakly_connected_component_subgraphs(G, copy=True): [4, 3] If you only want the largest component, it's more efficient to - use max instead of sort: + use max instead of sort. >>> Gc = max(nx.weakly_connected_component_subgraphs(G), key=len) See Also -------- - weakly_connected_components - components.strongly_connected_component_subgraphs - components.connected_component_subgraphs + strongly_connected_components + connected_components Notes ----- @@ -179,18 +162,11 @@ def is_weakly_connected(G): connected : bool True if the graph is weakly connected, False otherwise. - Raises - ------ - NetworkXNotImplemented: - If G is undirected. - See Also -------- - components.is_strongly_connected - components.is_semiconnected - components.is_connected - components.is_biconnected - weakly_connected_components + is_strongly_connected + is_semiconnected + is_connected Notes ----- diff --git a/networkx/algorithms/dominance.py b/networkx/algorithms/dominance.py index 0f0901e21..9d3b84375 100644 --- a/networkx/algorithms/dominance.py +++ b/networkx/algorithms/dominance.py @@ -126,17 +126,12 @@ def dominance_frontiers(G, start): """ idom = nx.immediate_dominators(G, start) - df = {u: [] for u in idom} - + df = {u: set() for u in idom} for u in idom: - if len(G.pred[u]) - int(u in G.pred[u]) >= 2: - p = set() + if len(G.pred[u]) >= 2: for v in G.pred[u]: - while v != idom[u] and v not in p: - p.add(v) - v = idom[v] - p.discard(u) - for v in p: - df[v].append(u) - + if v in idom: + while v != idom[u]: + df[v].add(u) + v = idom[v] return df diff --git a/networkx/generators/geometric.py b/networkx/generators/geometric.py index 02b3740fb..516fb4f4d 100644 --- a/networkx/generators/geometric.py +++ b/networkx/generators/geometric.py @@ -60,9 +60,9 @@ def random_geometric_graph(n, radius, dim=2, pos=None, metric=None): A metric on vectors of numbers (represented as lists or tuples). This must be a function that accepts two lists (or tuples) as input and yields a number as output. The function - must also satisfy the four requirements of a `metric`_. - Specifically, if *d* is the function and *x*, *y*, - and *z* are vectors in the graph, then *d* must satisfy + must also satisfy the four requirements of a + `metric`_. Specifically, if *d* is the function and *x*, *y*, + and *x* are vectors in the graph, then *d* must satisfy 1. *d*(*x*, *y*) ≥ 0, 2. *d*(*x*, *y*) = 0 if and only if *x* = *y*, @@ -72,7 +72,7 @@ def random_geometric_graph(n, radius, dim=2, pos=None, metric=None): If this argument is not specified, the Euclidean distance metric is used. - .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29 + .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29 Returns ------- @@ -193,9 +193,9 @@ def geographical_threshold_graph(n, theta, alpha=2, dim=2, pos=None, A metric on vectors of numbers (represented as lists or tuples). This must be a function that accepts two lists (or tuples) as input and yields a number as output. The function - must also satisfy the four requirements of a `metric`_. - Specifically, if *d* is the function and *x*, *y*, - and *z* are vectors in the graph, then *d* must satisfy + must also satisfy the four requirements of a + `metric`_. Specifically, if *d* is the function and *x*, *y*, + and *x* are vectors in the graph, then *d* must satisfy 1. *d*(*x*, *y*) ≥ 0, 2. *d*(*x*, *y*) = 0 if and only if *x* = *y*, @@ -205,7 +205,7 @@ def geographical_threshold_graph(n, theta, alpha=2, dim=2, pos=None, If this argument is not specified, the Euclidean distance metric is used. - .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29 + .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29 Returns ------- @@ -326,9 +326,9 @@ def waxman_graph(n, alpha=0.4, beta=0.1, L=None, domain=(0, 0, 1, 1), A metric on vectors of numbers (represented as lists or tuples). This must be a function that accepts two lists (or tuples) as input and yields a number as output. The function - must also satisfy the four requirements of a `metric`_. - Specifically, if *d* is the function and *x*, *y*, - and *z* are vectors in the graph, then *d* must satisfy + must also satisfy the four requirements of a + `metric`_. Specifically, if *d* is the function and *x*, *y*, + and *x* are vectors in the graph, then *d* must satisfy 1. *d*(*x*, *y*) ≥ 0, 2. *d*(*x*, *y*) = 0 if and only if *x* = *y*, @@ -338,7 +338,7 @@ def waxman_graph(n, alpha=0.4, beta=0.1, L=None, domain=(0, 0, 1, 1), If this argument is not specified, the Euclidean distance metric is used. - .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29 + .. _metric: https://en.wikipedia.org/wiki/Metric_%28mathematics%29 Returns -------
Possible bug in dominance package While working with ```dominance_frontiers``` algorithm I have noticed some strange line of code, which I think leads to incorrect results. My question is: why try to discard element ```u```? ``` p.discard(u) ``` Given the following example it produces wrong results. ``` import networkx as nx from networkx.algorithms.dominance import * g = nx.DiGraph() g.add_edges_from([ ('b0','b1'), ('b1', 'b2'), ('b2', 'b3'), ('b3','b1'), ('b1','b5'), ('b5', 'b6'), ('b5', 'b8'), ('b6', 'b7'), ('b8', 'b7'), ('b7', 'b3'), ('b3', 'b4') ] df = dominance_frontiers(g, 'b0') print df ``` It yields: ``` {'b0': [], 'b1': [], 'b2': ['b3'], 'b3': ['b1'], 'b4': [], 'b5': ['b3'], 'b6': ['b7'], 'b7': ['b3'], 'b8': ['b7']} ``` However, I expect to see ```b1``` in ```df[b1]```, as if I use general algorithm for ```b1```, while parsing its predecessors, ```b1``` itself will be passed before its immediate dominator ```b0```, so it should be added to ```df[b1]```.
networkx/networkx
diff --git a/networkx/algorithms/tests/test_dominance.py b/networkx/algorithms/tests/test_dominance.py index 94bd80468..4ce020f6c 100644 --- a/networkx/algorithms/tests/test_dominance.py +++ b/networkx/algorithms/tests/test_dominance.py @@ -99,28 +99,28 @@ class TestDominanceFrontiers(object): def test_singleton(self): G = nx.DiGraph() G.add_node(0) - assert_equal(nx.dominance_frontiers(G, 0), {0: []}) + assert_equal(nx.dominance_frontiers(G, 0), {0: set()}) G.add_edge(0, 0) - assert_equal(nx.dominance_frontiers(G, 0), {0: []}) + assert_equal(nx.dominance_frontiers(G, 0), {0: set()}) def test_path(self): n = 5 G = nx.path_graph(n, create_using=nx.DiGraph()) assert_equal(nx.dominance_frontiers(G, 0), - {i: [] for i in range(n)}) + {i: set() for i in range(n)}) def test_cycle(self): n = 5 G = nx.cycle_graph(n, create_using=nx.DiGraph()) assert_equal(nx.dominance_frontiers(G, 0), - {i: [] for i in range(n)}) + {i: set() for i in range(n)}) def test_unreachable(self): n = 5 assert_greater(n, 1) G = nx.path_graph(n, create_using=nx.DiGraph()) assert_equal(nx.dominance_frontiers(G, n // 2), - {i: [] for i in range(n // 2, n)}) + {i: set() for i in range(n // 2, n)}) def test_irreducible1(self): # Graph taken from Figure 2 of @@ -129,9 +129,11 @@ class TestDominanceFrontiers(object): # Software Practice & Experience, 4:110, 2001. edges = [(1, 2), (2, 1), (3, 2), (4, 1), (5, 3), (5, 4)] G = nx.DiGraph(edges) - assert_equal({u: sorted(df) + assert_equal({u: df for u, df in nx.dominance_frontiers(G, 5).items()}, - {1: [2], 2: [1], 3: [2], 4: [1], 5: []}) + {1: set([2]), 2: set([1]), 3: set([2]), + 4: set([1]), 5: set()}) + def test_irreducible2(self): # Graph taken from Figure 4 of @@ -142,18 +144,21 @@ class TestDominanceFrontiers(object): (6, 4), (6, 5)] G = nx.DiGraph(edges) assert_equal(nx.dominance_frontiers(G, 6), - {1: [2], 2: [1, 3], 3: [2], 4: [2, 3], 5: [1], 6: []}) + {1: set([2]), 2: set([1, 3]), 3: set([2]), 4: set([2, 3]) + , 5: set([1]), 6: set([])}) def test_domrel_png(self): # Graph taken from https://commons.wikipedia.org/wiki/File:Domrel.png edges = [(1, 2), (2, 3), (2, 4), (2, 6), (3, 5), (4, 5), (5, 2)] G = nx.DiGraph(edges) assert_equal(nx.dominance_frontiers(G, 1), - {1: [], 2: [], 3: [5], 4: [5], 5: [2], 6: []}) + {1: set([]), 2: set([2]), 3: set([5]), 4: set([5]), + 5: set([2]), 6: set()}) # Test postdominance. with nx.utils.reversed(G): assert_equal(nx.dominance_frontiers(G, 6), - {1: [], 2: [], 3: [2], 4: [2], 5: [2], 6: []}) + {1: set(), 2: set([2]), 3: set([2]), 4: set([2]), + 5: set([2]), 6: set()}) def test_boost_example(self): # Graph taken from Figure 1 of @@ -162,10 +167,97 @@ class TestDominanceFrontiers(object): (5, 7), (6, 4)] G = nx.DiGraph(edges) assert_equal(nx.dominance_frontiers(G, 0), - {0: [], 1: [], 2: [7], 3: [7], 4: [7], 5: [7], 6: [4], - 7: []}) + {0: set(), 1: set(), 2: set([7]), 3: set([7]), + 4: set([4,7]), 5: set([7]), 6: set([4]), 7: set()}) # Test postdominance. with nx.utils.reversed(G): assert_equal(nx.dominance_frontiers(G, 7), - {0: [], 1: [], 2: [1], 3: [1], 4: [1], 5: [1], 6: [4], - 7: []}) + {0: set(), 1: set(), 2: set([1]), 3: set([1]), + 4: set([1,4]), 5: set([1]), 6: set([4]), 7: set()}) + + + def test_discard_issue(self): + # https://github.com/networkx/networkx/issues/2071 + g = nx.DiGraph() + g.add_edges_from([ + ('b0','b1'), + ('b1', 'b2'), + ('b2', 'b3'), + ('b3','b1'), + ('b1','b5'), + ('b5', 'b6'), + ('b5', 'b8'), + ('b6', 'b7'), + ('b8', 'b7'), + ('b7', 'b3'), + ('b3', 'b4') + ] + ) + df = nx.dominance_frontiers(g, 'b0') + assert_equal(df, {'b4': set(), 'b5': set(['b3']), 'b6': set(['b7']), + 'b7': set(['b3']), + 'b0': set(), 'b1': set(['b1']), 'b2': set(['b3']), + 'b3': set(['b1']), 'b8': set(['b7'])}) + + def test_loop(self): + g = nx.DiGraph() + g.add_edges_from([('a','b'),('b','c'),('b','a')]) + df = nx.dominance_frontiers(g, 'a') + assert_equal(df, {'a': set(), 'b': set(), 'c': set()}) + + def test_missing_immediate_doms(self): + # see https://github.com/networkx/networkx/issues/2070 + g = nx.DiGraph() + edges = [ + ('entry_1', 'b1'), + ('b1', 'b2'), + ('b2', 'b3'), + ('b3', 'exit'), + ('entry_2', 'b3') + ] + + # entry_1 + # | + # b1 + # | + # b2 entry_2 + # | / + # b3 + # | + # exit + + g.add_edges_from(edges) + # formerly raised KeyError on entry_2 when parsing b3 + # because entry_2 does not have immediate doms (no path) + nx.dominance_frontiers(g,'entry_1') + + def test_loops_larger(self): + # from + # http://ecee.colorado.edu/~waite/Darmstadt/motion.html + g = nx.DiGraph() + edges = [ + ('entry', 'exit'), + ('entry', '1'), + ('1', '2'), + ('2', '3'), + ('3', '4'), + ('4', '5'), + ('5', '6'), + ('6', 'exit'), + ('6', '2'), + ('5', '3'), + ('4', '4') + ] + + g.add_edges_from(edges) + df = nx.dominance_frontiers(g,'entry') + answer = {'entry': set(), + '1': set(['exit']), + '2': set(['exit', '2']), + '3': set(['exit', '3', '2']), + '4': set(['exit', '4','3', '2']), + '5': set(['exit', '3', '2']), + '6': set(['exit', '2']), + 'exit': set()} + for n in df: + assert_equal(set(df[n]),set(answer[n]))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 12 }
help
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libgdal-dev graphviz" ], "python": "3.6", "reqs_path": [ "requirements/default.txt", "requirements/test.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 decorator==5.1.1 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/networkx/networkx.git@d26d5e4de3a7a7fa609f56295dd8537bccffccd9#egg=networkx nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: networkx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - decorator==5.1.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/networkx
[ "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_singleton", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_path", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_cycle", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_unreachable", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_irreducible1", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_irreducible2", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_domrel_png", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_boost_example", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_discard_issue", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_loop", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_missing_immediate_doms", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_loops_larger" ]
[]
[ "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_exceptions", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_singleton", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_path", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_cycle", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_unreachable", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_irreducible1", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_irreducible2", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_domrel_png", "networkx/algorithms/tests/test_dominance.py::TestImmediateDominators::test_boost_example", "networkx/algorithms/tests/test_dominance.py::TestDominanceFrontiers::test_exceptions" ]
[]
BSD 3-Clause
508
zalando-stups__zign-14
46f296b8952b518c9f93d398ef890d5d4001a37a
2016-04-19 17:40:40
e2641d7972e25769830f527c1bd81f6729f4d3ea
diff --git a/zign/api.py b/zign/api.py index d98ed9a..065afae 100644 --- a/zign/api.py +++ b/zign/api.py @@ -100,6 +100,11 @@ def get_named_token(scope, realm, name, user, password, url=None, if existing_token: return existing_token + if name and not realm: + access_token = get_service_token(name, scope) + if access_token: + return {'access_token': access_token} + config = get_config() url = url or config.get('url') @@ -153,6 +158,21 @@ def is_user_scope(scope: str): return scope in set(['uid', 'cn']) +def get_service_token(name: str, scopes: list): + '''Get service token (tokens lib) if possible, otherwise return None''' + tokens.manage(name, scopes) + try: + access_token = tokens.get(name) + except tokens.ConfigurationError: + # will be thrown if configuration is missing (e.g. OAUTH2_ACCESS_TOKEN_URL) + access_token = None + except tokens.InvalidCredentialsError: + # will be thrown if $CREDENTIALS_DIR/*.json cannot be read + access_token = None + + return access_token + + def get_token(name: str, scopes: list): '''Get an OAuth token, either from Token Service or directly from OAuth provider (using the Python tokens library)''' @@ -163,14 +183,7 @@ def get_token(name: str, scopes: list): if token: return token['access_token'] - tokens.manage(name, scopes) - try: - access_token = tokens.get(name) - except tokens.ConfigurationError: - access_token = None - except tokens.InvalidCredentialsError: - access_token = None - + access_token = get_service_token(name, scopes) if access_token: return access_token
Transparently get service tokens via "tokens" library if possible We already have the `zign.api.get_token` function and we should consider getting service tokens transparently also when using `zign token` directly.
zalando-stups/zign
diff --git a/tests/test_api.py b/tests/test_api.py index ad3cc20..e6e2f6c 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,4 +1,5 @@ import pytest +import time import tokens import zign.api @@ -72,3 +73,18 @@ def test_get_token_fallback_success(monkeypatch): monkeypatch.setattr('zign.api.get_new_token', lambda *args, **kwargs: {'access_token': 'tt77'}) assert zign.api.get_token('mytok', ['myscope']) == 'tt77' + + +def test_get_named_token_existing(monkeypatch): + existing = {'mytok': {'access_token': 'tt77', 'creation_time': time.time() - 10, 'expires_in': 3600}} + monkeypatch.setattr('zign.api.get_tokens', lambda: existing) + tok = zign.api.get_named_token(scope=['myscope'], realm=None, name='mytok', user='myusr', password='mypw') + assert tok['access_token'] == 'tt77' + + +def test_get_named_token_services(monkeypatch): + response = MagicMock(status_code=401) + monkeypatch.setattr('requests.get', MagicMock(return_value=response)) + monkeypatch.setattr('tokens.get', lambda x: 'svcmytok123') + tok = zign.api.get_named_token(scope=['myscope'], realm=None, name='mytok', user='myusr', password='mypw') + assert tok['access_token'] == 'svcmytok123'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
backports.tarfile==1.2.0 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 click==8.1.8 clickclick==20.10.2 coverage==7.8.0 cryptography==44.0.2 dnspython==2.7.0 exceptiongroup==1.2.2 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jeepney==0.9.0 keyring==25.6.0 keyrings.alt==5.0.2 more-itertools==10.6.0 packaging==24.2 pluggy==1.5.0 pycparser==2.22 pytest==8.3.5 pytest-cov==6.0.0 PyYAML==6.0.2 requests==2.32.3 SecretStorage==3.3.3 stups-cli-support==1.1.22 stups-tokens==1.1.19 -e git+https://github.com/zalando-stups/zign.git@46f296b8952b518c9f93d398ef890d5d4001a37a#egg=stups_zign tomli==2.2.1 urllib3==2.3.0 zipp==3.21.0
name: zign channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - backports-tarfile==1.2.0 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - click==8.1.8 - clickclick==20.10.2 - coverage==7.8.0 - cryptography==44.0.2 - dnspython==2.7.0 - exceptiongroup==1.2.2 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jeepney==0.9.0 - keyring==25.6.0 - keyrings-alt==5.0.2 - more-itertools==10.6.0 - packaging==24.2 - pluggy==1.5.0 - pycparser==2.22 - pytest==8.3.5 - pytest-cov==6.0.0 - pyyaml==6.0.2 - requests==2.32.3 - secretstorage==3.3.3 - stups-cli-support==1.1.22 - stups-tokens==1.1.19 - tomli==2.2.1 - urllib3==2.3.0 - zipp==3.21.0 prefix: /opt/conda/envs/zign
[ "tests/test_api.py::test_get_named_token_services" ]
[ "tests/test_api.py::test_get_new_token_auth_fail", "tests/test_api.py::test_get_new_token_server_error" ]
[ "tests/test_api.py::test_get_new_token_invalid_json", "tests/test_api.py::test_get_new_token_missing_access_token", "tests/test_api.py::test_get_token_existing", "tests/test_api.py::test_get_token_configuration_error", "tests/test_api.py::test_get_token_service_success", "tests/test_api.py::test_get_token_fallback_success", "tests/test_api.py::test_get_named_token_existing" ]
[]
Apache License 2.0
509
PyCQA__pycodestyle-499
eae54ff0e4c50ccc4507e95a2f8689fefb89e70e
2016-04-20 13:29:51
4f5d398f9256727ad8fd7f67c45ea60a8fad5a4a
IanLee1521: Can you also update the error list page in the docs to say this is in the default list?
diff --git a/docs/intro.rst b/docs/intro.rst index e26daf7..2ce1eb6 100644 --- a/docs/intro.rst +++ b/docs/intro.rst @@ -392,7 +392,7 @@ This is the current list of error and warning codes: +------------+----------------------------------------------------------------------+ | **W5** | *Line break warning* | +------------+----------------------------------------------------------------------+ -| W503 | line break occurred before a binary operator | +| W503 (*) | line break occurred before a binary operator | +------------+----------------------------------------------------------------------+ +------------+----------------------------------------------------------------------+ | **W6** | *Deprecation warning* | diff --git a/pep8.py b/pep8.py index 8ec21e1..499c370 100755 --- a/pep8.py +++ b/pep8.py @@ -65,7 +65,7 @@ except ImportError: __version__ = '1.8.0-dev' DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git,__pycache__,.tox' -DEFAULT_IGNORE = 'E121,E123,E126,E226,E24,E704' +DEFAULT_IGNORE = 'E121,E123,E126,E226,E24,E704,W503' try: if sys.platform == 'win32': USER_CONFIG = os.path.expanduser(r'~\.pep8')
Update handling of breaking around binary operators: W503 vs W504 Based on the discussion that started on python-dev [1] and ended with an update to PEP-8 [2][3], the logic for allowing (preferring really) breaks to occur before rather than after binary operators. [1] https://mail.python.org/pipermail/python-ideas/2016-April/039774.html [2] http://bugs.python.org/issue26763 [3] https://hg.python.org/peps/rev/3857909d7956
PyCQA/pycodestyle
diff --git a/testsuite/test_api.py b/testsuite/test_api.py index 1cb0d4b..0b83c4e 100644 --- a/testsuite/test_api.py +++ b/testsuite/test_api.py @@ -181,7 +181,7 @@ class APITestCase(unittest.TestCase): self.assertEqual(options.select, ()) self.assertEqual( options.ignore, - ('E121', 'E123', 'E126', 'E226', 'E24', 'E704') + ('E121', 'E123', 'E126', 'E226', 'E24', 'E704', 'W503') ) options = parse_argv('--doctest').options
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "tox", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cachetools==5.5.2 chardet==5.2.0 colorama==0.4.6 distlib==0.3.9 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work -e git+https://github.com/PyCQA/pycodestyle.git@eae54ff0e4c50ccc4507e95a2f8689fefb89e70e#egg=pep8 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pyproject-api==1.9.0 pytest @ file:///croot/pytest_1738938843180/work tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 virtualenv==20.30.0
name: pycodestyle channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cachetools==5.5.2 - chardet==5.2.0 - colorama==0.4.6 - distlib==0.3.9 - filelock==3.18.0 - platformdirs==4.3.7 - pyproject-api==1.9.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - virtualenv==20.30.0 prefix: /opt/conda/envs/pycodestyle
[ "testsuite/test_api.py::APITestCase::test_styleguide_ignore_code" ]
[]
[ "testsuite/test_api.py::APITestCase::test_check_nullbytes", "testsuite/test_api.py::APITestCase::test_check_unicode", "testsuite/test_api.py::APITestCase::test_register_ast_check", "testsuite/test_api.py::APITestCase::test_register_invalid_check", "testsuite/test_api.py::APITestCase::test_register_logical_check", "testsuite/test_api.py::APITestCase::test_register_physical_check", "testsuite/test_api.py::APITestCase::test_styleguide", "testsuite/test_api.py::APITestCase::test_styleguide_check_files", "testsuite/test_api.py::APITestCase::test_styleguide_checks", "testsuite/test_api.py::APITestCase::test_styleguide_continuation_line_outdented", "testsuite/test_api.py::APITestCase::test_styleguide_excluded", "testsuite/test_api.py::APITestCase::test_styleguide_init_report", "testsuite/test_api.py::APITestCase::test_styleguide_options", "testsuite/test_api.py::APITestCase::test_styleguide_unmatched_triple_quotes" ]
[]
Expat License
510
dask__dask-1113
6e7fea680dc7eaf6f96452e00625e0466c110532
2016-04-22 23:07:23
71e3e413d6e00942de3ff32a3ba378408f2648e9
diff --git a/dask/array/core.py b/dask/array/core.py index b85b5c2c0..a6e10cc55 100644 --- a/dask/array/core.py +++ b/dask/array/core.py @@ -1377,6 +1377,12 @@ class Array(Base): out._chunks = chunks return out + def copy(self): + """ + Copy array. This is a no-op for dask.arrays, which are immutable + """ + return self + def to_imperative(self): """ Convert Array into dask Values
Add a dummy .copy() method on dask arrays? There's no need to copy the data in dask arrays, because they're (currently) immutable. Still, it's common to copy numpy arrays to be on the safe side, so it might be nice to add this for duck-array compatibility.
dask/dask
diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py index f75b85ee5..1351bff05 100644 --- a/dask/array/tests/test_array_core.py +++ b/dask/array/tests/test_array_core.py @@ -2003,3 +2003,8 @@ def test_atop_names(): def test_A_property(): x = da.ones(5, chunks=(2,)) assert x.A is x + + +def test_copy(): + x = da.ones(5, chunks=(2,)) + assert x.copy() is x
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 pandas>=1.0.0 cloudpickle partd distributed s3fs toolz psutil pytables bokeh bcolz scipy h5py ipython", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz liblzma-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore @ file:///opt/conda/conda-bld/aiobotocore_1643638228694/work aiohttp @ file:///tmp/build/80754af9/aiohttp_1632748060317/work aioitertools @ file:///tmp/build/80754af9/aioitertools_1607109665762/work async-timeout==3.0.1 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work bcolz==1.2.1 bokeh @ file:///tmp/build/80754af9/bokeh_1620710048147/work boto3==1.23.10 botocore==1.26.10 brotlipy==0.7.0 certifi==2021.5.30 cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work chardet @ file:///tmp/build/80754af9/chardet_1607706739153/work click==8.0.3 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1632508026186/work contextvars==2.4 cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work cytoolz==0.11.0 -e git+https://github.com/dask/dask.git@6e7fea680dc7eaf6f96452e00625e0466c110532#egg=dask decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work distributed==1.9.5 fsspec @ file:///opt/conda/conda-bld/fsspec_1642510437511/work h5py==2.10.0 HeapDict @ file:///Users/ktietz/demo/mc3/conda-bld/heapdict_1630598515714/work idna @ file:///tmp/build/80754af9/idna_1637925883363/work idna-ssl @ file:///tmp/build/80754af9/idna_ssl_1611752490495/work immutables @ file:///tmp/build/80754af9/immutables_1628888996840/work importlib-metadata==4.8.3 iniconfig==1.1.1 ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work jmespath @ file:///Users/ktietz/demo/mc3/conda-bld/jmespath_1630583964805/work locket==0.2.1 MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work mock @ file:///tmp/build/80754af9/mock_1607622725907/work msgpack @ file:///tmp/build/80754af9/msgpack-python_1612287171716/work msgpack-python==0.5.6 multidict @ file:///tmp/build/80754af9/multidict_1607367768400/work numexpr @ file:///tmp/build/80754af9/numexpr_1618853194344/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 parso==0.7.0 partd @ file:///opt/conda/conda-bld/partd_1647245470509/work pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work pluggy==1.0.0 prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work psutil @ file:///tmp/build/80754af9/psutil_1612297621795/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl py==1.11.0 pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work pytest==7.0.1 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work pytz==2021.3 PyYAML==5.4.1 s3fs==0.4.2 s3transfer==0.5.2 scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work six @ file:///tmp/build/80754af9/six_1644875935023/work sortedcontainers @ file:///tmp/build/80754af9/sortedcontainers_1623949099177/work tables==3.6.1 tblib @ file:///Users/ktietz/demo/mc3/conda-bld/tblib_1629402031467/work tomli==1.2.3 toolz @ file:///tmp/build/80754af9/toolz_1636545406491/work tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work wrapt==1.12.1 yarl @ file:///tmp/build/80754af9/yarl_1606939915466/work zict==2.0.0 zipp==3.6.0
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - aiobotocore=2.1.0=pyhd3eb1b0_0 - aiohttp=3.7.4.post0=py36h7f8727e_2 - aioitertools=0.7.1=pyhd3eb1b0_0 - async-timeout=3.0.1=py36h06a4308_0 - attrs=21.4.0=pyhd3eb1b0_0 - backcall=0.2.0=pyhd3eb1b0_0 - bcolz=1.2.1=py36h04863e7_0 - blas=1.0=openblas - blosc=1.21.3=h6a678d5_0 - bokeh=2.3.2=py36h06a4308_0 - brotlipy=0.7.0=py36h27cfd23_1003 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - cffi=1.14.6=py36h400218f_0 - chardet=4.0.0=py36h06a4308_1003 - click=8.0.3=pyhd3eb1b0_0 - cloudpickle=2.0.0=pyhd3eb1b0_0 - contextvars=2.4=py_0 - cryptography=35.0.0=py36hd23ed53_0 - cytoolz=0.11.0=py36h7b6447c_0 - decorator=5.1.1=pyhd3eb1b0_0 - freetype=2.12.1=h4a9f257_0 - fsspec=2022.1.0=pyhd3eb1b0_0 - giflib=5.2.2=h5eee18b_0 - h5py=2.10.0=py36h7918eee_0 - hdf5=1.10.4=hb1b8bf9_0 - heapdict=1.0.1=pyhd3eb1b0_0 - idna=3.3=pyhd3eb1b0_0 - idna_ssl=1.1.0=py36h06a4308_0 - immutables=0.16=py36h7f8727e_0 - ipython=7.16.1=py36h5ca1d4c_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.17.2=py36h06a4308_1 - jinja2=3.0.3=pyhd3eb1b0_0 - jmespath=0.10.0=pyhd3eb1b0_0 - jpeg=9e=h5eee18b_3 - lcms2=2.16=hb9589c4_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h6a678d5_0 - libdeflate=1.22=h5eee18b_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtiff=4.5.1=hffd6297_1 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - locket=0.2.1=py36h06a4308_1 - lz4-c=1.9.4=h6a678d5_1 - lzo=2.10=h7b6447c_2 - markupsafe=2.0.1=py36h27cfd23_0 - mock=4.0.3=pyhd3eb1b0_0 - multidict=5.1.0=py36h27cfd23_2 - ncurses=6.4=h6a678d5_0 - numexpr=2.7.3=py36h4be448d_1 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pandas=1.1.5=py36ha9443f7_0 - parso=0.7.0=py_0 - partd=1.2.0=pyhd3eb1b0_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pillow=8.3.1=py36h5aabda8_0 - pip=21.2.2=py36h06a4308_0 - prompt-toolkit=3.0.20=pyhd3eb1b0_0 - psutil=5.8.0=py36h27cfd23_1 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.11.2=pyhd3eb1b0_0 - pyopenssl=22.0.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pysocks=1.7.1=py36h06a4308_0 - pytables=3.6.1=py36h71ec239_0 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytz=2021.3=pyhd3eb1b0_0 - pyyaml=5.4.1=py36h27cfd23_1 - readline=8.2=h5eee18b_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sortedcontainers=2.4.0=pyhd3eb1b0_0 - sqlite=3.45.3=h5eee18b_0 - tblib=1.7.0=pyhd3eb1b0_0 - tk=8.6.14=h39e8969_0 - toolz=0.11.2=pyhd3eb1b0_0 - tornado=6.1=py36h27cfd23_0 - traitlets=4.3.3=py36h06a4308_0 - typing-extensions=4.1.1=hd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - urllib3=1.26.8=pyhd3eb1b0_0 - wcwidth=0.2.5=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - wrapt=1.12.1=py36h7b6447c_1 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - yarl=1.6.3=py36h27cfd23_0 - zict=2.0.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - zstd=1.5.6=hc292b87_0 - pip: - boto3==1.23.10 - botocore==1.26.10 - distributed==1.9.5 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - msgpack-python==0.5.6 - pluggy==1.0.0 - py==1.11.0 - pytest==7.0.1 - s3fs==0.4.2 - s3transfer==0.5.2 - tomli==1.2.3 - zipp==3.6.0 prefix: /opt/conda/envs/dask
[ "dask/array/tests/test_array_core.py::test_copy" ]
[ "dask/array/tests/test_array_core.py::test_field_access", "dask/array/tests/test_array_core.py::test_coarsen", "dask/array/tests/test_array_core.py::test_coarsen_with_excess" ]
[ "dask/array/tests/test_array_core.py::test_getem", "dask/array/tests/test_array_core.py::test_top", "dask/array/tests/test_array_core.py::test_top_supports_broadcasting_rules", "dask/array/tests/test_array_core.py::test_concatenate3", "dask/array/tests/test_array_core.py::test_concatenate3_on_scalars", "dask/array/tests/test_array_core.py::test_chunked_dot_product", "dask/array/tests/test_array_core.py::test_chunked_transpose_plus_one", "dask/array/tests/test_array_core.py::test_transpose", "dask/array/tests/test_array_core.py::test_broadcast_dimensions_works_with_singleton_dimensions", "dask/array/tests/test_array_core.py::test_broadcast_dimensions", "dask/array/tests/test_array_core.py::test_Array", "dask/array/tests/test_array_core.py::test_uneven_chunks", "dask/array/tests/test_array_core.py::test_numblocks_suppoorts_singleton_block_dims", "dask/array/tests/test_array_core.py::test_keys", "dask/array/tests/test_array_core.py::test_Array_computation", "dask/array/tests/test_array_core.py::test_stack", "dask/array/tests/test_array_core.py::test_short_stack", "dask/array/tests/test_array_core.py::test_stack_scalars", "dask/array/tests/test_array_core.py::test_concatenate", "dask/array/tests/test_array_core.py::test_concatenate_fixlen_strings", "dask/array/tests/test_array_core.py::test_vstack", "dask/array/tests/test_array_core.py::test_hstack", "dask/array/tests/test_array_core.py::test_dstack", "dask/array/tests/test_array_core.py::test_take", "dask/array/tests/test_array_core.py::test_compress", "dask/array/tests/test_array_core.py::test_binops", "dask/array/tests/test_array_core.py::test_isnull", "dask/array/tests/test_array_core.py::test_isclose", "dask/array/tests/test_array_core.py::test_broadcast_shapes", "dask/array/tests/test_array_core.py::test_elemwise_on_scalars", "dask/array/tests/test_array_core.py::test_partial_by_order", "dask/array/tests/test_array_core.py::test_elemwise_with_ndarrays", "dask/array/tests/test_array_core.py::test_elemwise_differently_chunked", "dask/array/tests/test_array_core.py::test_operators", "dask/array/tests/test_array_core.py::test_operator_dtype_promotion", "dask/array/tests/test_array_core.py::test_tensordot", "dask/array/tests/test_array_core.py::test_dot_method", "dask/array/tests/test_array_core.py::test_T", "dask/array/tests/test_array_core.py::test_norm", "dask/array/tests/test_array_core.py::test_choose", "dask/array/tests/test_array_core.py::test_where", "dask/array/tests/test_array_core.py::test_where_has_informative_error", "dask/array/tests/test_array_core.py::test_insert", "dask/array/tests/test_array_core.py::test_multi_insert", "dask/array/tests/test_array_core.py::test_broadcast_to", "dask/array/tests/test_array_core.py::test_ravel", "dask/array/tests/test_array_core.py::test_unravel", "dask/array/tests/test_array_core.py::test_reshape", "dask/array/tests/test_array_core.py::test_reshape_unknown_dimensions", "dask/array/tests/test_array_core.py::test_full", "dask/array/tests/test_array_core.py::test_map_blocks", "dask/array/tests/test_array_core.py::test_map_blocks2", "dask/array/tests/test_array_core.py::test_map_blocks_with_constants", "dask/array/tests/test_array_core.py::test_map_blocks_with_kwargs", "dask/array/tests/test_array_core.py::test_fromfunction", "dask/array/tests/test_array_core.py::test_from_function_requires_block_args", "dask/array/tests/test_array_core.py::test_repr", "dask/array/tests/test_array_core.py::test_slicing_with_ellipsis", "dask/array/tests/test_array_core.py::test_slicing_with_ndarray", "dask/array/tests/test_array_core.py::test_dtype", "dask/array/tests/test_array_core.py::test_blockdims_from_blockshape", "dask/array/tests/test_array_core.py::test_coerce", "dask/array/tests/test_array_core.py::test_store", "dask/array/tests/test_array_core.py::test_store_compute_false", "dask/array/tests/test_array_core.py::test_store_locks", "dask/array/tests/test_array_core.py::test_to_hdf5", "dask/array/tests/test_array_core.py::test_np_array_with_zero_dimensions", "dask/array/tests/test_array_core.py::test_unique", "dask/array/tests/test_array_core.py::test_dtype_complex", "dask/array/tests/test_array_core.py::test_astype", "dask/array/tests/test_array_core.py::test_arithmetic", "dask/array/tests/test_array_core.py::test_elemwise_consistent_names", "dask/array/tests/test_array_core.py::test_optimize", "dask/array/tests/test_array_core.py::test_slicing_with_non_ndarrays", "dask/array/tests/test_array_core.py::test_getarray", "dask/array/tests/test_array_core.py::test_squeeze", "dask/array/tests/test_array_core.py::test_size", "dask/array/tests/test_array_core.py::test_nbytes", "dask/array/tests/test_array_core.py::test_Array_normalizes_dtype", "dask/array/tests/test_array_core.py::test_args", "dask/array/tests/test_array_core.py::test_from_array_with_lock", "dask/array/tests/test_array_core.py::test_from_func", "dask/array/tests/test_array_core.py::test_topk", "dask/array/tests/test_array_core.py::test_topk_k_bigger_than_chunk", "dask/array/tests/test_array_core.py::test_bincount", "dask/array/tests/test_array_core.py::test_bincount_with_weights", "dask/array/tests/test_array_core.py::test_bincount_raises_informative_error_on_missing_minlength_kwarg", "dask/array/tests/test_array_core.py::test_histogram", "dask/array/tests/test_array_core.py::test_histogram_alternative_bins_range", "dask/array/tests/test_array_core.py::test_histogram_return_type", "dask/array/tests/test_array_core.py::test_histogram_extra_args_and_shapes", "dask/array/tests/test_array_core.py::test_map_blocks3", "dask/array/tests/test_array_core.py::test_from_array_with_missing_chunks", "dask/array/tests/test_array_core.py::test_cache", "dask/array/tests/test_array_core.py::test_take_dask_from_numpy", "dask/array/tests/test_array_core.py::test_normalize_chunks", "dask/array/tests/test_array_core.py::test_raise_on_no_chunks", "dask/array/tests/test_array_core.py::test_chunks_is_immutable", "dask/array/tests/test_array_core.py::test_raise_on_bad_kwargs", "dask/array/tests/test_array_core.py::test_long_slice", "dask/array/tests/test_array_core.py::test_h5py_newaxis", "dask/array/tests/test_array_core.py::test_ellipsis_slicing", "dask/array/tests/test_array_core.py::test_point_slicing", "dask/array/tests/test_array_core.py::test_point_slicing_with_full_slice", "dask/array/tests/test_array_core.py::test_slice_with_floats", "dask/array/tests/test_array_core.py::test_vindex_errors", "dask/array/tests/test_array_core.py::test_vindex_merge", "dask/array/tests/test_array_core.py::test_empty_array", "dask/array/tests/test_array_core.py::test_array", "dask/array/tests/test_array_core.py::test_cov", "dask/array/tests/test_array_core.py::test_corrcoef", "dask/array/tests/test_array_core.py::test_memmap", "dask/array/tests/test_array_core.py::test_to_npy_stack", "dask/array/tests/test_array_core.py::test_view", "dask/array/tests/test_array_core.py::test_view_fortran", "dask/array/tests/test_array_core.py::test_h5py_tokenize", "dask/array/tests/test_array_core.py::test_map_blocks_with_changed_dimension", "dask/array/tests/test_array_core.py::test_broadcast_chunks", "dask/array/tests/test_array_core.py::test_chunks_error", "dask/array/tests/test_array_core.py::test_array_compute_forward_kwargs", "dask/array/tests/test_array_core.py::test_dont_fuse_outputs", "dask/array/tests/test_array_core.py::test_dont_dealias_outputs", "dask/array/tests/test_array_core.py::test_timedelta_op", "dask/array/tests/test_array_core.py::test_to_imperative", "dask/array/tests/test_array_core.py::test_cumulative", "dask/array/tests/test_array_core.py::test_eye", "dask/array/tests/test_array_core.py::test_diag", "dask/array/tests/test_array_core.py::test_tril_triu", "dask/array/tests/test_array_core.py::test_tril_triu_errors", "dask/array/tests/test_array_core.py::test_atop_names", "dask/array/tests/test_array_core.py::test_A_property" ]
[]
BSD 3-Clause "New" or "Revised" License
511
tornadoweb__tornado-1699
d71026ab2e1febfedb9d5e0589107349c5019fde
2016-04-23 23:40:24
c20c44d776d3bd9b2c002db5aaa9e3b5284a3043
diff --git a/tornado/escape.py b/tornado/escape.py index e6636f20..7a3b0e03 100644 --- a/tornado/escape.py +++ b/tornado/escape.py @@ -37,6 +37,11 @@ else: import htmlentitydefs import urllib as urllib_parse +try: + import typing # noqa +except ImportError: + pass + _XHTML_ESCAPE_RE = re.compile('[&<>"\']') _XHTML_ESCAPE_DICT = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', @@ -180,6 +185,7 @@ _UTF8_TYPES = (bytes, type(None)) def utf8(value): + # type: (typing.Union[bytes,unicode_type,None])->typing.Union[bytes,None] """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. diff --git a/tornado/http1connection.py b/tornado/http1connection.py index b04cff13..8194f914 100644 --- a/tornado/http1connection.py +++ b/tornado/http1connection.py @@ -30,7 +30,7 @@ from tornado import httputil from tornado import iostream from tornado.log import gen_log, app_log from tornado import stack_context -from tornado.util import GzipDecompressor +from tornado.util import GzipDecompressor, PY3 class _QuietException(Exception): @@ -372,7 +372,14 @@ class HTTP1Connection(httputil.HTTPConnection): self._expected_content_remaining = int(headers['Content-Length']) else: self._expected_content_remaining = None - lines.extend([utf8(n) + b": " + utf8(v) for n, v in headers.get_all()]) + # TODO: headers are supposed to be of type str, but we still have some + # cases that let bytes slip through. Remove these native_str calls when those + # are fixed. + header_lines = (native_str(n) + ": " + native_str(v) for n, v in headers.get_all()) + if PY3: + lines.extend(l.encode('latin1') for l in header_lines) + else: + lines.extend(header_lines) for line in lines: if b'\n' in line: raise ValueError('Newline in header: ' + repr(line)) diff --git a/tornado/httputil.py b/tornado/httputil.py index d0901565..866681ad 100644 --- a/tornado/httputil.py +++ b/tornado/httputil.py @@ -59,6 +59,12 @@ except ImportError: # on the class definition itself; must go through an assignment. SSLError = _SSLError # type: ignore +try: + import typing +except ImportError: + pass + + # RFC 7230 section 3.5: a recipient MAY recognize a single LF as a line # terminator and ignore any preceding CR. _CRLF_RE = re.compile(r'\r?\n') @@ -124,8 +130,8 @@ class HTTPHeaders(collections.MutableMapping): Set-Cookie: C=D """ def __init__(self, *args, **kwargs): - self._dict = {} - self._as_list = {} + self._dict = {} # type: typing.Dict[str, str] + self._as_list = {} # type: typing.Dict[str, typing.List[str]] self._last_key = None if (len(args) == 1 and len(kwargs) == 0 and isinstance(args[0], HTTPHeaders)): @@ -139,6 +145,7 @@ class HTTPHeaders(collections.MutableMapping): # new public methods def add(self, name, value): + # type: (str, str) -> None """Adds a new value for the given key.""" norm_name = _normalized_headers[name] self._last_key = norm_name @@ -155,6 +162,7 @@ class HTTPHeaders(collections.MutableMapping): return self._as_list.get(norm_name, []) def get_all(self): + # type: () -> typing.Iterable[typing.Tuple[str, str]] """Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be @@ -203,6 +211,7 @@ class HTTPHeaders(collections.MutableMapping): self._as_list[norm_name] = [value] def __getitem__(self, name): + # type: (str) -> str return self._dict[_normalized_headers[name]] def __delitem__(self, name): diff --git a/tornado/log.py b/tornado/log.py index ac1bb95e..1d10d379 100644 --- a/tornado/log.py +++ b/tornado/log.py @@ -77,8 +77,8 @@ class LogFormatter(logging.Formatter): * Robust against str/bytes encoding problems. This formatter is enabled automatically by - `tornado.options.parse_command_line` or `tornado.options.parse_config_file` - (unless ``--logging=none`` is used). + `tornado.options.parse_command_line` (unless ``--logging=none`` is + used). """ DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s' DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S' diff --git a/tornado/util.py b/tornado/util.py index 4283d4e8..d49a84f4 100644 --- a/tornado/util.py +++ b/tornado/util.py @@ -33,12 +33,13 @@ else: # Aliases for types that are spelled differently in different Python # versions. bytes_type is deprecated and no longer used in Tornado # itself but is left in case anyone outside Tornado is using it. -unicode_type = type(u'') bytes_type = bytes if PY3: + unicode_type = str basestring_type = str else: - # The name basestring doesn't exist in py3 so silence flake8. + # The names unicode and basestring don't exist in py3 so silence flake8. + unicode_type = unicode # noqa basestring_type = basestring # noqa diff --git a/tornado/web.py b/tornado/web.py index 8f2acfcc..c9ff2b2d 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -104,6 +104,11 @@ else: try: import typing # noqa + + # The following types are accepted by RequestHandler.set_header + # and related methods. + _HeaderTypes = typing.Union[bytes, unicode_type, + numbers.Integral, datetime.datetime] except ImportError: pass @@ -164,6 +169,7 @@ class RequestHandler(object): self._auto_finish = True self._transforms = None # will be set in _execute self._prepared_future = None + self._headers = None # type: httputil.HTTPHeaders self.path_args = None self.path_kwargs = None self.ui = ObjectDict((n, self._ui_method(m)) for n, m in @@ -318,6 +324,7 @@ class RequestHandler(object): return self._status_code def set_header(self, name, value): + # type: (str, _HeaderTypes) -> None """Sets the given response header name and value. If a datetime is given, we automatically format it according to the @@ -327,6 +334,7 @@ class RequestHandler(object): self._headers[name] = self._convert_header_value(value) def add_header(self, name, value): + # type: (str, _HeaderTypes) -> None """Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times @@ -343,13 +351,25 @@ class RequestHandler(object): if name in self._headers: del self._headers[name] - _INVALID_HEADER_CHAR_RE = re.compile(br"[\x00-\x1f]") + _INVALID_HEADER_CHAR_RE = re.compile(r"[\x00-\x1f]") def _convert_header_value(self, value): - if isinstance(value, bytes): - pass - elif isinstance(value, unicode_type): - value = value.encode('utf-8') + # type: (_HeaderTypes) -> str + + # Convert the input value to a str. This type check is a bit + # subtle: The bytes case only executes on python 3, and the + # unicode case only executes on python 2, because the other + # cases are covered by the first match for str. + if isinstance(value, str): + retval = value + elif isinstance(value, bytes): # py3 + # Non-ascii characters in headers are not well supported, + # but if you pass bytes, use latin1 so they pass through as-is. + retval = value.decode('latin1') + elif isinstance(value, unicode_type): # py2 + # TODO: This is inconsistent with the use of latin1 above, + # but it's been that way for a long time. Should it change? + retval = escape.utf8(value) elif isinstance(value, numbers.Integral): # return immediately since we know the converted value will be safe return str(value) @@ -359,9 +379,9 @@ class RequestHandler(object): raise TypeError("Unsupported header value %r" % value) # If \n is allowed into the header, it is possible to inject # additional headers or split the request. - if RequestHandler._INVALID_HEADER_CHAR_RE.search(value): - raise ValueError("Unsafe header value %r", value) - return value + if RequestHandler._INVALID_HEADER_CHAR_RE.search(retval): + raise ValueError("Unsafe header value %r", retval) + return retval _ARG_DEFAULT = object() @@ -2696,6 +2716,7 @@ class OutputTransform(object): pass def transform_first_chunk(self, status_code, headers, chunk, finishing): + # type: (int, httputil.HTTPHeaders, bytes, bool) -> typing.Tuple[int, httputil.HTTPHeaders, bytes] return status_code, headers, chunk def transform_chunk(self, chunk, finishing): @@ -2736,10 +2757,12 @@ class GZipContentEncoding(OutputTransform): return ctype.startswith('text/') or ctype in self.CONTENT_TYPES def transform_first_chunk(self, status_code, headers, chunk, finishing): + # type: (int, httputil.HTTPHeaders, bytes, bool) -> typing.Tuple[int, httputil.HTTPHeaders, bytes] + # TODO: can/should this type be inherited from the superclass? if 'Vary' in headers: - headers['Vary'] += b', Accept-Encoding' + headers['Vary'] += ', Accept-Encoding' else: - headers['Vary'] = b'Accept-Encoding' + headers['Vary'] = 'Accept-Encoding' if self._gzipping: ctype = _unicode(headers.get("Content-Type", "")).split(";")[0] self._gzipping = self._compressible_type(ctype) and \
When Use AsyncHttpClien.AttributeError: 'GZipContentEncoding' object has no attribute '_gzip_file' File "D:\Python3.4.3\lib\site-packages\tornado-4.3-py3.4-win32.egg\tornado\web.py", line 781, in render self.finish(html) File "D:\Python3.4.3\lib\site-packages\tornado-4.3-py3.4-win32.egg\tornado\web.py", line 932, in finish self.flush(include_footers=True) File "D:\Python3.4.3\lib\site-packages\tornado-4.3-py3.4-win32.egg\tornado\web.py", line 891, in flush chunk = transform.transform_chunk(chunk, include_footers) File "D:\Python3.4.3\lib\site-packages\tornado-4.3-py3.4-win32.egg\tornado\web.py", line 2763, in transform_chunk self._gzip_file.write(chunk) AttributeError: 'GZipContentEncoding' object has no attribute '_gzip_file'
tornadoweb/tornado
diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py index fac23a21..7e417854 100644 --- a/tornado/test/web_test.py +++ b/tornado/test/web_test.py @@ -1506,8 +1506,8 @@ class ErrorHandlerXSRFTest(WebTestCase): class GzipTestCase(SimpleHandlerTestCase): class Handler(RequestHandler): def get(self): - if self.get_argument('vary', None): - self.set_header('Vary', self.get_argument('vary')) + for v in self.get_arguments('vary'): + self.add_header('Vary', v) # Must write at least MIN_LENGTH bytes to activate compression. self.write('hello world' + ('!' * GZipContentEncoding.MIN_LENGTH)) @@ -1516,8 +1516,7 @@ class GzipTestCase(SimpleHandlerTestCase): gzip=True, static_path=os.path.join(os.path.dirname(__file__), 'static')) - def test_gzip(self): - response = self.fetch('/') + def assert_compressed(self, response): # simple_httpclient renames the content-encoding header; # curl_httpclient doesn't. self.assertEqual( @@ -1525,17 +1524,18 @@ class GzipTestCase(SimpleHandlerTestCase): 'Content-Encoding', response.headers.get('X-Consumed-Content-Encoding')), 'gzip') + + + def test_gzip(self): + response = self.fetch('/') + self.assert_compressed(response) self.assertEqual(response.headers['Vary'], 'Accept-Encoding') def test_gzip_static(self): # The streaming responses in StaticFileHandler have subtle # interactions with the gzip output so test this case separately. response = self.fetch('/robots.txt') - self.assertEqual( - response.headers.get( - 'Content-Encoding', - response.headers.get('X-Consumed-Content-Encoding')), - 'gzip') + self.assert_compressed(response) self.assertEqual(response.headers['Vary'], 'Accept-Encoding') def test_gzip_not_requested(self): @@ -1545,9 +1545,16 @@ class GzipTestCase(SimpleHandlerTestCase): def test_vary_already_present(self): response = self.fetch('/?vary=Accept-Language') - self.assertEqual(response.headers['Vary'], - 'Accept-Language, Accept-Encoding') - + self.assert_compressed(response) + self.assertEqual([s.strip() for s in response.headers['Vary'].split(',')], + ['Accept-Language', 'Accept-Encoding']) + + def test_vary_already_present_multiple(self): + # Regression test for https://github.com/tornadoweb/tornado/issues/1670 + response = self.fetch('/?vary=Accept-Language&vary=Cookie') + self.assert_compressed(response) + self.assertEqual([s.strip() for s in response.headers['Vary'].split(',')], + ['Accept-Language', 'Cookie', 'Accept-Encoding']) @wsgi_safe class PathArgsInPrepareTest(WebTestCase):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 6 }
4.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "futures", "mock", "monotonic", "trollius", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 futures==2.2.0 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mock==5.2.0 monotonic==1.6 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work -e git+https://github.com/tornadoweb/tornado.git@d71026ab2e1febfedb9d5e0589107349c5019fde#egg=tornado trollius==2.1.post2 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: tornado channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - futures==2.2.0 - mock==5.2.0 - monotonic==1.6 - six==1.17.0 - trollius==2.1.post2 prefix: /opt/conda/envs/tornado
[ "tornado/test/web_test.py::GzipTestCase::test_vary_already_present_multiple" ]
[]
[ "tornado/test/web_test.py::SecureCookieV1Test::test_arbitrary_bytes", "tornado/test/web_test.py::SecureCookieV1Test::test_cookie_tampering_future_timestamp", "tornado/test/web_test.py::SecureCookieV1Test::test_round_trip", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_increment_version", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_invalidate_version", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_roundtrip", "tornado/test/web_test.py::SecureCookieV2Test::test_key_version_roundtrip_differing_version", "tornado/test/web_test.py::SecureCookieV2Test::test_round_trip", "tornado/test/web_test.py::CookieTest::test_cookie_special_char", "tornado/test/web_test.py::CookieTest::test_get_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie_domain", "tornado/test/web_test.py::CookieTest::test_set_cookie_expires_days", "tornado/test/web_test.py::CookieTest::test_set_cookie_false_flags", "tornado/test/web_test.py::CookieTest::test_set_cookie_max_age", "tornado/test/web_test.py::CookieTest::test_set_cookie_overwrite", "tornado/test/web_test.py::AuthRedirectTest::test_absolute_auth_redirect", "tornado/test/web_test.py::AuthRedirectTest::test_relative_auth_redirect", "tornado/test/web_test.py::ConnectionCloseTest::test_connection_close", "tornado/test/web_test.py::RequestEncodingTest::test_error", "tornado/test/web_test.py::RequestEncodingTest::test_group_encoding", "tornado/test/web_test.py::RequestEncodingTest::test_group_question_mark", "tornado/test/web_test.py::RequestEncodingTest::test_slashes", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_invalid_unicode", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_plus", "tornado/test/web_test.py::WSGISafeWebTest::test_get_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_get_body_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_get_query_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_header_injection", "tornado/test/web_test.py::WSGISafeWebTest::test_multi_header", "tornado/test/web_test.py::WSGISafeWebTest::test_no_gzip", "tornado/test/web_test.py::WSGISafeWebTest::test_optional_path", "tornado/test/web_test.py::WSGISafeWebTest::test_redirect", "tornado/test/web_test.py::WSGISafeWebTest::test_reverse_url", "tornado/test/web_test.py::WSGISafeWebTest::test_types", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_resources", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_unescaped", "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect", "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect_double_slash", "tornado/test/web_test.py::NonWSGIWebTests::test_empty_flush", "tornado/test/web_test.py::NonWSGIWebTests::test_flow_control", "tornado/test/web_test.py::ErrorResponseTest::test_default", "tornado/test/web_test.py::ErrorResponseTest::test_failed_write_error", "tornado/test/web_test.py::ErrorResponseTest::test_write_error", "tornado/test/web_test.py::StaticFileTest::test_absolute_static_url", "tornado/test/web_test.py::StaticFileTest::test_absolute_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_include_host_override", "tornado/test/web_test.py::StaticFileTest::test_path_traversal_protection", "tornado/test/web_test.py::StaticFileTest::test_relative_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_root_static_path", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_modified_since", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_404", "tornado/test/web_test.py::StaticFileTest::test_static_compressed_files", "tornado/test/web_test.py::StaticFileTest::test_static_etag", "tornado/test/web_test.py::StaticFileTest::test_static_files", "tornado/test/web_test.py::StaticFileTest::test_static_head", "tornado/test/web_test.py::StaticFileTest::test_static_head_range", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_pre_epoch", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_time_zone", "tornado/test/web_test.py::StaticFileTest::test_static_invalid_range", "tornado/test/web_test.py::StaticFileTest::test_static_range_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_invalid_start", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_zero_suffix", "tornado/test/web_test.py::StaticFileTest::test_static_url", "tornado/test/web_test.py::StaticFileTest::test_static_with_range", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_end_edge", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_file", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_past_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_neg_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_partial_past_end", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_filename", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_redirect", "tornado/test/web_test.py::StaticFileWithPathTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_static_url", "tornado/test/web_test.py::HostMatchingTest::test_host_matching", "tornado/test/web_test.py::NamedURLSpecGroupsTest::test_named_urlspec_groups", "tornado/test/web_test.py::ClearHeaderTest::test_clear_header", "tornado/test/web_test.py::Header304Test::test_304_headers", "tornado/test/web_test.py::StatusReasonTest::test_status", "tornado/test/web_test.py::DateHeaderTest::test_date_header", "tornado/test/web_test.py::RaiseWithReasonTest::test_httperror_str", "tornado/test/web_test.py::RaiseWithReasonTest::test_httperror_str_from_httputil", "tornado/test/web_test.py::RaiseWithReasonTest::test_raise_with_reason", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_404_xsrf", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_error_xsrf", "tornado/test/web_test.py::GzipTestCase::test_gzip", "tornado/test/web_test.py::GzipTestCase::test_gzip_not_requested", "tornado/test/web_test.py::GzipTestCase::test_gzip_static", "tornado/test/web_test.py::GzipTestCase::test_vary_already_present", "tornado/test/web_test.py::PathArgsInPrepareTest::test_kw", "tornado/test/web_test.py::PathArgsInPrepareTest::test_pos", "tornado/test/web_test.py::ClearAllCookiesTest::test_clear_all_cookies", "tornado/test/web_test.py::ExceptionHandlerTest::test_http_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_known_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_unknown_error", "tornado/test/web_test.py::BuggyLoggingTest::test_buggy_log_exception", "tornado/test/web_test.py::UIMethodUIModuleTest::test_ui_method", "tornado/test/web_test.py::GetArgumentErrorTest::test_catch_error", "tornado/test/web_test.py::MultipleExceptionTest::test_multi_exception", "tornado/test/web_test.py::SetLazyPropertiesTest::test_set_properties", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_is_lazy", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_works", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_works", "tornado/test/web_test.py::UnimplementedHTTPMethodsTest::test_unimplemented_standard_methods", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_other", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_patch", "tornado/test/web_test.py::AllHTTPMethodsTest::test_standard_methods", "tornado/test/web_test.py::PatchMethodTest::test_other", "tornado/test/web_test.py::PatchMethodTest::test_patch", "tornado/test/web_test.py::FinishInPrepareTest::test_finish_in_prepare", "tornado/test/web_test.py::Default404Test::test_404", "tornado/test/web_test.py::Custom404Test::test_404", "tornado/test/web_test.py::DefaultHandlerArgumentsTest::test_403", "tornado/test/web_test.py::HandlerByNameTest::test_handler_by_name", "tornado/test/web_test.py::StreamingRequestBodyTest::test_close_during_upload", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return_with_data", "tornado/test/web_test.py::StreamingRequestBodyTest::test_streaming_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_chunked_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_compressed_body", "tornado/test/web_test.py::DecoratedStreamingRequestFlowControlTest::test_flow_control_fixed_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_chunked_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_compressed_body", "tornado/test/web_test.py::NativeStreamingRequestFlowControlTest::test_flow_control_fixed_body", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_high", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_low", "tornado/test/web_test.py::ClientCloseTest::test_client_close", "tornado/test/web_test.py::SignedValueTest::test_expired", "tornado/test/web_test.py::SignedValueTest::test_key_version_retrieval", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_invalid_key", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_read_write_default_key", "tornado/test/web_test.py::SignedValueTest::test_key_versioning_read_write_non_default_key", "tornado/test/web_test.py::SignedValueTest::test_known_values", "tornado/test/web_test.py::SignedValueTest::test_name_swap", "tornado/test/web_test.py::SignedValueTest::test_non_ascii", "tornado/test/web_test.py::SignedValueTest::test_payload_tampering", "tornado/test/web_test.py::SignedValueTest::test_signature_tampering", "tornado/test/web_test.py::XSRFTest::test_cross_user", "tornado/test/web_test.py::XSRFTest::test_distinct_tokens", "tornado/test/web_test.py::XSRFTest::test_refresh_token", "tornado/test/web_test.py::XSRFTest::test_versioning", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_body_no_cookie", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_cookie_no_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_no_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_header", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_non_hex_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_post_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_query_string", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_short_token", "tornado/test/web_test.py::XSRFCookieKwargsTest::test_xsrf_httponly", "tornado/test/web_test.py::FinishExceptionTest::test_finish_exception", "tornado/test/web_test.py::DecoratorTest::test_addslash", "tornado/test/web_test.py::DecoratorTest::test_removeslash", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_wildcard_etag", "tornado/test/web_test.py::RequestSummaryTest::test_missing_remote_ip", "tornado/test/web_test.py::HTTPErrorTest::test_copy", "tornado/test/web_test.py::ApplicationTest::test_listen", "tornado/test/web_test.py::URLSpecReverseTest::test_reverse" ]
[]
Apache License 2.0
512
falconry__falcon-762
3584dfd4d3653f2165cbd1e6832ea5d250a5d319
2016-04-25 12:43:40
67d61029847cbf59e4053c8a424df4f9f87ad36f
kgriffs: This looks good, thanks! Would you mind rebasing? Once that's done, this is ready to merge. yohanboniface: Done :) codecov-io: ## [Current coverage][cc-pull] is **98.99%** > Merging [#762][cc-pull] into [master][cc-base-branch] will not change coverage ```diff @@ master #762 diff @@ ========================================== Files 29 29 Lines 1777 1777 Methods 0 0 Messages 0 0 Branches 296 296 ========================================== Hits 1759 1759 Misses 5 5 Partials 13 13 ``` [![Sunburst](https://codecov.io/gh/falconry/falcon/pull/762/graphs/sunburst.svg?size=660&src=pr)][cc-pull] > Powered by [Codecov](https://codecov.io?src=pr). Last updated by dd75405 [cc-base-branch]: https://codecov.io/gh/falconry/falcon/branch/master?src=pr [cc-pull]: https://codecov.io/gh/falconry/falcon/pull/762?src=pr
diff --git a/falcon/request.py b/falcon/request.py index 5b4634a..6516154 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -43,8 +43,8 @@ SimpleCookie = http_cookies.SimpleCookie DEFAULT_ERROR_LOG_FORMAT = (u'{0:%Y-%m-%d %H:%M:%S} [FALCON] [ERROR]' u' {1} {2}{3} => ') -TRUE_STRINGS = ('true', 'True', 'yes') -FALSE_STRINGS = ('false', 'False', 'no') +TRUE_STRINGS = ('true', 'True', 'yes', '1') +FALSE_STRINGS = ('false', 'False', 'no', '0') WSGI_CONTENT_HEADERS = ('CONTENT_TYPE', 'CONTENT_LENGTH') @@ -865,8 +865,8 @@ class Request(object): The following boolean strings are supported:: - TRUE_STRINGS = ('true', 'True', 'yes') - FALSE_STRINGS = ('false', 'False', 'no') + TRUE_STRINGS = ('true', 'True', 'yes', '1') + FALSE_STRINGS = ('false', 'False', 'no', '0') Args: name (str): Parameter name, case-sensitive (e.g., 'detailed').
Also convert '1' and '0' as booleans from query string I see that [tests](https://github.com/falconry/falcon/blob/master/tests/test_query_params.py#L194) specifically exclude `0` and `1` from valid values to be converted to boolean by `Request.get_param_as_bool` method. I'd like to discuss this situation :) I see no reason not to convert those values as they seem non ambiguous to me and there are a bunch of situations where 1 and 0 are de facto boolean (database outputs…), but we only deals with string in query string. What is the rationale behind this? Thanks! :)
falconry/falcon
diff --git a/tests/test_query_params.py b/tests/test_query_params.py index 285a6aa..a9b44e0 100644 --- a/tests/test_query_params.py +++ b/tests/test_query_params.py @@ -201,8 +201,8 @@ class _TestQueryParams(testing.TestBase): req.get_param_as_int, 'pos', min=0, max=10) def test_boolean(self): - query_string = ('echo=true&doit=false&bogus=0&bogus2=1&' - 't1=True&f1=False&t2=yes&f2=no&blank') + query_string = ('echo=true&doit=false&bogus=bar&bogus2=foo&' + 't1=True&f1=False&t2=yes&f2=no&blank&one=1&zero=0') self.simulate_request('/', query_string=query_string) req = self.resource.req @@ -226,6 +226,8 @@ class _TestQueryParams(testing.TestBase): self.assertEqual(req.get_param_as_bool('t2'), True) self.assertEqual(req.get_param_as_bool('f1'), False) self.assertEqual(req.get_param_as_bool('f2'), False) + self.assertEqual(req.get_param_as_bool('one'), True) + self.assertEqual(req.get_param_as_bool('zero'), False) self.assertEqual(req.get_param('blank'), None) store = {}
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "tools/test-requires" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 ddt==1.7.2 -e git+https://github.com/falconry/falcon.git@3584dfd4d3653f2165cbd1e6832ea5d250a5d319#egg=falcon fixtures==4.0.1 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 nose==1.3.7 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-mimeparse==1.6.0 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 testtools==2.6.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - ddt==1.7.2 - fixtures==4.0.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-mimeparse==1.6.0 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - testtools==2.6.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/falcon
[ "tests/test_query_params.py::_TestQueryParams::test_boolean", "tests/test_query_params.py::PostQueryParams::test_boolean", "tests/test_query_params.py::GetQueryParams::test_boolean" ]
[]
[ "tests/test_query_params.py::_TestQueryParams::test_allowed_names", "tests/test_query_params.py::_TestQueryParams::test_bad_percentage", "tests/test_query_params.py::_TestQueryParams::test_blank", "tests/test_query_params.py::_TestQueryParams::test_boolean_blank", "tests/test_query_params.py::_TestQueryParams::test_get_date_invalid", "tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param", "tests/test_query_params.py::_TestQueryParams::test_get_date_store", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::_TestQueryParams::test_int", "tests/test_query_params.py::_TestQueryParams::test_int_neg", "tests/test_query_params.py::_TestQueryParams::test_list_transformer", "tests/test_query_params.py::_TestQueryParams::test_list_type", "tests/test_query_params.py::_TestQueryParams::test_list_type_blank", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::_TestQueryParams::test_none", "tests/test_query_params.py::_TestQueryParams::test_param_property", "tests/test_query_params.py::_TestQueryParams::test_percent_encoded", "tests/test_query_params.py::_TestQueryParams::test_required_1_get_param", "tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::_TestQueryParams::test_simple", "tests/test_query_params.py::PostQueryParams::test_allowed_names", "tests/test_query_params.py::PostQueryParams::test_bad_percentage", "tests/test_query_params.py::PostQueryParams::test_blank", "tests/test_query_params.py::PostQueryParams::test_boolean_blank", "tests/test_query_params.py::PostQueryParams::test_explicitly_disable_auto_parse", "tests/test_query_params.py::PostQueryParams::test_get_date_invalid", "tests/test_query_params.py::PostQueryParams::test_get_date_missing_param", "tests/test_query_params.py::PostQueryParams::test_get_date_store", "tests/test_query_params.py::PostQueryParams::test_get_date_valid", "tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::PostQueryParams::test_int", "tests/test_query_params.py::PostQueryParams::test_int_neg", "tests/test_query_params.py::PostQueryParams::test_list_transformer", "tests/test_query_params.py::PostQueryParams::test_list_type", "tests/test_query_params.py::PostQueryParams::test_list_type_blank", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::PostQueryParams::test_non_ascii", "tests/test_query_params.py::PostQueryParams::test_none", "tests/test_query_params.py::PostQueryParams::test_param_property", "tests/test_query_params.py::PostQueryParams::test_percent_encoded", "tests/test_query_params.py::PostQueryParams::test_required_1_get_param", "tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::PostQueryParams::test_simple", "tests/test_query_params.py::GetQueryParams::test_allowed_names", "tests/test_query_params.py::GetQueryParams::test_bad_percentage", "tests/test_query_params.py::GetQueryParams::test_blank", "tests/test_query_params.py::GetQueryParams::test_boolean_blank", "tests/test_query_params.py::GetQueryParams::test_get_date_invalid", "tests/test_query_params.py::GetQueryParams::test_get_date_missing_param", "tests/test_query_params.py::GetQueryParams::test_get_date_store", "tests/test_query_params.py::GetQueryParams::test_get_date_valid", "tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::GetQueryParams::test_int", "tests/test_query_params.py::GetQueryParams::test_int_neg", "tests/test_query_params.py::GetQueryParams::test_list_transformer", "tests/test_query_params.py::GetQueryParams::test_list_type", "tests/test_query_params.py::GetQueryParams::test_list_type_blank", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::GetQueryParams::test_none", "tests/test_query_params.py::GetQueryParams::test_param_property", "tests/test_query_params.py::GetQueryParams::test_percent_encoded", "tests/test_query_params.py::GetQueryParams::test_required_1_get_param", "tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::GetQueryParams::test_simple", "tests/test_query_params.py::PostQueryParamsDefaultBehavior::test_dont_auto_parse_by_default" ]
[]
Apache License 2.0
513
dask__dask-1126
5d94595499ebf0dd7b7bfcccca328f7d0fca7b7e
2016-04-27 16:57:30
71e3e413d6e00942de3ff32a3ba378408f2648e9
diff --git a/dask/callbacks.py b/dask/callbacks.py index 55e7a5a1b..61aba8676 100644 --- a/dask/callbacks.py +++ b/dask/callbacks.py @@ -44,10 +44,14 @@ class Callback(object): """ def __init__(self, start=None, pretask=None, posttask=None, finish=None): - self._start = start - self._pretask = pretask - self._posttask = posttask - self._finish = finish + if start: + self._start = start + if pretask: + self._pretask = pretask + if posttask: + self._posttask = posttask + if finish: + self._finish = finish @property def _callback(self):
Callback __init__() overrides subclass callback definitions The `__init__` method in `Callback` is: ``` def __init__(self, start=None, pretask=None, posttask=None, finish=None): self._start = start self._pretask = pretask self._posttask = posttask self._finish = finish ``` which overrides callbacks defined in subclasses, e.g.: ``` class TaskCounter(Callback): def _pretask(self, key, dask, state): count(key, dask, state) ``` which doesn't work, while: ``` class TaskCounter(Callback): def __init__(self): pass def _pretask(self, key, dask, state): count(key, dask, state) ``` does. Not sure quite what desired behavior here is, but the example in the docs: ``` class PrintKeys(Callback): def _pretask(self, key, dask, state): """Print the key of every task as it's started""" print("Computing: {0}!".format(repr(key))) ``` doesn't work.
dask/dask
diff --git a/dask/tests/test_callbacks.py b/dask/tests/test_callbacks.py new file mode 100644 index 000000000..b4f4b8396 --- /dev/null +++ b/dask/tests/test_callbacks.py @@ -0,0 +1,14 @@ +from dask.async import get_sync +from dask.callbacks import Callback + +def test_callback(): + flag = [False] + + class MyCallback(Callback): + def _start(self, dsk): + flag[0] = True + + with MyCallback(): + get_sync({'x': 1}, 'x') + + assert flag[0] is True
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
1.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 pandas>=1.0.0 cloudpickle partd distributed s3fs toolz psutil pytables bokeh bcolz scipy h5py ipython", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz liblzma-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore @ file:///opt/conda/conda-bld/aiobotocore_1643638228694/work aiohttp @ file:///tmp/build/80754af9/aiohttp_1632748060317/work aioitertools @ file:///tmp/build/80754af9/aioitertools_1607109665762/work async-timeout==3.0.1 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work bcolz==1.2.1 bokeh @ file:///tmp/build/80754af9/bokeh_1620710048147/work boto3==1.23.10 botocore==1.26.10 brotlipy==0.7.0 certifi==2021.5.30 cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work chardet @ file:///tmp/build/80754af9/chardet_1607706739153/work click==8.0.3 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1632508026186/work contextvars==2.4 cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work cytoolz==0.11.0 -e git+https://github.com/dask/dask.git@5d94595499ebf0dd7b7bfcccca328f7d0fca7b7e#egg=dask decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work distributed==1.9.5 fsspec @ file:///opt/conda/conda-bld/fsspec_1642510437511/work h5py==2.10.0 HeapDict @ file:///Users/ktietz/demo/mc3/conda-bld/heapdict_1630598515714/work idna @ file:///tmp/build/80754af9/idna_1637925883363/work idna-ssl @ file:///tmp/build/80754af9/idna_ssl_1611752490495/work immutables @ file:///tmp/build/80754af9/immutables_1628888996840/work importlib-metadata==4.8.3 iniconfig==1.1.1 ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work jmespath @ file:///Users/ktietz/demo/mc3/conda-bld/jmespath_1630583964805/work locket==0.2.1 MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work mock @ file:///tmp/build/80754af9/mock_1607622725907/work msgpack @ file:///tmp/build/80754af9/msgpack-python_1612287171716/work msgpack-python==0.5.6 multidict @ file:///tmp/build/80754af9/multidict_1607367768400/work numexpr @ file:///tmp/build/80754af9/numexpr_1618853194344/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 parso==0.7.0 partd @ file:///opt/conda/conda-bld/partd_1647245470509/work pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work pluggy==1.0.0 prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work psutil @ file:///tmp/build/80754af9/psutil_1612297621795/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl py==1.11.0 pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work pytest==7.0.1 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work pytz==2021.3 PyYAML==5.4.1 s3fs==0.4.2 s3transfer==0.5.2 scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work six @ file:///tmp/build/80754af9/six_1644875935023/work sortedcontainers @ file:///tmp/build/80754af9/sortedcontainers_1623949099177/work tables==3.6.1 tblib @ file:///Users/ktietz/demo/mc3/conda-bld/tblib_1629402031467/work tomli==1.2.3 toolz @ file:///tmp/build/80754af9/toolz_1636545406491/work tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work wrapt==1.12.1 yarl @ file:///tmp/build/80754af9/yarl_1606939915466/work zict==2.0.0 zipp==3.6.0
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - aiobotocore=2.1.0=pyhd3eb1b0_0 - aiohttp=3.7.4.post0=py36h7f8727e_2 - aioitertools=0.7.1=pyhd3eb1b0_0 - async-timeout=3.0.1=py36h06a4308_0 - attrs=21.4.0=pyhd3eb1b0_0 - backcall=0.2.0=pyhd3eb1b0_0 - bcolz=1.2.1=py36h04863e7_0 - blas=1.0=openblas - blosc=1.21.3=h6a678d5_0 - bokeh=2.3.2=py36h06a4308_0 - brotlipy=0.7.0=py36h27cfd23_1003 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - cffi=1.14.6=py36h400218f_0 - chardet=4.0.0=py36h06a4308_1003 - click=8.0.3=pyhd3eb1b0_0 - cloudpickle=2.0.0=pyhd3eb1b0_0 - contextvars=2.4=py_0 - cryptography=35.0.0=py36hd23ed53_0 - cytoolz=0.11.0=py36h7b6447c_0 - decorator=5.1.1=pyhd3eb1b0_0 - freetype=2.12.1=h4a9f257_0 - fsspec=2022.1.0=pyhd3eb1b0_0 - giflib=5.2.2=h5eee18b_0 - h5py=2.10.0=py36h7918eee_0 - hdf5=1.10.4=hb1b8bf9_0 - heapdict=1.0.1=pyhd3eb1b0_0 - idna=3.3=pyhd3eb1b0_0 - idna_ssl=1.1.0=py36h06a4308_0 - immutables=0.16=py36h7f8727e_0 - ipython=7.16.1=py36h5ca1d4c_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.17.2=py36h06a4308_1 - jinja2=3.0.3=pyhd3eb1b0_0 - jmespath=0.10.0=pyhd3eb1b0_0 - jpeg=9e=h5eee18b_3 - lcms2=2.16=hb9589c4_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h6a678d5_0 - libdeflate=1.22=h5eee18b_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtiff=4.5.1=hffd6297_1 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - locket=0.2.1=py36h06a4308_1 - lz4-c=1.9.4=h6a678d5_1 - lzo=2.10=h7b6447c_2 - markupsafe=2.0.1=py36h27cfd23_0 - mock=4.0.3=pyhd3eb1b0_0 - multidict=5.1.0=py36h27cfd23_2 - ncurses=6.4=h6a678d5_0 - numexpr=2.7.3=py36h4be448d_1 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pandas=1.1.5=py36ha9443f7_0 - parso=0.7.0=py_0 - partd=1.2.0=pyhd3eb1b0_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pillow=8.3.1=py36h5aabda8_0 - pip=21.2.2=py36h06a4308_0 - prompt-toolkit=3.0.20=pyhd3eb1b0_0 - psutil=5.8.0=py36h27cfd23_1 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.11.2=pyhd3eb1b0_0 - pyopenssl=22.0.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pysocks=1.7.1=py36h06a4308_0 - pytables=3.6.1=py36h71ec239_0 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytz=2021.3=pyhd3eb1b0_0 - pyyaml=5.4.1=py36h27cfd23_1 - readline=8.2=h5eee18b_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sortedcontainers=2.4.0=pyhd3eb1b0_0 - sqlite=3.45.3=h5eee18b_0 - tblib=1.7.0=pyhd3eb1b0_0 - tk=8.6.14=h39e8969_0 - toolz=0.11.2=pyhd3eb1b0_0 - tornado=6.1=py36h27cfd23_0 - traitlets=4.3.3=py36h06a4308_0 - typing-extensions=4.1.1=hd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - urllib3=1.26.8=pyhd3eb1b0_0 - wcwidth=0.2.5=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - wrapt=1.12.1=py36h7b6447c_1 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - yarl=1.6.3=py36h27cfd23_0 - zict=2.0.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - zstd=1.5.6=hc292b87_0 - pip: - boto3==1.23.10 - botocore==1.26.10 - distributed==1.9.5 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - msgpack-python==0.5.6 - pluggy==1.0.0 - py==1.11.0 - pytest==7.0.1 - s3fs==0.4.2 - s3transfer==0.5.2 - tomli==1.2.3 - zipp==3.6.0 prefix: /opt/conda/envs/dask
[ "dask/tests/test_callbacks.py::test_callback" ]
[]
[]
[]
BSD 3-Clause "New" or "Revised" License
514
pre-commit__pre-commit-hooks-111
17478a0a50faf20fd8e5b3fefe7435cea410df0b
2016-04-27 18:19:24
17478a0a50faf20fd8e5b3fefe7435cea410df0b
diff --git a/README.md b/README.md index 091a8a4..6c3a3ec 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,8 @@ Add this to your `.pre-commit-config.yaml` - `double-quote-string-fixer` - This hook replaces double quoted strings with single quoted strings. - `end-of-file-fixer` - Makes sure files end in a newline and only a newline. -- `fix-encoding-pragma` - Add `# -*- coding: utf-8 -*-` to the top of python files +- `fix-encoding-pragma` - Add `# -*- coding: utf-8 -*-` to the top of python files. + - To remove the coding pragma pass `--remove` (useful in a python3-only codebase) - `flake8` - Run flake8 on your python files. - `name-tests-test` - Assert that files in tests/ end in `_test.py`. - Use `args: ['--django']` to match `test*.py` instead. diff --git a/pre_commit_hooks/fix_encoding_pragma.py b/pre_commit_hooks/fix_encoding_pragma.py index 48fc9c7..8586937 100644 --- a/pre_commit_hooks/fix_encoding_pragma.py +++ b/pre_commit_hooks/fix_encoding_pragma.py @@ -3,7 +3,7 @@ from __future__ import print_function from __future__ import unicode_literals import argparse -import io +import collections expected_pragma = b'# -*- coding: utf-8 -*-\n' @@ -21,34 +21,72 @@ def has_coding(line): ) -def fix_encoding_pragma(f): - first_line = f.readline() - second_line = f.readline() - old = f.read() - f.seek(0) +class ExpectedContents(collections.namedtuple( + 'ExpectedContents', ('shebang', 'rest', 'pragma_status'), +)): + """ + pragma_status: + - True: has exactly the coding pragma expected + - False: missing coding pragma entirely + - None: has a coding pragma, but it does not match + """ + __slots__ = () - # Ok case: the file is empty - if not (first_line + second_line + old).strip(): - return 0 + @property + def has_any_pragma(self): + return self.pragma_status is not False - # Ok case: we specify pragma as the first line - if first_line == expected_pragma: - return 0 + def is_expected_pragma(self, remove): + expected_pragma_status = not remove + return self.pragma_status is expected_pragma_status - # OK case: we have a shebang as first line and pragma on second line - if first_line.startswith(b'#!') and second_line == expected_pragma: - return 0 - # Otherwise we need to rewrite stuff! +def _get_expected_contents(first_line, second_line, rest): if first_line.startswith(b'#!'): - if has_coding(second_line): - f.write(first_line + expected_pragma + old) - else: - f.write(first_line + expected_pragma + second_line + old) - elif has_coding(first_line): - f.write(expected_pragma + second_line + old) + shebang = first_line + potential_coding = second_line else: - f.write(expected_pragma + first_line + second_line + old) + shebang = b'' + potential_coding = first_line + rest = second_line + rest + + if potential_coding == expected_pragma: + pragma_status = True + elif has_coding(potential_coding): + pragma_status = None + else: + pragma_status = False + rest = potential_coding + rest + + return ExpectedContents( + shebang=shebang, rest=rest, pragma_status=pragma_status, + ) + + +def fix_encoding_pragma(f, remove=False): + expected = _get_expected_contents(f.readline(), f.readline(), f.read()) + + # Special cases for empty files + if not expected.rest.strip(): + # If a file only has a shebang or a coding pragma, remove it + if expected.has_any_pragma or expected.shebang: + f.seek(0) + f.truncate() + f.write(b'') + return 1 + else: + return 0 + + if expected.is_expected_pragma(remove): + return 0 + + # Otherwise, write out the new file + f.seek(0) + f.truncate() + f.write(expected.shebang) + if not remove: + f.write(expected_pragma) + f.write(expected.rest) return 1 @@ -56,18 +94,25 @@ def fix_encoding_pragma(f): def main(argv=None): parser = argparse.ArgumentParser('Fixes the encoding pragma of python files') parser.add_argument('filenames', nargs='*', help='Filenames to fix') + parser.add_argument( + '--remove', action='store_true', + help='Remove the encoding pragma (Useful in a python3-only codebase)', + ) args = parser.parse_args(argv) retv = 0 + if args.remove: + fmt = 'Removed encoding pragma from {filename}' + else: + fmt = 'Added `{pragma}` to {filename}' + for filename in args.filenames: - with io.open(filename, 'r+b') as f: - file_ret = fix_encoding_pragma(f) + with open(filename, 'r+b') as f: + file_ret = fix_encoding_pragma(f, remove=args.remove) retv |= file_ret if file_ret: - print('Added `{0}` to {1}'.format( - expected_pragma.strip(), filename, - )) + print(fmt.format(pragma=expected_pragma, filename=filename)) return retv
Add a --remove option to fix-encoding-pragma This is an unnecessary thing in python3
pre-commit/pre-commit-hooks
diff --git a/tests/fix_encoding_pragma_test.py b/tests/fix_encoding_pragma_test.py index e000a33..a9502a2 100644 --- a/tests/fix_encoding_pragma_test.py +++ b/tests/fix_encoding_pragma_test.py @@ -10,32 +10,46 @@ from pre_commit_hooks.fix_encoding_pragma import main def test_integration_inserting_pragma(tmpdir): - file_path = tmpdir.join('foo.py').strpath + path = tmpdir.join('foo.py') + path.write_binary(b'import httplib\n') - with open(file_path, 'wb') as file_obj: - file_obj.write(b'import httplib\n') + assert main((path.strpath,)) == 1 - assert main([file_path]) == 1 - - with open(file_path, 'rb') as file_obj: - assert file_obj.read() == ( - b'# -*- coding: utf-8 -*-\n' - b'import httplib\n' - ) + assert path.read_binary() == ( + b'# -*- coding: utf-8 -*-\n' + b'import httplib\n' + ) def test_integration_ok(tmpdir): - file_path = tmpdir.join('foo.py').strpath - with open(file_path, 'wb') as file_obj: - file_obj.write(b'# -*- coding: utf-8 -*-\nx = 1\n') - assert main([file_path]) == 0 + path = tmpdir.join('foo.py') + path.write_binary(b'# -*- coding: utf-8 -*-\nx = 1\n') + assert main((path.strpath,)) == 0 + + +def test_integration_remove(tmpdir): + path = tmpdir.join('foo.py') + path.write_binary(b'# -*- coding: utf-8 -*-\nx = 1\n') + + assert main((path.strpath, '--remove')) == 1 + + assert path.read_binary() == b'x = 1\n' + + +def test_integration_remove_ok(tmpdir): + path = tmpdir.join('foo.py') + path.write_binary(b'x = 1\n') + assert main((path.strpath, '--remove')) == 0 @pytest.mark.parametrize( 'input_str', ( b'', - b'# -*- coding: utf-8 -*-\n', + ( + b'# -*- coding: utf-8 -*-\n' + b'x = 1\n' + ), ( b'#!/usr/bin/env python\n' b'# -*- coding: utf-8 -*-\n' @@ -59,20 +73,32 @@ def test_ok_inputs(input_str): b'import httplib\n', ), ( - b'#!/usr/bin/env python\n', + b'#!/usr/bin/env python\n' + b'x = 1\n', b'#!/usr/bin/env python\n' b'# -*- coding: utf-8 -*-\n' + b'x = 1\n', ), ( - b'#coding=utf-8\n', + b'#coding=utf-8\n' + b'x = 1\n', b'# -*- coding: utf-8 -*-\n' + b'x = 1\n', ), ( b'#!/usr/bin/env python\n' - b'#coding=utf8\n', + b'#coding=utf8\n' + b'x = 1\n', b'#!/usr/bin/env python\n' - b'# -*- coding: utf-8 -*-\n', + b'# -*- coding: utf-8 -*-\n' + b'x = 1\n', ), + # These should each get truncated + (b'#coding: utf-8\n', b''), + (b'# -*- coding: utf-8 -*-\n', b''), + (b'#!/usr/bin/env python\n', b''), + (b'#!/usr/bin/env python\n#coding: utf8\n', b''), + (b'#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n', b''), ) ) def test_not_ok_inputs(input_str, output):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==1.3.2 attrs==22.2.0 autopep8==2.0.4 certifi==2021.5.30 cfgv==3.3.1 coverage==6.2 distlib==0.3.9 filelock==3.4.1 flake8==2.5.5 identify==2.4.4 importlib-metadata==4.2.0 importlib-resources==5.2.3 iniconfig==1.1.1 logilab-common==1.9.7 mccabe==0.4.0 mock==5.2.0 mypy-extensions==1.0.0 nodeenv==1.6.0 packaging==21.3 pep8==1.7.1 platformdirs==2.4.0 pluggy==1.0.0 pre-commit==2.17.0 -e git+https://github.com/pre-commit/pre-commit-hooks.git@17478a0a50faf20fd8e5b3fefe7435cea410df0b#egg=pre_commit_hooks py==1.11.0 pycodestyle==2.10.0 pyflakes==1.0.0 pylint==1.3.1 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 simplejson==3.20.1 six==1.17.0 toml==0.10.2 tomli==1.2.3 typing_extensions==4.1.1 virtualenv==20.16.2 zipp==3.6.0
name: pre-commit-hooks channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - astroid==1.3.2 - attrs==22.2.0 - autopep8==2.0.4 - cfgv==3.3.1 - coverage==6.2 - distlib==0.3.9 - filelock==3.4.1 - flake8==2.5.5 - identify==2.4.4 - importlib-metadata==4.2.0 - importlib-resources==5.2.3 - iniconfig==1.1.1 - logilab-common==1.9.7 - mccabe==0.4.0 - mock==5.2.0 - mypy-extensions==1.0.0 - nodeenv==1.6.0 - packaging==21.3 - pep8==1.7.1 - platformdirs==2.4.0 - pluggy==1.0.0 - pre-commit==2.17.0 - py==1.11.0 - pycodestyle==2.10.0 - pyflakes==1.0.0 - pylint==1.3.1 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - simplejson==3.20.1 - six==1.17.0 - toml==0.10.2 - tomli==1.2.3 - typing-extensions==4.1.1 - virtualenv==20.16.2 - zipp==3.6.0 prefix: /opt/conda/envs/pre-commit-hooks
[ "tests/fix_encoding_pragma_test.py::test_integration_remove", "tests/fix_encoding_pragma_test.py::test_integration_remove_ok", "tests/fix_encoding_pragma_test.py::test_not_ok_inputs[#!/usr/bin/env", "tests/fix_encoding_pragma_test.py::test_not_ok_inputs[#coding:", "tests/fix_encoding_pragma_test.py::test_not_ok_inputs[#" ]
[]
[ "tests/fix_encoding_pragma_test.py::test_integration_inserting_pragma", "tests/fix_encoding_pragma_test.py::test_integration_ok", "tests/fix_encoding_pragma_test.py::test_ok_inputs[]", "tests/fix_encoding_pragma_test.py::test_ok_inputs[#", "tests/fix_encoding_pragma_test.py::test_ok_inputs[#!/usr/bin/env", "tests/fix_encoding_pragma_test.py::test_not_ok_inputs[import", "tests/fix_encoding_pragma_test.py::test_not_ok_inputs[#coding=utf-8\\nx" ]
[]
MIT License
515
marshmallow-code__apispec-70
fe3f7a02358e65a7942d3d5d4d81c6a17844c6ce
2016-04-28 23:37:34
0aa7b1be3af715eace95c0e730f98ac6f5a03c64
diff --git a/apispec/ext/flask.py b/apispec/ext/flask.py index 19c029f..a6c1e97 100644 --- a/apispec/ext/flask.py +++ b/apispec/ext/flask.py @@ -27,6 +27,11 @@ function to `add_path`. Inspects URL rules and view docstrings. from __future__ import absolute_import import re +try: + from urllib.parse import urljoin +except ImportError: + from urlparse import urljoin + from flask import current_app from apispec.compat import iteritems @@ -61,6 +66,8 @@ def path_from_view(spec, view, **kwargs): """Path helper that allows passing a Flask view function.""" rule = _rule_for_view(view) path = flaskpath2swagger(rule.rule) + app_root = current_app.config['APPLICATION_ROOT'] or '/' + path = urljoin(app_root.rstrip('/') + '/', path.lstrip('/')) operations = utils.load_operations_from_docstring(view.__doc__) path = Path(path=path, operations=operations) return path
Flask extension does not support application root The flask extension only outputs the route path, but `flask.url_for()` takes into consideration that the path should be prefixed with the configured `APPLICATION_ROOT` path. [apispec/ext/flask.py#L58](https://github.com/marshmallow-code/apispec/blob/1076180/apispec/ext/flask.py#L58) - http://flask.pocoo.org/docs/0.10/config/#builtin-configuration-values - https://github.com/pallets/flask/blob/9f1be8e/flask/helpers.py#L309 - https://github.com/pallets/flask/blob/2bf477c/flask/app.py#L1761
marshmallow-code/apispec
diff --git a/tests/test_ext_flask.py b/tests/test_ext_flask.py index 0f6f292..eeb4a03 100644 --- a/tests/test_ext_flask.py +++ b/tests/test_ext_flask.py @@ -105,3 +105,36 @@ class TestPathHelpers: spec.add_path(view=get_pet) assert '/pet/{pet_id}' in spec._paths + + def test_path_includes_app_root(self, app, spec): + + app.config['APPLICATION_ROOT'] = '/app/root' + + @app.route('/partial/path/pet') + def get_pet(): + return 'pet' + + spec.add_path(view=get_pet) + assert '/app/root/partial/path/pet' in spec._paths + + def test_path_with_args_includes_app_root(self, app, spec): + + app.config['APPLICATION_ROOT'] = '/app/root' + + @app.route('/partial/path/pet/{pet_id}') + def get_pet(pet_id): + return 'representation of pet {pet_id}'.format(pet_id=pet_id) + + spec.add_path(view=get_pet) + assert '/app/root/partial/path/pet/{pet_id}' in spec._paths + + def test_path_includes_app_root_with_right_slash(self, app, spec): + + app.config['APPLICATION_ROOT'] = '/app/root/' + + @app.route('/partial/path/pet') + def get_pet(): + return 'pet' + + spec.add_path(view=get_pet) + assert '/app/root/partial/path/pet' in spec._paths
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/marshmallow-code/apispec.git@fe3f7a02358e65a7942d3d5d4d81c6a17844c6ce#egg=apispec backports.tarfile==1.2.0 blinker==1.9.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 colorama==0.4.6 cryptography==44.0.2 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 filelock==3.18.0 flake8==2.5.4 Flask==3.1.0 id==1.5.0 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 invoke==2.2.0 itsdangerous==2.2.0 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jeepney==0.9.0 Jinja2==3.1.6 keyring==25.6.0 markdown-it-py==3.0.0 MarkupSafe==3.0.2 marshmallow==3.26.1 mccabe==0.4.0 mdurl==0.1.2 mock==5.2.0 more-itertools==10.6.0 nh3==0.2.21 packaging==24.2 pep8==1.7.1 platformdirs==4.3.7 pluggy==1.5.0 pycparser==2.22 pyflakes==1.0.0 Pygments==2.19.1 pyproject-api==1.9.0 pytest==8.3.5 PyYAML==6.0.2 readme_renderer==44.0 requests==2.32.3 requests-toolbelt==1.0.0 rfc3986==2.0.0 rich==14.0.0 SecretStorage==3.3.3 tomli==2.2.1 tornado==6.4.2 tox==4.25.0 twine==6.1.0 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 Werkzeug==3.1.3 zipp==3.21.0
name: apispec channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - backports-tarfile==1.2.0 - blinker==1.9.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - colorama==0.4.6 - cryptography==44.0.2 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - filelock==3.18.0 - flake8==2.5.4 - flask==3.1.0 - id==1.5.0 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - invoke==2.2.0 - itsdangerous==2.2.0 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jeepney==0.9.0 - jinja2==3.1.6 - keyring==25.6.0 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - marshmallow==3.26.1 - mccabe==0.4.0 - mdurl==0.1.2 - mock==5.2.0 - more-itertools==10.6.0 - nh3==0.2.21 - packaging==24.2 - pep8==1.7.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pycparser==2.22 - pyflakes==1.0.0 - pygments==2.19.1 - pyproject-api==1.9.0 - pytest==8.3.5 - pyyaml==6.0.2 - readme-renderer==44.0 - requests==2.32.3 - requests-toolbelt==1.0.0 - rfc3986==2.0.0 - rich==14.0.0 - secretstorage==3.3.3 - tomli==2.2.1 - tornado==6.4.2 - tox==4.25.0 - twine==6.1.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - virtualenv==20.29.3 - werkzeug==3.1.3 - zipp==3.21.0 prefix: /opt/conda/envs/apispec
[ "tests/test_ext_flask.py::TestPathHelpers::test_path_includes_app_root", "tests/test_ext_flask.py::TestPathHelpers::test_path_with_args_includes_app_root", "tests/test_ext_flask.py::TestPathHelpers::test_path_includes_app_root_with_right_slash" ]
[ "tests/test_ext_flask.py::TestPathHelpers::test_integration_with_docstring_introspection" ]
[ "tests/test_ext_flask.py::TestPathHelpers::test_path_from_view", "tests/test_ext_flask.py::TestPathHelpers::test_path_with_multiple_methods", "tests/test_ext_flask.py::TestPathHelpers::test_path_is_translated_to_swagger_template" ]
[]
MIT License
516
auth0__auth0-python-40
013851d48025ec202464721c23d65156cd138565
2016-04-29 12:24:26
9a1050760af2337e0a32d68038e6b1df62ca45f9
diff --git a/auth0/v2/authentication/users.py b/auth0/v2/authentication/users.py index e031a75..bec1b4d 100644 --- a/auth0/v2/authentication/users.py +++ b/auth0/v2/authentication/users.py @@ -46,5 +46,5 @@ class Users(AuthenticationBase): return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, - headers={'Content-Type: application/json'} + headers={'Content-Type': 'application/json'} )
authentication.Users(client_domain).tokeninfo fails I've got a traceback: ```python In [78]: user_authentication.tokeninfo(id_token) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-78-decf4417ce18> in <module>() ----> 1 user_authentication.tokeninfo(id_token) /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/auth0/v2/authentication/users.pyc in tokeninfo(self, jwt) 47 url='https://%s/tokeninfo' % self.domain,  48 data={'id_token': jwt}, ---> 49 headers={'Content-Type: application/json'} 50 ) /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/auth0/v2/authentication/base.pyc in post(self, url, data, headers) 8 def post(self, url, data={}, headers={}): 9 response = requests.post(url=url, data=json.dumps(data), ---> 10 headers=headers) 11 return self._process_response(response) 12 /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/api.pyc in post(url, data, json, **kwargs) 107 """ 108 --> 109 return request('post', url, data=data, json=json, **kwargs) 110 111 /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/api.pyc in request(method, url, **kwargs) 48 49 session = sessions.Session() ---> 50 response = session.request(method=method, url=url, **kwargs) 51 # By explicitly closing the session, we avoid leaving sockets open which 52 # can trigger a ResourceWarning in some cases, and look like a memory leak /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, jso n) 452 hooks = hooks, 453 ) --> 454 prep = self.prepare_request(req) 455 456 proxies = proxies or {} /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/sessions.pyc in prepare_request(self, request) 386 auth=merge_setting(auth, self.auth), 387 cookies=merged_cookies, --> 388 hooks=merge_hooks(request.hooks, self.hooks), 389 ) 390 return p /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/models.pyc in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json) 292 self.prepare_method(method) 293 self.prepare_url(url, params) --> 294 self.prepare_headers(headers) 295 self.prepare_cookies(cookies) 296 self.prepare_body(data, files, json) /home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/models.pyc in prepare_headers(self, headers) 400 401 if headers: --> 402 self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) 403 else: 404 self.headers = CaseInsensitiveDict() AttributeError: 'set' object has no attribute 'items' ```
auth0/auth0-python
diff --git a/auth0/v2/test/authentication/test_users.py b/auth0/v2/test/authentication/test_users.py index c842f55..446301d 100644 --- a/auth0/v2/test/authentication/test_users.py +++ b/auth0/v2/test/authentication/test_users.py @@ -27,5 +27,5 @@ class TestUsers(unittest.TestCase): mock_post.assert_called_with( url='https://my.domain.com/tokeninfo', data={'id_token': 'jwtoken'}, - headers={'Content-Type: application/json'} + headers={'Content-Type': 'application/json'} )
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
2.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 -e git+https://github.com/auth0/auth0-python.git@013851d48025ec202464721c23d65156cd138565#egg=auth0_python certifi==2021.5.30 importlib-metadata==4.8.3 iniconfig==1.1.1 mock==1.3.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 requests==2.8.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: auth0-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==1.3.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.8.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/auth0-python
[ "auth0/v2/test/authentication/test_users.py::TestUsers::test_tokeninfo" ]
[]
[ "auth0/v2/test/authentication/test_users.py::TestUsers::test_userinfo" ]
[]
MIT License
517
4degrees__clique-26
a89507304acce5931f940c34025a6547fa8227b5
2016-04-30 17:21:04
a89507304acce5931f940c34025a6547fa8227b5
diff --git a/source/clique/collection.py b/source/clique/collection.py index 0c3b296..db9276c 100644 --- a/source/clique/collection.py +++ b/source/clique/collection.py @@ -251,15 +251,25 @@ class Collection(object): else: data['padding'] = '%d' - if self.indexes: + if '{holes}' in pattern: data['holes'] = self.holes().format('{ranges}') + if '{range}' in pattern or '{ranges}' in pattern: indexes = list(self.indexes) - if len(indexes) == 1: + indexes_count = len(indexes) + + if indexes_count == 0: + data['range'] = '' + + elif indexes_count == 1: data['range'] = '{0}'.format(indexes[0]) + else: - data['range'] = '{0}-{1}'.format(indexes[0], indexes[-1]) + data['range'] = '{0}-{1}'.format( + indexes[0], indexes[-1] + ) + if '{ranges}' in pattern: separated = self.separate() if len(separated) > 1: ranges = [collection.format('{range}') @@ -270,11 +280,6 @@ class Collection(object): data['ranges'] = ', '.join(ranges) - else: - data['holes'] = '' - data['range'] = '' - data['ranges'] = '' - return pattern.format(**data) def is_contiguous(self):
collection.format hits maximum recursion depth for collections with lots of holes. The following code gives an example. ```python paths = ["name.{0:04d}.jpg".format(x) for x in range(2000)[::2]] collection = clique.assemble(paths)[0][0] collection.format("{head}####{tail}") ```
4degrees/clique
diff --git a/test/unit/test_collection.py b/test/unit/test_collection.py index ce4daa7..11cb01e 100644 --- a/test/unit/test_collection.py +++ b/test/unit/test_collection.py @@ -2,6 +2,7 @@ # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. +import sys import inspect import pytest @@ -242,7 +243,6 @@ def test_remove_non_member(): (PaddedCollection, '{range}', '1-12'), (PaddedCollection, '{ranges}', '1-3, 7, 9-12'), (PaddedCollection, '{holes}', '4-6, 8'), - ]) def test_format(CollectionCls, pattern, expected): '''Format collection according to pattern.''' @@ -250,6 +250,25 @@ def test_format(CollectionCls, pattern, expected): assert collection.format(pattern) == expected +def test_format_sparse_collection(): + '''Format sparse collection without recursion error.''' + recursion_limit = sys.getrecursionlimit() + recursion_error_occurred = False + + try: + collection = PaddedCollection( + indexes=set(range(0, recursion_limit * 2, 2)) + ) + collection.format() + except RuntimeError as error: + if 'maximum recursion depth exceeded' in str(error): + recursion_error_occurred = True + else: + raise + + assert not recursion_error_occurred + + @pytest.mark.parametrize(('collection', 'expected'), [ (PaddedCollection(indexes=set([])), True), (PaddedCollection(indexes=set([1])), True),
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=2.3.5" ], "pre_install": null, "python": "2.7", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 -e git+https://github.com/4degrees/clique.git@a89507304acce5931f940c34025a6547fa8227b5#egg=Clique importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: clique channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/clique
[ "test/unit/test_collection.py::test_format_sparse_collection" ]
[ "test/unit/test_collection.py::test_change_property[head-diff_head.-^diff\\\\_head\\\\.(?P<index>(?P<padding>0*)\\\\d+?)\\\\.tail$-diff_head.1.tail]", "test/unit/test_collection.py::test_change_property[tail-.diff_tail-^head\\\\.(?P<index>(?P<padding>0*)\\\\d+?)\\\\.diff\\\\_tail$-head.1.diff_tail]" ]
[ "test/unit/test_collection.py::test_change_property[padding-4-^head\\\\.(?P<index>(?P<padding>0*)\\\\d+?)\\\\.tail$-head.0001.tail]", "test/unit/test_collection.py::test_unsettable_indexes", "test/unit/test_collection.py::test_str", "test/unit/test_collection.py::test_repr", "test/unit/test_collection.py::test_iterator[unpadded-collection]", "test/unit/test_collection.py::test_iterator[padded-collection]", "test/unit/test_collection.py::test_contains[valid", "test/unit/test_collection.py::test_contains[different", "test/unit/test_collection.py::test_contains[non-member", "test/unit/test_collection.py::test_comparisons[equal]", "test/unit/test_collection.py::test_comparisons[different", "test/unit/test_collection.py::test_not_implemented_comparison", "test/unit/test_collection.py::test_match[different", "test/unit/test_collection.py::test_match[unpadded-collection:unpadded", "test/unit/test_collection.py::test_match[unpadded-collection:padded", "test/unit/test_collection.py::test_match[padded-collection:padded", "test/unit/test_collection.py::test_match[padded-collection:unpadded", "test/unit/test_collection.py::test_add[unpadded-collection:unpadded", "test/unit/test_collection.py::test_add[unpadded-collection:padded", "test/unit/test_collection.py::test_add[padded-collection:padded", "test/unit/test_collection.py::test_add[padded-collection:unpadded", "test/unit/test_collection.py::test_add_duplicate", "test/unit/test_collection.py::test_remove", "test/unit/test_collection.py::test_remove_non_member", "test/unit/test_collection.py::test_format[PaddedCollection-{head}-/head.]", "test/unit/test_collection.py::test_format[PaddedCollection-{padding}-%04d]", "test/unit/test_collection.py::test_format[UnpaddedCollection-{padding}-%d]", "test/unit/test_collection.py::test_format[PaddedCollection-{tail}-.ext]", "test/unit/test_collection.py::test_format[PaddedCollection-{range}-1-12]", "test/unit/test_collection.py::test_format[PaddedCollection-{ranges}-1-3,", "test/unit/test_collection.py::test_format[PaddedCollection-{holes}-4-6,", "test/unit/test_collection.py::test_is_contiguous[empty]", "test/unit/test_collection.py::test_is_contiguous[single]", "test/unit/test_collection.py::test_is_contiguous[contiguous", "test/unit/test_collection.py::test_is_contiguous[non-contiguous]", "test/unit/test_collection.py::test_holes[empty]", "test/unit/test_collection.py::test_holes[single", "test/unit/test_collection.py::test_holes[contiguous", "test/unit/test_collection.py::test_holes[missing", "test/unit/test_collection.py::test_holes[range", "test/unit/test_collection.py::test_holes[multiple", "test/unit/test_collection.py::test_is_compatible[compatible]", "test/unit/test_collection.py::test_is_compatible[incompatible", "test/unit/test_collection.py::test_compatible_merge[both", "test/unit/test_collection.py::test_compatible_merge[complimentary]", "test/unit/test_collection.py::test_compatible_merge[duplicates]", "test/unit/test_collection.py::test_incompatible_merge[incompatible", "test/unit/test_collection.py::test_separate[empty]", "test/unit/test_collection.py::test_separate[single", "test/unit/test_collection.py::test_separate[contiguous", "test/unit/test_collection.py::test_separate[non-contiguous", "test/unit/test_collection.py::test_escaping_expression" ]
[]
Apache License 2.0
518
sigmavirus24__github3.py-606
1a7455c6c5098603b33c15576624e63ce6751bf7
2016-05-02 17:13:26
05ed0c6a02cffc6ddd0e82ce840c464e1c5fd8c4
diff --git a/github3/orgs.py b/github3/orgs.py index 0b8cda6a..62b3652c 100644 --- a/github3/orgs.py +++ b/github3/orgs.py @@ -255,6 +255,11 @@ class Organization(BaseAccount): # Roles available to members in an organization. members_roles = frozenset(['all', 'admin', 'member']) + def _all_events_url(self, username): + url_parts = list(self._uri) + url_parts[2] = 'users/{}/events{}'.format(username, url_parts[2]) + return self._uri.__class__(*url_parts).geturl() + def _update_attributes(self, org): super(Organization, self)._update_attributes(org) self.type = self.type or 'Organization' @@ -453,8 +458,39 @@ class Organization(BaseAccount): url = self._build_url('public_members', username, base_url=self._api) return self._boolean(self._get(url), 204, 404) + def all_events(self, number=-1, etag=None, username=None): + r"""Iterate over all org events visible to the authenticated user. + + :param int number: (optional), number of events to return. Default: -1 + iterates over all events available. + :param str etag: (optional), ETag from a previous request to the same + endpoint + :param str username: (required), the username of the currently + authenticated user. + :returns: generator of :class:`Event <github3.events.Event>`\ s + """ + url = self._all_events_url(username) + return self._iter(int(number), url, Event, etag=etag) + def events(self, number=-1, etag=None): - r"""Iterate over events for this org. + r"""Iterate over public events for this org (deprecated). + + :param int number: (optional), number of events to return. Default: -1 + iterates over all events available. + :param str etag: (optional), ETag from a previous request to the same + endpoint + :returns: generator of :class:`Event <github3.events.Event>`\ s + + Deprecated: Use ``public_events`` instead. + """ + + warnings.warn( + 'This method is deprecated. Please use ``public_events`` instead.', + DeprecationWarning) + return self.public_events(number, etag=etag) + + def public_events(self, number=-1, etag=None): + r"""Iterate over public events for this org. :param int number: (optional), number of events to return. Default: -1 iterates over all events available.
Organization.events should be public_events I just discovered that `Organization.events` lists only the public events of an organization, and excludes the events to private repositories. The resource that includes private events is: ``` GET /users/:username/events/orgs/:org ``` Source: https://developer.github.com/v3/activity/events/#list-events-for-an-organization It seems there should be two functions which seems could either be named: - `events` -- all events (must be a member of the organization) - `public_events` -- all public events or - `all_events` -- all events (must be a member of the organization) - `events` -- all public events The latter doesn't seem like a good fit, however, as `all_events` corresponds to public events at the top-level: https://github3py.readthedocs.io/en/latest/api.html?highlight=all_events#github3.all_events However, using the former requires a breaking change to what currently exists in the alpha version. Since 1.0 is in alpha that could be okay, but may break people's code who aren't locking their dependencies on the precise alpha version. I'm happy to implement the function when I get a chance, I would just like to know which of these naming schemes is preferred (or another one altogether). Thanks! ## <bountysource-plugin> --- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/33479528-organization-events-should-be-public_events?utm_campaign=plugin&utm_content=tracker%2F183477&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F183477&utm_medium=issues&utm_source=github). </bountysource-plugin>
sigmavirus24/github3.py
diff --git a/LATEST_VERSION_NOTES.rst b/LATEST_VERSION_NOTES.rst index 73d8fa34..2d523618 100644 --- a/LATEST_VERSION_NOTES.rst +++ b/LATEST_VERSION_NOTES.rst @@ -1,5 +1,11 @@ .. vim: set tw=100 +Unreleased +~~~~~~~~~~ + +- Add ``Organization#all_events``. +- Deprecate ``Organization#events`` in favor of ``Organization#public_events``. + 1.0.0a4: 2016-02-19 ~~~~~~~~~~~~~~~~~~~ diff --git a/tests/cassettes/Organization_all_events.json b/tests/cassettes/Organization_all_events.json new file mode 100644 index 00000000..06304ffa --- /dev/null +++ b/tests/cassettes/Organization_all_events.json @@ -0,0 +1,1 @@ +{"recorded_with": "betamax/0.5.1", "http_interactions": [{"request": {"headers": {"User-Agent": "github3.py/1.0.0a4", "Accept-Encoding": "gzip, deflate", "Content-Type": "application/json", "Accept": "application/vnd.github.v3.full+json", "Accept-Charset": "utf-8", "Authorization": "token <AUTH_TOKEN>", "Connection": "keep-alive"}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.github.com/orgs/praw-dev", "method": "GET"}, "response": {"headers": {"Server": "GitHub.com", "Content-Type": "application/json; charset=utf-8", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "X-OAuth-Scopes": "repo", "Cache-Control": "private, max-age=60, s-maxage=60", "X-GitHub-Media-Type": "github.v3; param=full; format=json", "Content-Encoding": "gzip", "Transfer-Encoding": "chunked", "X-Accepted-OAuth-Scopes": "admin:org, read:org, repo, user, write:org", "X-RateLimit-Limit": "5000", "X-RateLimit-Reset": "1462322134", "X-RateLimit-Remaining": "4989", "X-Frame-Options": "deny", "Access-Control-Allow-Origin": "*", "Last-Modified": "Sat, 23 Jan 2016 18:15:03 GMT", "Status": "200 OK", "ETag": "W/\"ea404ad7fb8166ea4147395dc5d3ca08\"", "X-GitHub-Request-Id": "CEA95BCA:FD17:F5AFD:57293868", "Vary": "Accept, Authorization, Cookie, X-GitHub-OTP", "Content-Security-Policy": "default-src 'none'", "X-Served-By": "139317cebd6caf9cd03889139437f00b", "Date": "Tue, 03 May 2016 23:46:49 GMT", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "X-XSS-Protection": "1; mode=block", "X-Content-Type-Options": "nosniff"}, "body": {"encoding": "utf-8", "base64_string": "H4sIAAAAAAAAA51Sy27bMBD8FYPX2tErVmwCRRIgPfTUoAhQoBdhSTESEYokSMqGY/jfu7TkRHEucW/kcme4M7N7okwjNaHEOtguarEhcyJrQrNyXa5WqznpncLXNgTraZKAlVeNDG3PrrjpEuMan0yQTljjq69DkiMAvxQbocNFyAGB0NaYl4uQR0CU6X0vLkIOCIR2omPCXYQdIftkOByQxfZMSV79B9lH5JQTNhDAnUdwLPoxud4Lx40O6PgxxD4Zw77dfC9wrFp47qQN0sS9wIKGTuDpcRdao2e/RV3LMLt//Dn748Ba4WYPGIYytkNGbEdOC3pHqO6VmhOGGzbwKMNhZP0BLrQx9w5k3K93N4aNoNdv9jTSB09oOifPRimzRd8nN6mRHN/a0Kkz1ZM9nawodwKCqCsI+G2eZvkiXS7S7CnPaZbTYvkXR+lt/aGnxIZFXjxlK5otaVrEnrCz0ZRfrgEtXwddWDUBVGWdRMdFNWrB8cxW45+f66fKu8ha+peq99Age1YWN2gER93AjINgRu1MKoXKq5N9jL0yt+PiWxR610RTY7TRVQWY4v6U4bMTAqveAkf+9U25LPPr9Rr7zkY+HP4BnIZbmhsEAAA=", "string": ""}, "status": {"code": 200, "message": "OK"}, "url": "https://api.github.com/orgs/praw-dev"}, "recorded_at": "2016-05-03T23:46:49"}, {"request": {"headers": {"User-Agent": "github3.py/1.0.0a4", "Accept-Encoding": "gzip, deflate", "Content-Type": "application/json", "Accept": "application/vnd.github.v3.full+json", "Accept-Charset": "utf-8", "Authorization": "token <AUTH_TOKEN>", "Connection": "keep-alive"}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.github.com/user", "method": "GET"}, "response": {"headers": {"Server": "GitHub.com", "Content-Type": "application/json; charset=utf-8", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "X-OAuth-Scopes": "repo", "Cache-Control": "private, max-age=60, s-maxage=60", "X-GitHub-Media-Type": "github.v3; param=full; format=json", "Content-Encoding": "gzip", "Transfer-Encoding": "chunked", "X-Accepted-OAuth-Scopes": "", "X-RateLimit-Limit": "5000", "X-RateLimit-Reset": "1462322134", "X-RateLimit-Remaining": "4988", "X-Frame-Options": "deny", "Access-Control-Allow-Origin": "*", "Last-Modified": "Thu, 21 Apr 2016 23:10:46 GMT", "Status": "200 OK", "ETag": "W/\"7b4d32554fa33ad7750b8c67afabac34\"", "X-GitHub-Request-Id": "CEA95BCA:FD17:F5B52:57293869", "Vary": "Accept, Authorization, Cookie, X-GitHub-OTP", "Content-Security-Policy": "default-src 'none'", "X-Served-By": "474556b853193c38f1b14328ce2d1b7d", "Date": "Tue, 03 May 2016 23:46:49 GMT", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "X-XSS-Protection": "1; mode=block", "X-Content-Type-Options": "nosniff"}, "body": {"encoding": "utf-8", "base64_string": "H4sICEk6KVcAA2ZvbwCrVsrJT8/MU7JSSkrKT1WqBQAOtiqcEAAAAA==", "string": ""}, "status": {"code": 200, "message": "OK"}, "url": "https://api.github.com/user"}, "recorded_at": "2016-05-03T23:46:49"}, {"request": {"headers": {"User-Agent": "github3.py/1.0.0a4", "Accept-Encoding": "gzip, deflate", "Content-Type": "application/json", "Accept": "application/vnd.github.v3.full+json", "Accept-Charset": "utf-8", "Authorization": "token <AUTH_TOKEN>", "Connection": "keep-alive"}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.github.com/users/bboe/events/orgs/praw-dev?per_page=100", "method": "GET"}, "response": {"headers": {"X-Poll-Interval": "60", "Server": "GitHub.com", "Content-Type": "application/json; charset=utf-8", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "X-Accepted-OAuth-Scopes": "", "Cache-Control": "private, max-age=60, s-maxage=60", "X-RateLimit-Remaining": "4987", "Date": "Tue, 03 May 2016 23:46:50 GMT", "Last-Modified": "Tue, 03 May 2016 14:40:11 GMT", "X-OAuth-Scopes": "repo", "Transfer-Encoding": "chunked", "X-RateLimit-Limit": "5000", "X-RateLimit-Reset": "1462322134", "Link": "<https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=2>; rel=\"next\", <https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=3>; rel=\"last\"", "X-Frame-Options": "deny", "Access-Control-Allow-Origin": "*", "X-Served-By": "593010132f82159af0ded24b4932e109", "Status": "200 OK", "ETag": "W/\"aaec7c9c419bf77af766f3f8a5cd3be1\"", "X-GitHub-Media-Type": "github.v3; param=full; format=json", "X-GitHub-Request-Id": "CEA95BCA:FD17:F5B64:57293869", "Vary": "Accept, Authorization, Cookie, X-GitHub-OTP", "Content-Security-Policy": "default-src 'none'", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "Content-Encoding": "gzip", "X-XSS-Protection": "1; mode=block", "X-Content-Type-Options": "nosniff"}, "body": {"encoding": "utf-8", "base64_string": "H4sIAAAAAAAAA+y97ZbjxpUt+Cro9I8q2ZkkwW+yLUu6arldd7rbtdTl0bqj8mKBBJiEkyRogMwUlUuz5iHmMeYt5k3mSWafiMBHACAIRKCkSinKclUmidgIBICIE/ucs8/3zze+ezO/GczG41l/Zo97N7c3x/PBw2d/DsKHbx69/REfOatjEN7M+dH2YNif2rc32+De3+PAf0RHb/ujF+K4+9B5dI5OuGCo+OAUbvHD5ng8RPNu1zn4nXv/uDktO6tg1z1FXhh1M81F41wjhhiJhtRmFeyP6BfH6PLufHHz0+1N6B2CuJfT4WQ2mtze7J0dXc0hdJ7uXO+xSz9c6xjhROzItAngD855Gzi4suebNQbHAy4fkdFkNhkP7al0NpxkfdpuF6ID8WXGHQie9hgyAJQMI41ePMo6Y/L4+UD/pmyOu+1CviWZe5i5e+tguw2ecEtzR1fe9W7SisaLIfj7ewUEtHruBseNFy7oGfmJLtyPjs06w1o8d+kfPMKEEe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bzvmdXW3ffam6rue2Zm0Nz3LJop7ntGJurte9amqO37j42/pZ2ILLM5Rmzbaz5NaX/GmLHO/owtM5X9GUPmGvuesWkK+54xc339sFeHt/yTKnjZFscbvBDTtPX9jqnF27AU53ljBrr6nqES1DFV1Z95v/oWSyaIiUNWTScp6ntdnElPPxjG3Ym0/3cvf3zip4fPCi574gdh9NpN19L3+meipO+ZmEdH3zNqpqI/+0iNNPQ9SxMV9P1B32yRcXC/E52UEB31u8Hb8SXU872OT9HO90xNVM73Xxckb9x/pFwatM5nMoltfs9PABzAkAvfOFI3D008c9eB1MQr+Kj3m5G6eXftg/Ek5fdXdPPdLr6mmj/761c082fbXFXMd1ug/wZ6eTcmYQIqjanV1Orln57T7Sa7Wau0Z2NevsWR5HzmepHV440P2nme49V6eSN+sAZgX4P8QSYinsQRLzIWId7ucBEnecFEkWZOwRMncdIoZOf5wUj1GyaeB4lumIZ+WAQRQx/8nOf4LuQ5aFUFuBgU6vlSIP/qw+b0sDoKRRXeIIU2Qf7H56cnsIVnhfpH32xDCtZ4ILOMz4/icf9erJ53gMSJN70rNm+fMSDgR68K7CBWe7nLP846LqNvUicEotbLRWYKCX0PCWJaIRCrjLiujGBugIliEl1BYxZrlE54SsyPoG5CThDh+cgjkCDgmccepwin48agLBTifKYQjQsu17NH36SeZ3uUiXyJmqfAdSPHapKb6t8yjnE5Z0gcx6BWTyMuZOO9tPbsFOUMgjCGgjFJHA6dkhNFIvNY5qEagSNYHqZBjL8oZAUyIxT4+bkW8oy/4CyeTWUFekThr7enGT26oz3coRxxUCn78qy7iFPLr/8fkigthw6FBgA=", "string": ""}, "status": {"code": 200, "message": "OK"}, "url": "https://api.github.com/users/bboe/events/orgs/praw-dev?per_page=100"}, "recorded_at": "2016-05-03T23:46:50"}, {"request": {"headers": {"User-Agent": "github3.py/1.0.0a4", "Accept-Encoding": "gzip, deflate", "Content-Type": "application/json", "Accept": "application/vnd.github.v3.full+json", "Accept-Charset": "utf-8", "Authorization": "token <AUTH_TOKEN>", "Connection": "keep-alive"}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=2", "method": "GET"}, "response": {"headers": {"X-Poll-Interval": "60", "Server": "GitHub.com", "Content-Type": "application/json; charset=utf-8", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "X-Accepted-OAuth-Scopes": "", "Cache-Control": "private, max-age=60, s-maxage=60", "X-RateLimit-Remaining": "4986", "Date": "Tue, 03 May 2016 23:46:50 GMT", "Last-Modified": "Sun, 20 Mar 2016 07:28:16 GMT", "X-OAuth-Scopes": "repo", "Transfer-Encoding": "chunked", "X-RateLimit-Limit": "5000", "X-RateLimit-Reset": "1462322134", "Link": "<https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=3>; rel=\"next\", <https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=3>; rel=\"last\", <https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=1>; rel=\"first\", <https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=1>; rel=\"prev\"", "X-Frame-Options": "deny", "Access-Control-Allow-Origin": "*", "X-Served-By": "8a5c38021a5cd7cef7b8f49a296fee40", "Status": "200 OK", "ETag": "W/\"b4fc80ce6bccfa6c1c1c284ad498e1d4\"", "X-GitHub-Media-Type": "github.v3; param=full; format=json", "X-GitHub-Request-Id": "CEA95BCA:FD17:F5BAA:5729386A", "Vary": "Accept, Authorization, Cookie, X-GitHub-OTP", "Content-Security-Policy": "default-src 'none'", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "Content-Encoding": "gzip", "X-XSS-Protection": "1; mode=block", "X-Content-Type-Options": "nosniff"}, "body": {"encoding": "utf-8", "base64_string": "H4sIAAAAAAAAA+29bXPkNpIt/FcY2g/e3emWAPC9IvbO2B5PjCP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TwwsvT6M6DM9BoHs5c/5KiA/7n/weZaWsBgWIDAA==", "string": ""}, "status": {"code": 200, "message": "OK"}, "url": "https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=2"}, "recorded_at": "2016-05-03T23:46:50"}, {"request": {"headers": {"User-Agent": "github3.py/1.0.0a4", "Accept-Encoding": "gzip, deflate", "Content-Type": "application/json", "Accept": "application/vnd.github.v3.full+json", "Accept-Charset": "utf-8", "Authorization": "token <AUTH_TOKEN>", "Connection": "keep-alive"}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=3", "method": "GET"}, "response": {"headers": {"X-Poll-Interval": "60", "Server": "GitHub.com", "Content-Type": "application/json; charset=utf-8", "Access-Control-Expose-Headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "X-Accepted-OAuth-Scopes": "", "Cache-Control": "private, max-age=60, s-maxage=60", "X-RateLimit-Remaining": "4985", "Date": "Tue, 03 May 2016 23:46:51 GMT", "Last-Modified": "Sat, 12 Mar 2016 19:55:03 GMT", "X-OAuth-Scopes": "repo", "Transfer-Encoding": "chunked", "X-RateLimit-Limit": "5000", "X-RateLimit-Reset": "1462322134", "Link": "<https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=1>; rel=\"first\", <https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=2>; rel=\"prev\"", "X-Frame-Options": "deny", "Access-Control-Allow-Origin": "*", "X-Served-By": "e183f7c661b1bbc2c987b3c4dc7b04e0", "Status": "200 OK", "ETag": "W/\"971a2d5c640517963c8dcd33839b3ce1\"", "X-GitHub-Media-Type": "github.v3; param=full; format=json", "X-GitHub-Request-Id": "CEA95BCA:FD17:F5C19:5729386A", "Vary": "Accept, Authorization, Cookie, X-GitHub-OTP", "Content-Security-Policy": "default-src 'none'", "Strict-Transport-Security": "max-age=31536000; includeSubdomains; preload", "Content-Encoding": "gzip", "X-XSS-Protection": "1; mode=block", "X-Content-Type-Options": "nosniff"}, "body": {"encoding": "utf-8", "base64_string": "H4sIAAAAAAAAA+y9aXPkxpU1/Fdg+oOscDcL+1LxemRZYz+jCHuskNvjeF7JwcaSIOGuhVOoIkUx9N+fczMTSwKoIra2mzLabjVZhbxIJHI999xzv3u+ypKr9ZXlOY5r2oGvX725Oj7dM3z2zSm/+/0D2x3xURgf94ertbja9g1df3O12d9mO1wXRXuGS24P4UN4DA833CA+OB02+OHueLzP16tVeJ9d32bHu1N0He+3q1PODvlKFpUFGwW4tVwWouvj/e6I6ojyK16LL65+enN1YPf7om6+7QWO9+ZqF27pGe4P4ePbhD2s6IeX6kR2cn5lVQTm78OnzT7EQz1f3aNJ+PMZuuHrumUHzpurPPsRt7LfXCVZfsx28fGm/OTAUlQC/81XdyxMhHEb9aDf8E2oB0nAwsjwEyNI/JQFRphaQWobruUHYZDGscsiy0CJiKX7Az0SPggM24jdxA18x4pSO9BZEkSOybyI2XoYGo4TxxHKoKG32TG/Wn/3fJXfhSisx6FhR4nO3NBl9D/L8V3X0JkRMy/0EtdIYj0yAnrlp+OdeOdsG2b0KqPox+jwFLPf3tIH9BpwmWzo39EX2u/QE9BiW5bn4S1V9ssk0Y4sP2rHvcZ2+enAtP8JNyf2+8Nhf9CyXDuEWc4SLdvhinst3CUaveXD/gHdIws32oa36W1+jVsV7Xu1Ph5O7IUO1vEyV7I9Vr1b4ac3ZcN5epAGno23zliSWngdpodXZNmmG+tx6rumoxsBvdtZGu4dNdq3LEkyDDxq6i16fs4bqPw0P0XbLM+z/S7X8PPHaaq+z101Vah7ccT0IDTChEVGbMcJ8z3TS9E8rm95aWyHse4nczUV9bH8dH+/Pxw1jBHtL/Ehuz9+ie47a6fp/Vj1lug9vGfpNMVoy3k7lP3k9pRtktkHUe+566e/0yRK/TMuRm58YOGRJTfhEXOEqRvuW916a5jvjGDtOGvd+v/RN/aH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0YyiKQqIfgvMMgvOeb8MBikMsE1P2fwWyLNRomhjMEZs6f9J7EOb6CNn/PTxc4Ue3sEMfyv7v8R0TP3Tih57Tepz4oafJsqhVwhbvofYikycLnKEDvWzK/ieqSkvYApvcxA8t1qRJvqO2/IyDx8ozss4EnvihEz+0eUY95VFO2f/DPPEp+7/1uH7qNSNO55T9j1BAT4bFlP0/8UN7vzRT9r9QHIy36Q2OQcMW+Cn7f7dfr9hAcvaU/X8kMGLjQ/lxVAz7cLXg5OcKvXPYu/mv5odKFJk49kLTCz+1H5MbvM1dKYKNJv9zPFfPGgHBguj5K2f/E7lASu48uux/MCJIgA1UGpBwKII3F5sBJ+LckbA4xaboj+f4oVP2f6Erh8k6abuCaHd+mapDsaOR8+QSMWX/V2hSOuDQhO5O6G4THJomcCvnWS4/E7o7abueQrYmbdfh+aaTtmvH9CaCT7k0rKJlOVyPgOxN2q5D1Kmvpuz/KftfVSo7vTOIQi/VvOtJ23XK/q+q3J16dyZt19Xuw+e7xSplT1AD+glkJPaLdAHaO1TS6BUS+qzncYlTgztpu5qW/9S0n9pqpbEJ3d1VAN9yo0fQ9uX9/oaXy/mVtV3HQXen7P+ihOep9UGKCZzJzx8riZ6XnGtoCwzPpRfSAk3m+SPI/u9MDq9m/xdVoivp/zU9gEr6P+I6JBBQSgfw/H+R+zA0nxnV50bMZ5ZhtkeR8PiP/w9Bh4hMu2UGAA==", "string": ""}, "status": {"code": 200, "message": "OK"}, "url": "https://api.github.com/user/48100/events/orgs/praw-dev?per_page=100&page=3"}, "recorded_at": "2016-05-03T23:46:51"}]} diff --git a/tests/cassettes/Organization_events.json b/tests/cassettes/Organization_public_events.json similarity index 100% rename from tests/cassettes/Organization_events.json rename to tests/cassettes/Organization_public_events.json diff --git a/tests/integration/test_orgs.py b/tests/integration/test_orgs.py index eabb556a..b062d695 100644 --- a/tests/integration/test_orgs.py +++ b/tests/integration/test_orgs.py @@ -109,15 +109,34 @@ class TestOrganization(IntegrationHelper): assert o.is_public_member('defunkt') is False + def test_all_events(self): + """Test retrieving organization's complete event stream.""" + self.token_login() + cassette_name = self.cassette_name('all_events') + with self.recorder.use_cassette(cassette_name): + o = self.get_organization('praw-dev') + + for event in o.all_events(username='bboe'): + assert isinstance(event, github3.events.Event) + def test_events(self): - """Test the ability to retrieve an organization's event stream.""" - cassette_name = self.cassette_name('events') + """Test retrieving an organization's public event stream.""" + cassette_name = self.cassette_name('public_events') with self.recorder.use_cassette(cassette_name): o = self.get_organization() for event in o.events(): assert isinstance(event, github3.events.Event) + def test_public_events(self): + """Test retrieving an organization's public event stream.""" + cassette_name = self.cassette_name('public_events') + with self.recorder.use_cassette(cassette_name): + o = self.get_organization() + + for event in o.public_events(): + assert isinstance(event, github3.events.Event) + def test_members(self): """Test the ability to retrieve an organization's members.""" self.basic_login() diff --git a/tests/unit/test_orgs.py b/tests/unit/test_orgs.py index dca92087..4e920ea6 100644 --- a/tests/unit/test_orgs.py +++ b/tests/unit/test_orgs.py @@ -1,3 +1,4 @@ +import mock import pytest from github3 import GitHubError @@ -215,7 +216,18 @@ class TestOrganizationIterator(helper.UnitIteratorHelper): 'url': url_for() } - def test_events(self): + def test_all_events(self): + i = self.instance.all_events(username='dummy') + self.get_next(i) + + self.session.get.assert_called_once_with( + 'https://api.github.com/users/dummy/events/orgs/github', + params={'per_page': 100}, + headers={} + ) + + @mock.patch('warnings.warn') + def test_events(self, warn_mock): """Show that one can iterate over an organization's events.""" i = self.instance.events() self.get_next(i) @@ -226,6 +238,10 @@ class TestOrganizationIterator(helper.UnitIteratorHelper): headers={} ) + warn_mock.assert_called_once_with( + 'This method is deprecated. Please use ``public_events`` instead.', + DeprecationWarning) + def test_members(self): """Show that one can iterate over all members.""" i = self.instance.members() @@ -281,6 +297,17 @@ class TestOrganizationIterator(helper.UnitIteratorHelper): headers={} ) + def test_public_events(self): + """Show that one can iterate over an organization's public events.""" + i = self.instance.public_events() + self.get_next(i) + + self.session.get.assert_called_once_with( + url_for('events'), + params={'per_page': 100}, + headers={} + ) + def test_public_members(self): """Show that one can iterate over all public members.""" i = self.instance.public_members()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": -1, "issue_text_score": 0, "test_score": -1 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
betamax==0.9.0 betamax-matchers==0.4.0 cachetools==5.5.2 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 colorama==0.4.6 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 -e git+https://github.com/sigmavirus24/github3.py.git@1a7455c6c5098603b33c15576624e63ce6751bf7#egg=github3.py idna==3.10 iniconfig==2.1.0 mock==1.0.1 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pyproject-api==1.9.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 requests==2.32.3 requests-toolbelt==1.0.0 swebench_matterhorn @ file:///swebench_matterhorn tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 uritemplate==4.1.1 uritemplate.py==3.0.2 urllib3==2.3.0 virtualenv==20.29.3
name: github3.py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - betamax==0.9.0 - betamax-matchers==0.4.0 - cachetools==5.5.2 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - colorama==0.4.6 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - idna==3.10 - iniconfig==2.1.0 - mock==1.0.1 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - requests==2.32.3 - requests-toolbelt==1.0.0 - swebench-matterhorn==0.0.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - uritemplate==4.1.1 - uritemplate-py==3.0.2 - urllib3==2.3.0 - virtualenv==20.29.3 - wheel==0.21.0 prefix: /opt/conda/envs/github3.py
[ "tests/integration/test_orgs.py::TestOrganization::test_all_events", "tests/integration/test_orgs.py::TestOrganization::test_public_events", "tests/unit/test_orgs.py::TestOrganizationIterator::test_all_events", "tests/unit/test_orgs.py::TestOrganizationIterator::test_events", "tests/unit/test_orgs.py::TestOrganizationIterator::test_public_events" ]
[ "tests/integration/test_orgs.py::TestOrganization::test_is_member" ]
[ "tests/integration/test_orgs.py::TestOrganization::test_add_member", "tests/integration/test_orgs.py::TestOrganization::test_add_repository", "tests/integration/test_orgs.py::TestOrganization::test_can_filter_members_by_role", "tests/integration/test_orgs.py::TestOrganization::test_conceal_member", "tests/integration/test_orgs.py::TestOrganization::test_create_repository", "tests/integration/test_orgs.py::TestOrganization::test_create_team", "tests/integration/test_orgs.py::TestOrganization::test_edit", "tests/integration/test_orgs.py::TestOrganization::test_events", "tests/integration/test_orgs.py::TestOrganization::test_is_public_member", "tests/integration/test_orgs.py::TestOrganization::test_members", "tests/integration/test_orgs.py::TestOrganization::test_public_members", "tests/integration/test_orgs.py::TestOrganization::test_publicize_member", "tests/integration/test_orgs.py::TestOrganization::test_remove_member", "tests/integration/test_orgs.py::TestOrganization::test_remove_repository", "tests/integration/test_orgs.py::TestOrganization::test_repositories", "tests/integration/test_orgs.py::TestOrganization::test_team", "tests/integration/test_orgs.py::TestOrganization::test_teams", "tests/unit/test_orgs.py::TestOrganization::test_add_member", "tests/unit/test_orgs.py::TestOrganization::test_add_repository", "tests/unit/test_orgs.py::TestOrganization::test_conceal_member", "tests/unit/test_orgs.py::TestOrganization::test_create_repository", "tests/unit/test_orgs.py::TestOrganization::test_create_team", "tests/unit/test_orgs.py::TestOrganization::test_edit", "tests/unit/test_orgs.py::TestOrganization::test_equality", "tests/unit/test_orgs.py::TestOrganization::test_is_member", "tests/unit/test_orgs.py::TestOrganization::test_is_public_member", "tests/unit/test_orgs.py::TestOrganization::test_publicize_member", "tests/unit/test_orgs.py::TestOrganization::test_remove_member", "tests/unit/test_orgs.py::TestOrganization::test_remove_repository", "tests/unit/test_orgs.py::TestOrganization::test_remove_repository_requires_positive_team_id", "tests/unit/test_orgs.py::TestOrganization::test_repr", "tests/unit/test_orgs.py::TestOrganization::test_team", "tests/unit/test_orgs.py::TestOrganization::test_team_requires_positive_team_id", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_add_member", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_add_repository", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_conceal_member", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_create_repository", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_create_team", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_edit", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_publicize_member", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_remove_member", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_remove_repository", "tests/unit/test_orgs.py::TestOrganizationRequiresAuth::test_team", "tests/unit/test_orgs.py::TestOrganizationIterator::test_members", "tests/unit/test_orgs.py::TestOrganizationIterator::test_members_excludes_fake_filters", "tests/unit/test_orgs.py::TestOrganizationIterator::test_members_excludes_fake_roles", "tests/unit/test_orgs.py::TestOrganizationIterator::test_members_filters", "tests/unit/test_orgs.py::TestOrganizationIterator::test_members_roles", "tests/unit/test_orgs.py::TestOrganizationIterator::test_public_members", "tests/unit/test_orgs.py::TestOrganizationIterator::test_repositories", "tests/unit/test_orgs.py::TestOrganizationIterator::test_respositories_accepts_type", "tests/unit/test_orgs.py::TestOrganizationIterator::test_teams", "tests/unit/test_orgs.py::TestOrganizationIterator::test_teams_requires_auth" ]
[]
BSD 3-Clause "New" or "Revised" License
519
dask__dask-1137
b066b73cfa68e31848a0ff0d6348f6a0df73d4a7
2016-05-02 22:00:14
71e3e413d6e00942de3ff32a3ba378408f2648e9
eriknw: Looking now. eriknw: Great. I think the tradeoff is worth it for these functions. Not passing an optional `dependencies` to non-critical functions also seems reasonable as a way to avoid complications. A downside is that now I don't know the next "obvious" thing to do to optimize these further! What do profiles look like with these changes? mrocklin: I recommend pulling out snakeviz and running the following: ```python In [1]: import dask.array as da In [2]: n = 12 In [3]: x = da.random.random((2**n, 2**n), chunks=(2**n, 1)) # 4096 x 4096, 4096 x 1 In [4]: for i in range(1, n): # 4096 x 4096, 2048 x 2 x = x.rechunk((2**(n - i), 2**(i + 1))) # 4096 x 4096, 1024 x 4 ...: In [5]: y = x.sum() In [6]: %load_ext snakeviz In [7]: %snakeviz y._optimize(y.dask, y._keys()) ``` Inline_functions takes up about half of the optimization time now. Really though, I think we're at the point of diminishing returns. This computation takes around a minute-plus to run on a distributed machine. mrocklin: If you are looking to do some optimization work we're close to the point where we might want to Cythonize a couple of functions within the distributed scheduler. If you're interested let me know and I'll produce a benchmark script for you to play with. eriknw: Okay. I'm up for Cythonizing some functions. I'm taking a vacation in a few days, so it'll probably be a few weeks until I can do the work. Thanks for letting me know this would be beneficial to do.
diff --git a/dask/array/optimization.py b/dask/array/optimization.py index 8d7224fd4..6a201ead5 100644 --- a/dask/array/optimization.py +++ b/dask/array/optimization.py @@ -21,10 +21,11 @@ def optimize(dsk, keys, **kwargs): keys = list(flatten(keys)) fast_functions = kwargs.get('fast_functions', set([getarray, np.transpose])) - dsk2 = cull(dsk, keys) - dsk4 = fuse(dsk2, keys) + dsk2, dependencies = cull(dsk, keys) + dsk4, dependencies = fuse(dsk2, keys, dependencies) dsk5 = optimize_slices(dsk4) - dsk6 = inline_functions(dsk5, keys, fast_functions=fast_functions) + dsk6 = inline_functions(dsk5, keys, fast_functions=fast_functions, + dependencies=dependencies) return dsk6 diff --git a/dask/async.py b/dask/async.py index 4f9d92b1c..2d8fbb87b 100644 --- a/dask/async.py +++ b/dask/async.py @@ -434,7 +434,7 @@ def get_async(apply_async, num_workers, dsk, result, cache=None, for f in start_cbs: f(dsk) - dsk = cull(dsk, list(results)) + dsk, dependencies = cull(dsk, list(results)) keyorder = order(dsk) diff --git a/dask/bag/core.py b/dask/bag/core.py index 3348be39a..268a17931 100644 --- a/dask/bag/core.py +++ b/dask/bag/core.py @@ -64,7 +64,7 @@ def lazify(dsk): return valmap(lazify_task, dsk) -def inline_singleton_lists(dsk): +def inline_singleton_lists(dsk, dependencies=None): """ Inline lists that are only used once >>> d = {'b': (list, 'a'), @@ -74,8 +74,8 @@ def inline_singleton_lists(dsk): Pairs nicely with lazify afterwards """ - - dependencies = dict((k, get_dependencies(dsk, k)) for k in dsk) + if dependencies is None: + dependencies = dict((k, get_dependencies(dsk, k)) for k in dsk) dependents = reverse_dict(dependencies) keys = [k for k, v in dsk.items() @@ -85,9 +85,9 @@ def inline_singleton_lists(dsk): def optimize(dsk, keys, **kwargs): """ Optimize a dask from a dask.bag """ - dsk2 = cull(dsk, keys) - dsk3 = fuse(dsk2, keys) - dsk4 = inline_singleton_lists(dsk3) + dsk2, dependencies = cull(dsk, keys) + dsk3, dependencies = fuse(dsk2, keys, dependencies) + dsk4 = inline_singleton_lists(dsk3, dependencies) dsk5 = lazify(dsk4) return dsk5 diff --git a/dask/core.py b/dask/core.py index 275748384..ead939fd0 100644 --- a/dask/core.py +++ b/dask/core.py @@ -319,7 +319,7 @@ def subs(task, key, val): return task[:1] + tuple(newargs) -def _toposort(dsk, keys=None, returncycle=False): +def _toposort(dsk, keys=None, returncycle=False, dependencies=None): # Stack-based depth-first search traversal. This is based on Tarjan's # method for topological sorting (see wikipedia for pseudocode) if keys is None: @@ -340,6 +340,9 @@ def _toposort(dsk, keys=None, returncycle=False): # that has already been added to `completed`. seen = set() + if dependencies is None: + dependencies = dict((k, get_dependencies(dsk, k)) for k in dsk) + for key in keys: if key in completed: continue @@ -355,7 +358,7 @@ def _toposort(dsk, keys=None, returncycle=False): # Add direct descendants of cur to nodes stack next_nodes = [] - for nxt in get_dependencies(dsk, cur): + for nxt in dependencies[cur]: if nxt not in completed: if nxt in seen: # Cycle detected! @@ -385,9 +388,9 @@ def _toposort(dsk, keys=None, returncycle=False): return ordered -def toposort(dsk): +def toposort(dsk, dependencies=None): """ Return a list of keys of dask sorted in topological order.""" - return _toposort(dsk) + return _toposort(dsk, dependencies=dependencies) def getcycle(d, keys): diff --git a/dask/dataframe/optimize.py b/dask/dataframe/optimize.py index 0ae46d54c..d23a7ff2e 100644 --- a/dask/dataframe/optimize.py +++ b/dask/dataframe/optimize.py @@ -15,9 +15,9 @@ def fuse_castra_index(dsk): def optimize(dsk, keys, **kwargs): if isinstance(keys, list): - dsk2 = cull(dsk, list(core.flatten(keys))) + dsk2, dependencies = cull(dsk, list(core.flatten(keys))) else: - dsk2 = cull(dsk, [keys]) + dsk2, dependencies = cull(dsk, [keys]) try: from castra import Castra dsk3 = fuse_getitem(dsk2, Castra.load_partition, 3) @@ -25,5 +25,5 @@ def optimize(dsk, keys, **kwargs): except ImportError: dsk4 = dsk2 dsk5 = fuse_getitem(dsk4, dataframe_from_ctable, 3) - dsk6 = cull(dsk5, keys) + dsk6, _ = cull(dsk5, keys) return dsk6 diff --git a/dask/dataframe/shuffle.py b/dask/dataframe/shuffle.py index 0b4c49ab0..fb797a503 100644 --- a/dask/dataframe/shuffle.py +++ b/dask/dataframe/shuffle.py @@ -144,7 +144,7 @@ def set_partition(df, index, divisions, compute=False, drop=True, **kwargs): dsk.update(index.dask) if compute: - dsk = cull(dsk, list(dsk4.keys())) + dsk, _ = cull(dsk, list(dsk4.keys())) return DataFrame(dsk, name, metadata, divisions) diff --git a/dask/multiprocessing.py b/dask/multiprocessing.py index dce045998..a2f6b996f 100644 --- a/dask/multiprocessing.py +++ b/dask/multiprocessing.py @@ -68,8 +68,9 @@ def get(dsk, keys, optimizations=[], num_workers=None, func_loads=func_loads) # Optimize Dask - dsk2 = fuse(dsk, keys) - dsk3 = pipe(dsk2, partial(cull, keys=keys), *optimizations) + dsk2, dependencies = cull(dsk, keys) + dsk3, dependencies = fuse(dsk2, keys, dependencies) + dsk4 = pipe(dsk3, *optimizations) try: # Run diff --git a/dask/optimize.py b/dask/optimize.py index e557ccd73..c34b6e4c7 100644 --- a/dask/optimize.py +++ b/dask/optimize.py @@ -22,49 +22,80 @@ def cull(dsk, keys): Examples -------- >>> d = {'x': 1, 'y': (inc, 'x'), 'out': (add, 'x', 10)} - >>> cull(d, 'out') # doctest: +SKIP + >>> dsk, dependencies = cull(d, 'out') # doctest: +SKIP + >>> dsk # doctest: +SKIP {'x': 1, 'out': (add, 'x', 10)} + >>> dependencies # doctest: +SKIP + {'x': set(), 'out': set(['x'])} + + Returns + ------- + dsk: culled dask graph + dependencies: Dict mapping {key: [deps]}. Useful side effect to accelerate + other optimizations, notably fuse. """ if not isinstance(keys, (list, set)): keys = [keys] - nxt = set(flatten(keys)) - seen = nxt - while nxt: - cur = nxt - nxt = set() - for item in cur: - for dep in get_dependencies(dsk, item): - if dep not in seen: - nxt.add(dep) - seen.update(nxt) - return dict((k, v) for k, v in dsk.items() if k in seen) - - -def fuse(dsk, keys=None): - """ Return new dask with linear sequence of tasks fused together. + out = dict() + seen = set() + dependencies = dict() + stack = list(set(flatten(keys))) + while stack: + key = stack.pop() + out[key] = dsk[key] + deps = get_dependencies(dsk, key, as_list=True) # fuse needs lists + dependencies[key] = deps + unseen = [d for d in deps if d not in seen] + stack.extend(unseen) + seen.update(unseen) + return out, dependencies + + +def fuse(dsk, keys=None, dependencies=None): + """ Return new dask graph with linear sequence of tasks fused together. If specified, the keys in ``keys`` keyword argument are *not* fused. + Supply ``dependencies`` from output of ``cull`` if available to avoid + recomputing dependencies. - This may be used as an optimization step. + Parameters + ---------- + dsk: dict + keys: list + dependencies: dict, optional + {key: [list-of-keys]}. Must be a list to provide count of each key + This optional input often comes from ``cull`` Examples -------- >>> d = {'a': 1, 'b': (inc, 'a'), 'c': (inc, 'b')} - >>> fuse(d) # doctest: +SKIP + >>> dsk, dependencies = fuse(d) + >>> dsk # doctest: +SKIP {'c': (inc, (inc, 1))} - >>> fuse(d, keys=['b']) # doctest: +SKIP + >>> dsk, dependencies = fuse(d, keys=['b']) + >>> dsk # doctest: +SKIP {'b': (inc, 1), 'c': (inc, 'b')} + + Returns + ------- + dsk: output graph with keys fused + dependencies: dict mapping dependencies after fusion. Useful side effect + to accelerate other downstream optimizations. """ if keys is not None and not isinstance(keys, set): if not isinstance(keys, list): keys = [keys] keys = set(flatten(keys)) + if dependencies is None: + dependencies = dict((key, get_dependencies(dsk, key, as_list=True)) + for key in dsk) + # locate all members of linear chains child2parent = {} unfusible = set() for parent in dsk: - deps = get_dependencies(dsk, parent, as_list=True) + deps = dependencies[parent] has_many_children = len(deps) > 1 for child in deps: if keys is not None and child in keys: @@ -94,6 +125,8 @@ def fuse(dsk, keys=None): chain.append(child) chains.append(chain) + dependencies = dict((k, set(v)) for k, v in dependencies.items()) + # create a new dask with fused chains rv = {} fused = set() @@ -102,6 +135,8 @@ def fuse(dsk, keys=None): val = dsk[child] while chain: parent = chain.pop() + dependencies[parent].update(dependencies.pop(child)) + dependencies[parent].remove(child) val = subs(dsk[parent], child, val) fused.add(child) child = parent @@ -111,10 +146,10 @@ def fuse(dsk, keys=None): for key, val in dsk.items(): if key not in fused: rv[key] = val - return rv + return rv, dependencies -def inline(dsk, keys=None, inline_constants=True): +def inline(dsk, keys=None, inline_constants=True, dependencies=None): """ Return new dask with the given keys inlined with their values. Inlines all constants if ``inline_constants`` keyword is True. @@ -140,13 +175,17 @@ def inline(dsk, keys=None, inline_constants=True): if inline_constants: keys.update(k for k, v in dsk.items() if not istask(v)) + if dependencies is None: + dependencies = dict((k, get_dependencies(dsk, k)) for k in dsk) + # Keys may depend on other keys, so determine replace order with toposort. # The values stored in `keysubs` do not include other keys. - replaceorder = toposort(dict((k, dsk[k]) for k in keys if k in dsk)) + replaceorder = toposort(dict((k, dsk[k]) for k in keys if k in dsk), + dependencies=dependencies) keysubs = {} for key in replaceorder: val = dsk[key] - for dep in keys & get_dependencies(dsk, key): + for dep in keys & dependencies[key]: if dep in keysubs: replace = keysubs[dep] else: @@ -159,13 +198,14 @@ def inline(dsk, keys=None, inline_constants=True): for key, val in dsk.items(): if key in keys: continue - for item in keys & get_dependencies(dsk, key): + for item in keys & dependencies[key]: val = subs(val, item, keysubs[item]) rv[key] = val return rv -def inline_functions(dsk, output, fast_functions=None, inline_constants=False): +def inline_functions(dsk, output, fast_functions=None, inline_constants=False, + dependencies=None): """ Inline cheap functions into larger operations Examples @@ -194,7 +234,8 @@ def inline_functions(dsk, output, fast_functions=None, inline_constants=False): fast_functions = set(fast_functions) - dependencies = dict((k, get_dependencies(dsk, k)) for k in dsk) + if dependencies is None: + dependencies = dict((k, get_dependencies(dsk, k)) for k in dsk) dependents = reverse_dict(dependencies) keys = [k for k, v in dsk.items() @@ -203,7 +244,8 @@ def inline_functions(dsk, output, fast_functions=None, inline_constants=False): and dependents[k] and k not in output] if keys: - return inline(dsk, keys, inline_constants=inline_constants) + return inline(dsk, keys, inline_constants=inline_constants, + dependencies=dependencies) else: return dsk @@ -515,7 +557,7 @@ def fuse_selections(dsk, head1, head2, merge): ... 'y': (getitem, 'x', 'a')} >>> merge = lambda t1, t2: (load, t2[1], t2[2], t1[2]) >>> dsk2 = fuse_selections(dsk, getitem, load, merge) - >>> cull(dsk2, 'y') + >>> cull(dsk2, 'y')[0] {'y': (<function load at ...>, 'store', 'part', 'a')} """ dsk2 = dict() @@ -548,7 +590,7 @@ def fuse_getitem(dsk, func, place): >>> dsk = {'x': (load, 'store', 'part', ['a', 'b']), ... 'y': (getitem, 'x', 'a')} >>> dsk2 = fuse_getitem(dsk, load, 3) # columns in arg place 3 - >>> cull(dsk2, 'y') + >>> cull(dsk2, 'y')[0] {'y': (<function load at ...>, 'store', 'part', 'a')} """ return fuse_selections(dsk, getitem, func, diff --git a/dask/order.py b/dask/order.py index 60fd03787..06f602c5d 100644 --- a/dask/order.py +++ b/dask/order.py @@ -58,10 +58,10 @@ from __future__ import absolute_import, division, print_function from operator import add -from .core import get_deps +from .core import get_dependencies, reverse_dict, get_deps -def order(dsk): +def order(dsk, dependencies=None): """ Order nodes in dask graph The ordering will be a toposort but will also have other convenient @@ -74,7 +74,10 @@ def order(dsk): >>> order(dsk) {'a': 2, 'c': 1, 'b': 3, 'd': 0} """ - dependencies, dependents = get_deps(dsk) + if dependencies is None: + dependencies = dict((k, get_dependencies(dsk, k)) for k in dsk) + dependents = reverse_dict(dependencies) + ndeps = ndependents(dependencies, dependents) maxes = child_max(dependencies, dependents, ndeps) return dfs(dependencies, dependents, key=maxes.get)
Tune dask.array.optimize In some pathological (yet also real) cases, graph optimization can cost about as much as computation: I've been benchmarking against this computation ```python import dask.array as da n = 12 x = da.random.random((2**n, 2**n), chunks=(2**n, 1)) # 4096 x 4096, 4096 x 1 for i in range(1, n): # 4096 x 4096, 2048 x 2 x = x.rechunk((2**(n - i), 2**(i + 1))) # 4096 x 4096, 1024 x 4 y = x.sum() >>> %time y.compute() CPU times: user 39 s, sys: 2.45 s, total: 41.5 s Wall time: 39.1 s >>> %prun y._optimize(y.dask, y._keys()) ``` ``` 29816630 function calls (28569410 primitive calls) in 22.570 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 604153 3.733 0.000 8.800 0.000 core.py:189(get_dependencies) 6240188 2.504 0.000 2.843 0.000 core.py:27(istask) 1312754 2.414 0.000 3.091 0.000 core.py:154(_deps) 3 2.146 0.715 2.146 0.715 core.py:284(<listcomp>) 299004 1.456 0.000 3.326 0.000 rewrite.py:375(_match) 909302/77823 1.331 0.000 2.017 0.000 optimize.py:211(functions_of) 2009082 0.625 0.000 0.625 0.000 {built-in method isinstance} 3 0.618 0.206 2.821 0.940 core.py:275(reverse_dict) 299004/77823 0.553 0.000 5.650 0.000 rewrite.py:363(_bottom_up) 299004 0.480 0.000 4.206 0.000 rewrite.py:283(iter_matches) 348156 0.426 0.000 0.426 0.000 rewrite.py:50(__init__) 874487 0.406 0.000 1.014 0.000 rewrite.py:8(head) 2303972 0.403 0.000 0.403 0.000 {method 'pop' of 'list' objects} 219136/51200 0.400 0.000 0.990 0.000 core.py:291(subs) 2250724 0.391 0.000 0.391 0.000 {method 'extend' of 'list' objects} 2 0.376 0.188 4.363 2.182 optimize.py:117(inline) 49152 0.341 0.000 0.673 0.000 core.py:307(<listcomp>) 4671438 0.339 0.000 0.339 0.000 {built-in method callable} 299004 0.270 0.000 4.477 0.000 rewrite.py:304(_rewrite) 794616 0.257 0.000 1.211 0.000 rewrite.py:81(current) 1 0.204 0.204 1.261 1.261 optimize.py:43(fuse) 745465 0.186 0.000 0.186 0.000 {method 'get' of 'dict' objects} 1484786 0.168 0.000 0.168 0.000 {method 'append' of 'list' objects} 2 0.133 0.066 0.752 0.376 core.py:321(_toposort) 1 0.127 0.127 1.249 1.249 optimize.py:16(cull) 348156 0.126 0.000 0.126 0.000 {method 'pop' of 'collections.deque' objects} 79871 0.125 0.000 0.185 0.000 optimization.py:32(is_full_slice) 745464 0.122 0.000 0.122 0.000 rewrite.py:119(edges) 1 0.122 0.122 2.202 2.202 optimize.py:200(<listcomp>) 595958 0.113 0.000 0.113 0.000 {method 'add' of 'set' objects} 1 0.106 0.106 5.805 5.805 {method 'update' of 'dict' objects} 225278/221182 0.106 0.000 3.578 0.000 rewrite.py:365(<genexpr>) 1 0.098 0.098 6.363 6.363 optimize.py:237(dealias) 176126 0.093 0.000 0.175 0.000 rewrite.py:19(args) 81919 0.086 0.000 0.086 0.000 {built-in method hasattr} 49152 0.070 0.000 0.135 0.000 rewrite.py:70(next) 79871 0.069 0.000 0.069 0.000 {built-in method hash} 47103/24575 0.067 0.000 1.377 0.000 rewrite.py:367(<listcomp>) 79872 0.066 0.000 1.486 0.000 optimize.py:287(<genexpr>) 79872 0.065 0.000 1.344 0.000 optimize.py:278(<genexpr>) 79871 0.063 0.000 0.132 0.000 core.py:9(ishashable) 77824 0.061 0.000 1.311 0.000 optimize.py:197(<genexpr>) 49152 0.058 0.000 0.084 0.000 rewrite.py:62(copy) 1 0.058 0.058 6.676 6.676 optimization.py:49(remove_full_slices) 1 0.054 0.054 22.570 22.570 <string>:1(<module>) 77823 0.049 0.000 5.699 0.000 rewrite.py:315(rewrite) 79872 0.044 0.000 0.044 0.000 optimize.py:40(<genexpr>) 28675 0.042 0.000 0.042 0.000 {method 'values' of 'dict' objects} 1 0.039 0.039 7.491 7.491 optimize.py:168(inline_functions) 98304 0.038 0.000 0.038 0.000 optimization.py:46(<genexpr>) 1 0.037 0.037 0.169 0.169 optimize.py:281(<genexpr>) 1 0.036 0.036 0.221 0.221 optimization.py:69(<genexpr>) 79872 0.033 0.000 0.033 0.000 optimization.py:71(<genexpr>) 1 0.033 0.033 22.515 22.515 optimization.py:14(optimize) 49152 0.032 0.000 0.780 0.000 core.py:314(<listcomp>) 79871 0.031 0.000 0.117 0.000 optimize.py:231(unwrap_partial) 49154 0.026 0.000 0.026 0.000 optimize.py:145(<genexpr>) 49160 0.018 0.000 0.028 0.000 core.py:246(flatten) 2 0.011 0.006 0.011 0.006 optimize.py:282(<genexpr>) 49152 0.011 0.000 0.011 0.000 {method 'extend' of 'collections.deque' objects} 1 0.009 0.009 0.009 0.009 {method 'copy' of 'dict' objects} 49152 0.009 0.000 0.037 0.000 {built-in method all} 77823 0.008 0.000 0.008 0.000 {method 'issubset' of 'set' objects} 79872 0.008 0.000 0.008 0.000 {built-in method len} ``` I also recommend looking at this with snakeviz ```python %load_ext snakeviz %snakeviz y._optimize(y.dask, y._keys()) ```
dask/dask
diff --git a/dask/array/tests/test_optimization.py b/dask/array/tests/test_optimization.py index 37d02d38d..0ff08fb2f 100644 --- a/dask/array/tests/test_optimization.py +++ b/dask/array/tests/test_optimization.py @@ -69,14 +69,14 @@ def test_optimize_slicing(): 'e': (getarray, 'd', (slice(None, None, None),))} expected = {'e': (getarray, (range, 10), (slice(0, 5, None),))} - result = optimize_slices(fuse(dsk, [])) + result = optimize_slices(fuse(dsk, [])[0]) assert result == expected # protect output keys expected = {'c': (range, 10), 'd': (getarray, 'c', (slice(0, 5, None),)), 'e': 'd'} - result = optimize_slices(fuse(dsk, ['c', 'd', 'e'])) + result = optimize_slices(fuse(dsk, ['c', 'd', 'e'])[0]) assert result == expected diff --git a/dask/tests/test_optimize.py b/dask/tests/test_optimize.py index fb713f7f3..749a03c83 100644 --- a/dask/tests/test_optimize.py +++ b/dask/tests/test_optimize.py @@ -18,27 +18,27 @@ def double(x): def test_cull(): # 'out' depends on 'x' and 'y', but not 'z' d = {'x': 1, 'y': (inc, 'x'), 'z': (inc, 'x'), 'out': (add, 'y', 10)} - culled = cull(d, 'out') + culled, dependencies = cull(d, 'out') assert culled == {'x': 1, 'y': (inc, 'x'), 'out': (add, 'y', 10)} + assert dependencies == {'x': [], 'y': ['x'], 'out': ['y']} + assert cull(d, 'out') == cull(d, ['out']) - assert cull(d, ['out', 'z']) == d + assert cull(d, ['out', 'z'])[0] == d assert cull(d, [['out'], ['z']]) == cull(d, ['out', 'z']) assert raises(KeyError, lambda: cull(d, 'badkey')) def test_fuse(): - assert fuse({ - 'w': (inc, 'x'), - 'x': (inc, 'y'), - 'y': (inc, 'z'), - 'z': (add, 'a', 'b'), - 'a': 1, - 'b': 2, - }) == { - 'w': (inc, (inc, (inc, (add, 'a', 'b')))), - 'a': 1, - 'b': 2, - } + dsk, dependencies = fuse({'w': (inc, 'x'), + 'x': (inc, 'y'), + 'y': (inc, 'z'), + 'z': (add, 'a', 'b'), + 'a': 1, + 'b': 2}) + assert dsk == {'w': (inc, (inc, (inc, (add, 'a', 'b')))), + 'a': 1, + 'b': 2} + assert dependencies == {'a': set(), 'b': set(), 'w': set(['a', 'b'])} assert fuse({ 'NEW': (inc, 'y'), 'w': (inc, 'x'), @@ -47,13 +47,16 @@ def test_fuse(): 'z': (add, 'a', 'b'), 'a': 1, 'b': 2, - }) == { + }) == ({ 'NEW': (inc, 'y'), 'w': (inc, (inc, 'y')), 'y': (inc, (add, 'a', 'b')), 'a': 1, 'b': 2, - } + }, + {'a': set(), 'b': set(), 'y': set(['a', 'b']), + 'w': set(['y']), 'NEW': set(['y'])}) + assert fuse({ 'v': (inc, 'y'), 'u': (inc, 'w'), @@ -65,13 +68,15 @@ def test_fuse(): 'b': (inc, 'd'), 'c': 1, 'd': 2, - }) == { + }) == ({ 'u': (inc, (inc, (inc, 'y'))), 'v': (inc, 'y'), 'y': (inc, (add, 'a', 'b')), 'a': (inc, 1), 'b': (inc, 2), - } + }, + {'a': set(), 'b': set(), 'y': set(['a', 'b']), + 'v': set(['y']), 'u': set(['y'])}) assert fuse({ 'a': (inc, 'x'), 'b': (inc, 'x'), @@ -79,39 +84,43 @@ def test_fuse(): 'd': (inc, 'c'), 'x': (inc, 'y'), 'y': 0, - }) == { + }) == ({ 'a': (inc, 'x'), 'b': (inc, 'x'), 'd': (inc, (inc, 'x')), 'x': (inc, 0), - } + }, + {'x': set(), 'd': set(['x']), 'a': set(['x']), 'b': set(['x'])}) assert fuse({ 'a': 1, 'b': (inc, 'a'), 'c': (add, 'b', 'b') - }) == { + }) == ({ 'b': (inc, 1), 'c': (add, 'b', 'b') - } + }, {'b': set(), 'c': set(['b'])}) def test_fuse_keys(): assert (fuse({'a': 1, 'b': (inc, 'a'), 'c': (inc, 'b')}, keys=['b']) - == {'b': (inc, 1), 'c': (inc, 'b')}) - assert fuse({ + == ({'b': (inc, 1), 'c': (inc, 'b')}, + {'b': set(), 'c': set(['b'])})) + dsk, dependencies = fuse({ 'w': (inc, 'x'), 'x': (inc, 'y'), 'y': (inc, 'z'), 'z': (add, 'a', 'b'), 'a': 1, 'b': 2, - }, keys=['x', 'z']) == { - 'w': (inc, 'x'), - 'x': (inc, (inc, 'z')), - 'z': (add, 'a', 'b'), - 'a': 1, - 'b': 2, - } + }, keys=['x', 'z']) + + assert dsk == {'w': (inc, 'x'), + 'x': (inc, (inc, 'z')), + 'z': (add, 'a', 'b'), + 'a': 1, + 'b': 2 } + assert dependencies == {'a': set(), 'b': set(), 'z': set(['a', 'b']), + 'x': set(['z']), 'w': set(['x'])} def test_inline(): @@ -341,7 +350,7 @@ def test_fuse_getitem(): dsk = {'x': (load, 'store', 'part', ['a', 'b']), 'y': (getitem, 'x', 'a')} dsk2 = fuse_getitem(dsk, load, 3) - dsk2 = cull(dsk2, 'y') + dsk2, dependencies = cull(dsk2, 'y') assert dsk2 == {'y': (load, 'store', 'part', 'a')} @@ -352,5 +361,5 @@ def test_fuse_selections(): 'y': (getitem, 'x', 'a')} merge = lambda t1, t2: (load, t2[1], t2[2], t1[2]) dsk2 = fuse_selections(dsk, getitem, load, merge) - dsk2 = cull(dsk2, 'y') + dsk2, dependencies = cull(dsk2, 'y') assert dsk2 == {'y': (load, 'store', 'part', 'a')} diff --git a/dask/tests/test_order.py b/dask/tests/test_order.py index d64dee715..3b5f8c3ce 100644 --- a/dask/tests/test_order.py +++ b/dask/tests/test_order.py @@ -1,5 +1,6 @@ from itertools import chain -from dask.order import dfs, child_max, ndependents, order, inc, get_deps +from dask.order import dfs, child_max, ndependents, order, inc +from dask.core import get_deps def issorted(L, reverse=False):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 9 }
1.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 pandas>=1.0.0 cloudpickle partd distributed s3fs toolz psutil pytables bokeh bcolz scipy h5py ipython", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz liblzma-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore @ file:///opt/conda/conda-bld/aiobotocore_1643638228694/work aiohttp @ file:///tmp/build/80754af9/aiohttp_1632748060317/work aioitertools @ file:///tmp/build/80754af9/aioitertools_1607109665762/work async-timeout==3.0.1 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work bcolz==1.2.1 bokeh @ file:///tmp/build/80754af9/bokeh_1620710048147/work boto3==1.23.10 botocore==1.26.10 brotlipy==0.7.0 certifi==2021.5.30 cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work chardet @ file:///tmp/build/80754af9/chardet_1607706739153/work click==8.0.3 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1632508026186/work contextvars==2.4 cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work cytoolz==0.11.0 -e git+https://github.com/dask/dask.git@b066b73cfa68e31848a0ff0d6348f6a0df73d4a7#egg=dask decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work distributed==1.9.5 fsspec @ file:///opt/conda/conda-bld/fsspec_1642510437511/work h5py==2.10.0 HeapDict @ file:///Users/ktietz/demo/mc3/conda-bld/heapdict_1630598515714/work idna @ file:///tmp/build/80754af9/idna_1637925883363/work idna-ssl @ file:///tmp/build/80754af9/idna_ssl_1611752490495/work immutables @ file:///tmp/build/80754af9/immutables_1628888996840/work importlib-metadata==4.8.3 iniconfig==1.1.1 ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work jmespath @ file:///Users/ktietz/demo/mc3/conda-bld/jmespath_1630583964805/work locket==0.2.1 MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work mock @ file:///tmp/build/80754af9/mock_1607622725907/work msgpack @ file:///tmp/build/80754af9/msgpack-python_1612287171716/work msgpack-python==0.5.6 multidict @ file:///tmp/build/80754af9/multidict_1607367768400/work numexpr @ file:///tmp/build/80754af9/numexpr_1618853194344/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 parso==0.7.0 partd @ file:///opt/conda/conda-bld/partd_1647245470509/work pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work pluggy==1.0.0 prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work psutil @ file:///tmp/build/80754af9/psutil_1612297621795/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl py==1.11.0 pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work pytest==7.0.1 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work pytz==2021.3 PyYAML==5.4.1 s3fs==0.4.2 s3transfer==0.5.2 scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work six @ file:///tmp/build/80754af9/six_1644875935023/work sortedcontainers @ file:///tmp/build/80754af9/sortedcontainers_1623949099177/work tables==3.6.1 tblib @ file:///Users/ktietz/demo/mc3/conda-bld/tblib_1629402031467/work tomli==1.2.3 toolz @ file:///tmp/build/80754af9/toolz_1636545406491/work tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work wrapt==1.12.1 yarl @ file:///tmp/build/80754af9/yarl_1606939915466/work zict==2.0.0 zipp==3.6.0
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - aiobotocore=2.1.0=pyhd3eb1b0_0 - aiohttp=3.7.4.post0=py36h7f8727e_2 - aioitertools=0.7.1=pyhd3eb1b0_0 - async-timeout=3.0.1=py36h06a4308_0 - attrs=21.4.0=pyhd3eb1b0_0 - backcall=0.2.0=pyhd3eb1b0_0 - bcolz=1.2.1=py36h04863e7_0 - blas=1.0=openblas - blosc=1.21.3=h6a678d5_0 - bokeh=2.3.2=py36h06a4308_0 - brotlipy=0.7.0=py36h27cfd23_1003 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - cffi=1.14.6=py36h400218f_0 - chardet=4.0.0=py36h06a4308_1003 - click=8.0.3=pyhd3eb1b0_0 - cloudpickle=2.0.0=pyhd3eb1b0_0 - contextvars=2.4=py_0 - cryptography=35.0.0=py36hd23ed53_0 - cytoolz=0.11.0=py36h7b6447c_0 - decorator=5.1.1=pyhd3eb1b0_0 - freetype=2.12.1=h4a9f257_0 - fsspec=2022.1.0=pyhd3eb1b0_0 - giflib=5.2.2=h5eee18b_0 - h5py=2.10.0=py36h7918eee_0 - hdf5=1.10.4=hb1b8bf9_0 - heapdict=1.0.1=pyhd3eb1b0_0 - idna=3.3=pyhd3eb1b0_0 - idna_ssl=1.1.0=py36h06a4308_0 - immutables=0.16=py36h7f8727e_0 - ipython=7.16.1=py36h5ca1d4c_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.17.2=py36h06a4308_1 - jinja2=3.0.3=pyhd3eb1b0_0 - jmespath=0.10.0=pyhd3eb1b0_0 - jpeg=9e=h5eee18b_3 - lcms2=2.16=hb9589c4_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h6a678d5_0 - libdeflate=1.22=h5eee18b_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtiff=4.5.1=hffd6297_1 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - locket=0.2.1=py36h06a4308_1 - lz4-c=1.9.4=h6a678d5_1 - lzo=2.10=h7b6447c_2 - markupsafe=2.0.1=py36h27cfd23_0 - mock=4.0.3=pyhd3eb1b0_0 - multidict=5.1.0=py36h27cfd23_2 - ncurses=6.4=h6a678d5_0 - numexpr=2.7.3=py36h4be448d_1 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pandas=1.1.5=py36ha9443f7_0 - parso=0.7.0=py_0 - partd=1.2.0=pyhd3eb1b0_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pillow=8.3.1=py36h5aabda8_0 - pip=21.2.2=py36h06a4308_0 - prompt-toolkit=3.0.20=pyhd3eb1b0_0 - psutil=5.8.0=py36h27cfd23_1 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.11.2=pyhd3eb1b0_0 - pyopenssl=22.0.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pysocks=1.7.1=py36h06a4308_0 - pytables=3.6.1=py36h71ec239_0 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytz=2021.3=pyhd3eb1b0_0 - pyyaml=5.4.1=py36h27cfd23_1 - readline=8.2=h5eee18b_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sortedcontainers=2.4.0=pyhd3eb1b0_0 - sqlite=3.45.3=h5eee18b_0 - tblib=1.7.0=pyhd3eb1b0_0 - tk=8.6.14=h39e8969_0 - toolz=0.11.2=pyhd3eb1b0_0 - tornado=6.1=py36h27cfd23_0 - traitlets=4.3.3=py36h06a4308_0 - typing-extensions=4.1.1=hd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - urllib3=1.26.8=pyhd3eb1b0_0 - wcwidth=0.2.5=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - wrapt=1.12.1=py36h7b6447c_1 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - yarl=1.6.3=py36h27cfd23_0 - zict=2.0.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - zstd=1.5.6=hc292b87_0 - pip: - boto3==1.23.10 - botocore==1.26.10 - distributed==1.9.5 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - msgpack-python==0.5.6 - pluggy==1.0.0 - py==1.11.0 - pytest==7.0.1 - s3fs==0.4.2 - s3transfer==0.5.2 - tomli==1.2.3 - zipp==3.6.0 prefix: /opt/conda/envs/dask
[ "dask/array/tests/test_optimization.py::test_optimize_slicing", "dask/tests/test_optimize.py::test_cull", "dask/tests/test_optimize.py::test_fuse", "dask/tests/test_optimize.py::test_fuse_keys", "dask/tests/test_optimize.py::test_fuse_getitem", "dask/tests/test_optimize.py::test_fuse_selections" ]
[]
[ "dask/array/tests/test_optimization.py::test_fuse_getitem", "dask/array/tests/test_optimization.py::test_optimize_with_getitem_fusion", "dask/array/tests/test_optimization.py::test_fuse_slice", "dask/array/tests/test_optimization.py::test_fuse_slice_with_lists", "dask/array/tests/test_optimization.py::test_hard_fuse_slice_cases", "dask/array/tests/test_optimization.py::test_dont_fuse_different_slices", "dask/tests/test_optimize.py::test_inline", "dask/tests/test_optimize.py::test_inline_functions", "dask/tests/test_optimize.py::test_inline_ignores_curries_and_partials", "dask/tests/test_optimize.py::test_inline_doesnt_shrink_fast_functions_at_top", "dask/tests/test_optimize.py::test_inline_traverses_lists", "dask/tests/test_optimize.py::test_inline_protects_output_keys", "dask/tests/test_optimize.py::test_functions_of", "dask/tests/test_optimize.py::test_dealias", "dask/tests/test_optimize.py::test_dealias_keys", "dask/tests/test_optimize.py::test_equivalent", "dask/tests/test_optimize.py::test_equivalence_uncomparable", "dask/tests/test_optimize.py::test_sync_keys", "dask/tests/test_optimize.py::test_sync_uncomparable", "dask/tests/test_optimize.py::test_merge_sync", "dask/tests/test_order.py::test_ordering_keeps_groups_together", "dask/tests/test_order.py::test_prefer_broker_nodes", "dask/tests/test_order.py::test_base_of_reduce_preferred", "dask/tests/test_order.py::test_deep_bases_win_over_dependents", "dask/tests/test_order.py::test_prefer_deep", "dask/tests/test_order.py::test_stacklimit", "dask/tests/test_order.py::test_ndependents" ]
[]
BSD 3-Clause "New" or "Revised" License
520
chimpler__pyhocon-81
24117399090b3ca1ea5d041f9de46101569ace13
2016-05-04 14:36:50
4683937b1d195ce2f53ca78987571e41bfe273e7
diff --git a/CHANGELOG.md b/CHANGELOG.md index 373df98..5f75182 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +# Version 0.3.xx (TBA) + +* Implemented self-referential subsitutions + # Version 0.3.25 * ConfigValue.transform: do not wrap lists. PR [#76] diff --git a/README.md b/README.md index a811af0..6153f4f 100644 --- a/README.md +++ b/README.md @@ -300,8 +300,8 @@ Arrays without commas | :white_check_mark: Path expressions | :white_check_mark: Paths as keys | :white_check_mark: Substitutions | :white_check_mark: -Self-referential substitutions | :x: -The `+=` separator | :x: +Self-referential substitutions | :white_check_mark: +The `+=` separator | :white_check_mark: Includes | :white_check_mark: Include semantics: merging | :white_check_mark: Include semantics: substitution | :white_check_mark: @@ -335,6 +335,7 @@ Java properties mapping | :x: - Virgil Palanciuc ([@virgil-palanciuc](https://github.com/virgil-palanciuc)) - Douglas Simon ([@dougxc](https://github.com/dougxc)) - Gilles Duboscq ([@gilles-duboscq](https://github.com/gilles-duboscq)) + - Stefan Anzinger ([@sanzinger](https://github.com/sanzinger)) ### Thanks diff --git a/pyhocon/config_parser.py b/pyhocon/config_parser.py index 5f3d4bd..a029912 100644 --- a/pyhocon/config_parser.py +++ b/pyhocon/config_parser.py @@ -3,7 +3,7 @@ import os import socket import contextlib from pyparsing import Forward, Keyword, QuotedString, Word, Literal, Suppress, Regex, Optional, SkipTo, ZeroOrMore, \ - Group, lineno, col, TokenConverter, replaceWith, alphanums + Group, lineno, col, TokenConverter, replaceWith, alphanums, ParseSyntaxException from pyparsing import ParserElement from pyhocon.config_tree import ConfigTree, ConfigSubstitution, ConfigList, ConfigValues, ConfigUnquotedString, \ ConfigInclude, NoneValue @@ -230,6 +230,7 @@ class ConfigParser(object): (Keyword('url') | Keyword('file')) - Literal('(').suppress() - quoted_string - Literal(')').suppress()))) \ .setParseAction(include_config) + root_dict_expr = Forward() dict_expr = Forward() list_expr = Forward() multi_value_expr = ZeroOrMore((Literal( @@ -237,7 +238,9 @@ class ConfigParser(object): # for a dictionary : or = is optional # last zeroOrMore is because we can have t = {a:4} {b: 6} {c: 7} which is dictionary concatenation inside_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma)) + inside_root_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma), root=True) dict_expr << Suppress('{') - inside_dict_expr - Suppress('}') + root_dict_expr << Suppress('{') - inside_root_dict_expr - Suppress('}') list_entry = ConcatenatedValueParser(multi_value_expr) list_expr << Suppress('[') - ListParser(list_entry - ZeroOrMore(eol_comma - list_entry)) - Suppress(']') @@ -245,12 +248,12 @@ class ConfigParser(object): assign_expr << Group( key - ZeroOrMore(comment_no_comma_eol) - - (dict_expr | Suppress(Literal('=') | Literal(':')) - ZeroOrMore( + (dict_expr | (Literal('=') | Literal(':') | Literal('+=')) - ZeroOrMore( comment_no_comma_eol) - ConcatenatedValueParser(multi_value_expr)) ) # the file can be { ... } where {} can be omitted or [] - config_expr = ZeroOrMore(comment_eol | eol) + (list_expr | dict_expr | inside_dict_expr) + ZeroOrMore( + config_expr = ZeroOrMore(comment_eol | eol) + (list_expr | root_dict_expr | inside_root_dict_expr) + ZeroOrMore( comment_eol | eol_comma) config = config_expr.parseString(content, parseAll=True)[0] if resolve: @@ -290,41 +293,106 @@ class ConfigParser(object): col=col(substitution.loc, substitution.instring))) return True, value + @staticmethod + def _fixup_self_references(config): + if isinstance(config, ConfigTree) and config.root: + for key in config: # Traverse history of element + history = config.history[key] + previous_item = history[0] + for current_item in history[1:]: + for substitution in ConfigParser._find_substitutions(current_item): + prop_path = ConfigTree.parse_key(substitution.variable) + if len(prop_path) > 1 and config.get(substitution.variable, None) is not None: + continue # If value is present in latest version, don't do anything + if prop_path[0] == key: + if isinstance(previous_item, ConfigValues): # We hit a dead end, we cannot evaluate + raise ConfigSubstitutionException("Property {variable} cannot be substituted. Check for cycles.".format( + variable=substitution.variable)) + value = previous_item if len(prop_path) == 1 else previous_item.get(".".join(prop_path[1:])) + (_, _, current_item) = ConfigParser._do_substitute(substitution, value) + previous_item = current_item + + if len(history) == 1: # special case, when self optional referencing without existing + for substitution in ConfigParser._find_substitutions(previous_item): + prop_path = ConfigTree.parse_key(substitution.variable) + if len(prop_path) > 1 and config.get(substitution.variable, None) is not None: + continue # If value is present in latest version, don't do anything + if prop_path[0] == key and substitution.optional: + ConfigParser._do_substitute(substitution, None) + + # traverse config to find all the substitutions + @staticmethod + def _find_substitutions(item): + """Convert HOCON input into a JSON output + + :return: JSON string representation + :type return: basestring + """ + if isinstance(item, ConfigValues): + return item.get_substitutions() + + substitutions = [] + if isinstance(item, ConfigTree): + for key, child in item.items(): + substitutions += ConfigParser._find_substitutions(child) + elif isinstance(item, list): + for child in item: + substitutions += ConfigParser._find_substitutions(child) + return substitutions + + @staticmethod + def _do_substitute(substitution, resolved_value, is_optional_resolved=True): + unresolved = False + new_substitutions = [] + if isinstance(resolved_value, ConfigValues): + resolved_value = resolved_value.transform() + if isinstance(resolved_value, ConfigValues): + unresolved = True + result = None + else: + # replace token by substitution + config_values = substitution.parent + # if it is a string, then add the extra ws that was present in the original string after the substitution + formatted_resolved_value = resolved_value \ + if resolved_value is None \ + or isinstance(resolved_value, (dict, list)) \ + or substitution.index == len(config_values.tokens) - 1 \ + else (str(resolved_value) + substitution.ws) + config_values.put(substitution.index, formatted_resolved_value) + transformation = config_values.transform() + result = None + if transformation is None and not is_optional_resolved: + result = config_values.overriden_value + else: + result = transformation + + if result is None: + del config_values.parent[config_values.key] + else: + config_values.parent[config_values.key] = result + s = ConfigParser._find_substitutions(result) + if s: + new_substitutions = s + unresolved = True + + return (unresolved, new_substitutions, result) + + @staticmethod + def _final_fixup(item): + if isinstance(item, ConfigValues): + return item.transform() + elif isinstance(item, list): + return list([ConfigParser._final_fixup(child) for child in item]) + elif isinstance(item, ConfigTree): + items = list(item.items()) + for key, child in items: + item[key] = ConfigParser._final_fixup(child) + return item + @staticmethod def resolve_substitutions(config): - # traverse config to find all the substitutions - def find_substitutions(item): - """Convert HOCON input into a JSON output - - :return: JSON string representation - :type return: basestring - """ - if isinstance(item, ConfigValues): - return item.get_substitutions() - - substitutions = [] - if isinstance(item, ConfigTree): - for key, child in item.items(): - substitutions += find_substitutions(child) - elif isinstance(item, list): - for child in item: - substitutions += find_substitutions(child) - - return substitutions - - def final_fixup(item): - if isinstance(item, ConfigValues): - return item.transform() - elif isinstance(item, list): - return list([final_fixup(child) for child in item]) - elif isinstance(item, ConfigTree): - items = list(item.items()) - for key, child in items: - item[key] = final_fixup(child) - - return item - - substitutions = find_substitutions(config) + ConfigParser._fixup_self_references(config) + substitutions = ConfigParser._find_substitutions(config) if len(substitutions) > 0: unresolved = True @@ -340,42 +408,11 @@ class ConfigParser(object): if not is_optional_resolved and substitution.optional: resolved_value = None - if isinstance(resolved_value, ConfigValues): - resolved_value = resolved_value.transform() - if isinstance(resolved_value, ConfigValues): - unresolved = True - else: - # replace token by substitution - config_values = substitution.parent - # if it is a string, then add the extra ws that was present in the original string after the substitution - formatted_resolved_value = resolved_value \ - if resolved_value is None \ - or isinstance(resolved_value, (dict, list)) \ - or substitution.index == len(config_values.tokens) - 1 \ - else (str(resolved_value) + substitution.ws) - config_values.put(substitution.index, formatted_resolved_value) - transformation = config_values.transform() - if transformation is None and not is_optional_resolved: - # if it does not override anything remove the key - # otherwise put back old value that it was overriding - if config_values.overriden_value is None: - if config_values.key in config_values.parent: - del config_values.parent[config_values.key] - else: - config_values.parent[config_values.key] = config_values.overriden_value - s = find_substitutions(config_values.overriden_value) - if s: - substitutions.extend(s) - unresolved = True - else: - config_values.parent[config_values.key] = transformation - s = find_substitutions(transformation) - if s: - substitutions.extend(s) - unresolved = True - substitutions.remove(substitution) - - final_fixup(config) + unresolved, new_subsitutions, _ = ConfigParser._do_substitute(substitution, resolved_value, is_optional_resolved) + substitutions.extend(new_subsitutions) + substitutions.remove(substitution) + + ConfigParser._final_fixup(config) if unresolved: raise ConfigSubstitutionException("Cannot resolve {variables}. Check for cycles.".format( variables=', '.join('${{{variable}}}: (line: {line}, col: {col})'.format( @@ -425,8 +462,9 @@ class ConfigTreeParser(TokenConverter): Parse a config tree from tokens """ - def __init__(self, expr=None): + def __init__(self, expr=None, root=False): super(ConfigTreeParser, self).__init__(expr) + self.root = root self.saveAsList = True def postParse(self, instring, loc, token_list): @@ -437,35 +475,47 @@ class ConfigTreeParser(TokenConverter): :param token_list: :return: """ - config_tree = ConfigTree() + config_tree = ConfigTree(root=self.root) for element in token_list: expanded_tokens = element.tokens if isinstance(element, ConfigInclude) else [element] for tokens in expanded_tokens: # key, value1 (optional), ... key = tokens[0].strip() - values = tokens[1:] - + operator = '=' + if len(tokens) == 3 and tokens[1].strip() in [':', '=', '+=']: + operator = tokens[1].strip() + values = tokens[2:] + elif len(tokens) == 2: + values = tokens[1:] + else: + raise ParseSyntaxException("Unknown tokens {} received".format(tokens)) # empty string if len(values) == 0: config_tree.put(key, '') else: value = values[0] - if isinstance(value, list): + if isinstance(value, list) and operator == "+=": + value = ConfigValues([ConfigSubstitution(key, True, '', False, loc), value], False, loc) + config_tree.put(key, value, False) + elif isinstance(value, str) and operator == "+=": + value = ConfigValues([ConfigSubstitution(key, True, '', True, loc), ' ' + value], True, loc) + config_tree.put(key, value, False) + elif isinstance(value, list): config_tree.put(key, value, False) else: - if isinstance(value, ConfigTree): + existing_value = config_tree.get(key, None) + if isinstance(value, ConfigTree) and not isinstance(existing_value, list): + # Only Tree has to be merged with tree config_tree.put(key, value, True) elif isinstance(value, ConfigValues): conf_value = value value.parent = config_tree value.key = key - existing_value = config_tree.get(key, None) if isinstance(existing_value, list) or isinstance(existing_value, ConfigTree): config_tree.put(key, conf_value, True) else: config_tree.put(key, conf_value, False) else: - conf_value = value - config_tree.put(key, conf_value, False) + config_tree.put(key, value, False) return config_tree diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py index 92a7afc..225e15f 100644 --- a/pyhocon/config_tree.py +++ b/pyhocon/config_tree.py @@ -26,8 +26,10 @@ class ConfigTree(OrderedDict): KEY_SEP = '.' def __init__(self, *args, **kwds): + self.root = kwds.pop('root') if 'root' in kwds else False + if self.root: + self.history = {} super(ConfigTree, self).__init__(*args, **kwds) - for key, value in self.items(): if isinstance(value, ConfigValues): value.parent = self @@ -55,6 +57,8 @@ class ConfigTree(OrderedDict): value.key = key value.overriden_value = a.get(key, None) a[key] = value + if a.root: + a.history[key] = (a.history.get(key) or []) + b.history.get(key) return a @@ -65,7 +69,13 @@ class ConfigTree(OrderedDict): # if they are both configs then merge # if not then override if key_elt in self and isinstance(self[key_elt], ConfigTree) and isinstance(value, ConfigTree): - ConfigTree.merge_configs(self[key_elt], value) + if self.root: + new_value = ConfigTree.merge_configs(ConfigTree(), self[key_elt], copy_trees=True) + new_value = ConfigTree.merge_configs(new_value, value, copy_trees=True) + self._push_history(key_elt, new_value) + self[key_elt] = new_value + else: + ConfigTree.merge_configs(self[key_elt], value) elif append: # If we have t=1 # and we try to put t.a=5 then t is replaced by {a: 5} @@ -76,10 +86,16 @@ class ConfigTree(OrderedDict): elif isinstance(l, ConfigTree) and isinstance(value, ConfigValues): value.tokens.append(l) value.recompute() + self._push_history(key_elt, value) + self[key_elt] = value + elif isinstance(l, list) and isinstance(value, ConfigValues): + self._push_history(key_elt, value) self[key_elt] = value elif isinstance(l, list): l += value + self._push_history(key_elt, l) elif l is None: + self._push_history(key_elt, value) self[key_elt] = value else: @@ -96,15 +112,24 @@ class ConfigTree(OrderedDict): value.parent = self value.key = key_elt value.overriden_value = self.get(key_elt, None) - super(ConfigTree, self).__setitem__(key_elt, value) + self._push_history(key_elt, value) + self[key_elt] = value else: next_config_tree = super(ConfigTree, self).get(key_elt) if not isinstance(next_config_tree, ConfigTree): # create a new dictionary or overwrite a previous value next_config_tree = ConfigTree() + self._push_history(key_elt, value) self[key_elt] = next_config_tree next_config_tree._put(key_path[1:], value, append) + def _push_history(self, key, value): + if self.root: + hist = self.history.get(key) + if hist is None: + hist = self.history[key] = [] + hist.append(value) + def _get(self, key_path, key_index=0, default=UndefinedKey): key_elt = key_path[key_index] elt = super(ConfigTree, self).get(key_elt, UndefinedKey) @@ -130,7 +155,8 @@ class ConfigTree(OrderedDict): else: return default - def _parse_key(self, str): + @staticmethod + def parse_key(str): """ Split a key into path elements: - a.b.c => a, b, c @@ -150,7 +176,7 @@ class ConfigTree(OrderedDict): :type key: basestring :param value: value to put """ - self._put(self._parse_key(key), value, append) + self._put(ConfigTree.parse_key(key), value, append) def get(self, key, default=UndefinedKey): """Get a value from the tree @@ -161,7 +187,7 @@ class ConfigTree(OrderedDict): :type default: object :return: value in the tree located at key """ - return self._get(self._parse_key(key), 0, default) + return self._get(ConfigTree.parse_key(key), 0, default) def get_string(self, key, default=UndefinedKey): """Return string representation of value found at key
support for "+=" field separator? I get an error when parsing a hocon file: ``` [ec2-user@ip-172-16-2-117 ~]$ pyhocon -i /opt/mapr/drill/drill-1.1.0/conf/drill-override-example.conf Traceback (most recent call last): File "/usr/local/bin/pyhocon", line 9, in <module> load_entry_point('pyhocon==0.3.4', 'console_scripts', 'pyhocon')() File "/usr/local/lib/python2.7/site-packages/pyhocon/tool.py", line 188, in main HOCONConverter.convert(args.input, args.output, args.format) File "/usr/local/lib/python2.7/site-packages/pyhocon/tool.py", line 145, in convert config = ConfigFactory.parse_file(input_file) File "/usr/local/lib/python2.7/site-packages/pyhocon/__init__.py", line 40, in parse_file return ConfigFactory.parse_string(content, os.path.dirname(filename)) File "/usr/local/lib/python2.7/site-packages/pyhocon/__init__.py", line 75, in parse_string return ConfigParser().parse(content, basedir) File "/usr/local/lib/python2.7/site-packages/pyhocon/__init__.py", line 216, in parse config = config_expr.parseString(content, parseAll=True)[0] File "/usr/local/lib/python2.7/site-packages/pyparsing.py", line 1125, in parseString raise exc pyparsing.ParseSyntaxException: Expected "{" (at char 1087), (line:20, col:33) ``` Line 20 in the above looks like this: ``` drill.logical.function.packages += "org.apache.drill.exec.expr.fn.impl" ``` And column 33 implicates the "+=" field separator. Any plans to add support for this? https://github.com/typesafehub/config/blob/master/HOCON.md#the--field-separator
chimpler/pyhocon
diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index a639f89..2c93f13 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -706,6 +706,234 @@ class TestConfigParser(object): """ ) + def test_self_ref_substitution_array(self): + config = ConfigFactory.parse_string( + """ + x = [1,2] + x = ${x} [3,4] + x = [-1, 0] ${x} [5, 6] + x = [-3, -2] ${x} + """ + ) + assert config.get("x") == [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6] + + def test_self_append_array(self): + config = ConfigFactory.parse_string( + """ + x = [1,2] + x += [3,4] + """ + ) + assert config.get("x") == [1, 2, 3, 4] + + def test_self_append_string(self): + ''' + Should be equivalent to + x = abc + x = ${?x} def + ''' + config = ConfigFactory.parse_string( + """ + x = abc + x += def + """ + ) + assert config.get("x") == "abc def" + + def test_self_append_non_existent_string(self): + ''' + Should be equivalent to x = ${?x} def + ''' + config = ConfigFactory.parse_string( + """ + x += def + """ + ) + assert config.get("x") == " def" + + def test_self_append_nonexistent_array(self): + config = ConfigFactory.parse_string( + """ + x += [1,2] + """ + ) + assert config.get("x") == [1, 2] + + def test_self_append_object(self): + config = ConfigFactory.parse_string( + """ + x = {a: 1} + x += {b: 2} + """ + ) + assert config.get("x") == {'a': 1, 'b': 2} + + def test_self_append_nonexistent_object(self): + config = ConfigFactory.parse_string( + """ + x += {a: 1} + """ + ) + assert config.get("x") == {'a': 1} + + def test_self_ref_substitution_array_to_dict(self): + config = ConfigFactory.parse_string( + """ + x = [1,2] + x = {x: [3,4]} + x = {y: [5,6]} + x = {z: ${x}} + """ + ) + assert config.get("x.x") == [3, 4] + assert config.get("x.y") == [5, 6] + assert config.get("x.z") == {'x': [3, 4], 'y': [5, 6]} + + def test_self_ref_substitiotion_dict_in_array(self): + config = ConfigFactory.parse_string( + """ + x = {x: [3,4]} + x = [${x}, 2, 3] + """ + ) + (one, two, three) = config.get("x") + assert one == {'x': [3, 4]} + assert two == 2 + assert three == 3 + + def test_self_ref_substitution_dict_path(self): + config = ConfigFactory.parse_string( + """ + x = {y: {z: 1}} + x = ${x.y} + """ + ) + assert config.get("x.y") == {'z': 1} + assert config.get("x.z") == 1 + assert set(config.get("x").keys()) == set(['y', 'z']) + + def test_self_ref_substitution_dict_path_hide(self): + config = ConfigFactory.parse_string( + """ + x = {y: {y: 1}} + x = ${x.y} + """ + ) + assert config.get("x.y") == {'y': 1} + assert set(config.get("x").keys()) == set(['y']) + + def test_self_ref_substitution_dict_recurse(self): + with pytest.raises(ConfigSubstitutionException): + ConfigFactory.parse_string( + """ + x = ${x} + """ + ) + + def test_self_ref_substitution_dict_recurse2(self): + with pytest.raises(ConfigSubstitutionException): + ConfigFactory.parse_string( + """ + x = ${x} + x = ${x} + """ + ) + + def test_self_ref_substitution_dict_merge(self): + ''' + Example from HOCON spec + ''' + config = ConfigFactory.parse_string( + """ + foo : { a : { c : 1 } } + foo : ${foo.a} + foo : { a : 2 } + """ + ) + assert config.get('foo') == {'a': 2, 'c': 1} + assert set(config.keys()) == set(['foo']) + + def test_self_ref_substitution_dict_otherfield(self): + ''' + Example from HOCON spec + ''' + config = ConfigFactory.parse_string( + """ + bar : { + foo : 42, + baz : ${bar.foo} + } + """ + ) + assert config.get("bar") == {'foo': 42, 'baz': 42} + assert set(config.keys()) == set(['bar']) + + def test_self_ref_substitution_dict_otherfield_merged_in(self): + ''' + Example from HOCON spec + ''' + config = ConfigFactory.parse_string( + """ + bar : { + foo : 42, + baz : ${bar.foo} + } + bar : { foo : 43 } + """ + ) + assert config.get("bar") == {'foo': 43, 'baz': 43} + assert set(config.keys()) == set(['bar']) + + def test_self_ref_substitution_dict_otherfield_merged_in_mutual(self): + ''' + Example from HOCON spec + ''' + config = ConfigFactory.parse_string( + """ + // bar.a should end up as 4 + bar : { a : ${foo.d}, b : 1 } + bar.b = 3 + // foo.c should end up as 3 + foo : { c : ${bar.b}, d : 2 } + foo.d = 4 + """ + ) + assert config.get("bar") == {'a': 4, 'b': 3} + assert config.get("foo") == {'c': 3, 'd': 4} + assert set(config.keys()) == set(['bar', 'foo']) + + def test_self_ref_substitution_string_opt_concat(self): + ''' + Example from HOCON spec + ''' + config = ConfigFactory.parse_string( + """ + a = ${?a}foo + """ + ) + assert config.get("a") == 'foo' + assert set(config.keys()) == set(['a']) + + def test_self_ref_substitution_dict_recurse_part(self): + with pytest.raises(ConfigSubstitutionException): + ConfigFactory.parse_string( + """ + x = ${x} {y: 1} + x = ${x.y} + """ + ) + + def test_self_ref_substitution_object(self): + config = ConfigFactory.parse_string( + """ + x = {a: 1, b: 2} + x = ${x} {c: 3} + x = {z: 0} ${x} + x = {y: -1} ${x} {d: 4} + """ + ) + assert config.get("x") == {'a': 1, 'b': 2, 'c': 3, 'z': 0, 'y': -1, 'd': 4} + def test_concat_multi_line_string(self): config = ConfigFactory.parse_string( """ @@ -1278,6 +1506,66 @@ class TestConfigParser(object): 'large-jvm-opts': ['-XX:+UseParNewGC', '-Xm16g'] } + def test_fallback_self_ref_substitutions_append(self): + config1 = ConfigFactory.parse_string( + """ + list = [ 1, 2, 3 ] + """ + ) + config2 = ConfigFactory.parse_string( + """ + list = ${list} [ 4, 5, 6 ] + """, + resolve=False + ) + config2 = config2.with_fallback(config1) + assert config2.get("list") == [1, 2, 3, 4, 5, 6] + + def test_fallback_self_ref_substitutions_append_plus_equals(self): + config1 = ConfigFactory.parse_string( + """ + list = [ 1, 2, 3 ] + """ + ) + config2 = ConfigFactory.parse_string( + """ + list += [ 4, 5, 6 ] + """, + resolve=False + ) + config2 = config2.with_fallback(config1) + assert config2.get("list") == [1, 2, 3, 4, 5, 6] + + def test_fallback_self_ref_substitutions_merge(self): + config1 = ConfigFactory.parse_string( + """ + dict = { x: 1 } + """ + ) + config2 = ConfigFactory.parse_string( + """ + dict = ${dict} { y: 2 } + """, + resolve=False + ) + config2 = config2.with_fallback(config1) + assert config2.get("dict") == {'x': 1, 'y': 2} + + def test_fallback_self_ref_substitutions_concat_string(self): + config1 = ConfigFactory.parse_string( + """ + string = abc + """ + ) + config2 = ConfigFactory.parse_string( + """ + string = ${string}def + """, + resolve=False + ) + config2 = config2.with_fallback(config1) + assert config2.get("string") == 'abcdef' + def test_object_field_substitution(self): config = ConfigFactory.parse_string( """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 4 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.4", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 -e git+https://github.com/chimpler/pyhocon.git@24117399090b3ca1ea5d041f9de46101569ace13#egg=pyhocon pyparsing==2.1.1 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: pyhocon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==2.1.1 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/pyhocon
[ "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array", "tests/test_config_parser.py::TestConfigParser::test_self_append_array", "tests/test_config_parser.py::TestConfigParser::test_self_append_string", "tests/test_config_parser.py::TestConfigParser::test_self_append_non_existent_string", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_array", "tests/test_config_parser.py::TestConfigParser::test_self_append_object", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_object", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array_to_dict", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitiotion_dict_in_array", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path_hide", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_string_opt_concat", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse_part", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_object", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append_plus_equals", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_merge", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_concat_string" ]
[]
[ "tests/test_config_parser.py::TestConfigParser::test_parse_simple_value", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket", "tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots", "tests/test_config_parser.py::TestConfigParser::test_dotted_notation_merge", "tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr", "tests/test_config_parser.py::TestConfigParser::test_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_parse_with_comments", "tests/test_config_parser.py::TestConfigParser::test_missing_config", "tests/test_config_parser.py::TestConfigParser::test_parse_null", "tests/test_config_parser.py::TestConfigParser::test_parse_empty", "tests/test_config_parser.py::TestConfigParser::test_parse_override", "tests/test_config_parser.py::TestConfigParser::test_concat_dict", "tests/test_config_parser.py::TestConfigParser::test_concat_string", "tests/test_config_parser.py::TestConfigParser::test_concat_list", "tests/test_config_parser.py::TestConfigParser::test_bad_concat", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions_with_no_space", "tests/test_config_parser.py::TestConfigParser::test_int_substitutions", "tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_multiple_substitutions", "tests/test_config_parser.py::TestConfigParser::test_dict_substitutions", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_unquoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_triple_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_int_noeol", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_float_noeol", "tests/test_config_parser.py::TestConfigParser::test_list_substitutions", "tests/test_config_parser.py::TestConfigParser::test_list_element_substitution", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append_substitution", "tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution", "tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse2", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in_mutual", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_samples", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_invalid", "tests/test_config_parser.py::TestConfigParser::test_include_dict_from_samples", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts_with_merge", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists_with_merge", "tests/test_config_parser.py::TestConfigParser::test_invalid_assignment", "tests/test_config_parser.py::TestConfigParser::test_invalid_dict", "tests/test_config_parser.py::TestConfigParser::test_include_list", "tests/test_config_parser.py::TestConfigParser::test_include_dict", "tests/test_config_parser.py::TestConfigParser::test_include_substitution", "tests/test_config_parser.py::TestConfigParser::test_substitution_override", "tests/test_config_parser.py::TestConfigParser::test_substitution_flat_override", "tests/test_config_parser.py::TestConfigParser::test_substitution_nested_override", "tests/test_config_parser.py::TestConfigParser::test_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_cascade_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_substitution_cycle", "tests/test_config_parser.py::TestConfigParser::test_assign_number_with_eol", "tests/test_config_parser.py::TestConfigParser::test_assign_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_assign_list_numbers_with_eol", "tests/test_config_parser.py::TestConfigParser::test_assign_list_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_with_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_no_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite_file", "tests/test_config_parser.py::TestConfigParser::test_object_field_substitution", "tests/test_config_parser.py::TestConfigParser::test_one_line_quote_escape", "tests/test_config_parser.py::TestConfigParser::test_multi_line_escape", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_dict", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_nested_dict", "tests/test_config_parser.py::TestConfigParser::test_object_concat", "tests/test_config_parser.py::TestConfigParser::test_issue_75" ]
[]
Apache License 2.0
521
sympy__sympy-11080
ef47677483b2f29d0b8e6a0eb45de72b2e34477d
2016-05-05 22:11:31
8bb5814067cfa0348fb8b708848f35dba2b55ff4
lindsayad: Please let me know if there's additional work (or complete re-work!) that needs to be done in order for this to go in. lindsayad: Can someone tell this contributing newbie why the different tests are failing? jksuom: It looks like the code in manualintegrate is running in a loop. You could investigate by testing one new rule at a time.
diff --git a/sympy/integrals/manualintegrate.py b/sympy/integrals/manualintegrate.py index 50d75d5f92..e8cda04f04 100644 --- a/sympy/integrals/manualintegrate.py +++ b/sympy/integrals/manualintegrate.py @@ -47,7 +47,6 @@ def __eq__(self, other): TrigRule = Rule("TrigRule", "func arg") ExpRule = Rule("ExpRule", "base exp") ReciprocalRule = Rule("ReciprocalRule", "func") -ArctanRule = Rule("ArctanRule") ArcsinRule = Rule("ArcsinRule") InverseHyperbolicRule = Rule("InverseHyperbolicRule", "func") AlternativeRule = Rule("AlternativeRule", "alternatives") @@ -58,6 +57,9 @@ def __eq__(self, other): HeavisideRule = Rule("HeavisideRule", "harg ibnd substep") TrigSubstitutionRule = Rule("TrigSubstitutionRule", "theta func rewritten substep restriction") +ArctanRule = Rule("ArctanRule", "a b c") +ArccothRule = Rule("ArccothRule", "a b c") +ArctanhRule = Rule("ArctanhRule", "a b c") IntegralInfo = namedtuple('IntegralInfo', 'integrand symbol') @@ -170,7 +172,7 @@ def _rewriter(integral): rewritten = rewrite(*integral) if rewritten != integrand: substep = integral_steps(rewritten, symbol) - if not isinstance(substep, DontKnowRule): + if not isinstance(substep, DontKnowRule) and substep: return RewriteRule( rewritten, substep, @@ -286,12 +288,12 @@ def make_inverse_trig(RuleClass, base_exp, a, sign_a, b, sign_b): substep = RuleClass(current_base ** base_exp, current_symbol) if u_func is not None: - if u_constant != 1: + if u_constant != 1 and substep is not None: substep = ConstantTimesRule( u_constant, current_base ** base_exp, substep, u_constant * current_base ** base_exp, symbol) substep = URule(u_var, u_func, u_constant, substep, factored, symbol) - if constant is not None: + if constant is not None and substep is not None: substep = ConstantTimesRule(constant, factored, substep, integrand, symbol) return substep @@ -300,9 +302,7 @@ def make_inverse_trig(RuleClass, base_exp, a, sign_a, b, sign_b): # list of (rule, base_exp, a, sign_a, b, sign_b, condition) possibilities = [] - if sympy.simplify(exp + 1) == 0 and not (negative(a) or negative(b)): - possibilities.append((ArctanRule, exp, a, 1, b, 1, sympy.And(a > 0, b > 0))) - elif sympy.simplify(2*exp + 1) == 0: + if sympy.simplify(2*exp + 1) == 0: possibilities.append((ArcsinRule, exp, a, 1, -b, -1, sympy.And(a > 0, b < 0))) possibilities.append((ArcsinhRule, exp, a, 1, b, 1, sympy.And(a > 0, b > 0))) possibilities.append((ArccoshRule, exp, -a, -1, b, 1, sympy.And(a < 0, b > 0))) @@ -330,22 +330,25 @@ def mul_rule(integral): # Constant times function case coeff, f = integrand.as_independent(symbol) + next_step = integral_steps(f, symbol) - if coeff != 1: + if coeff != 1 and next_step is not None: return ConstantTimesRule( coeff, f, - integral_steps(f, symbol), + next_step, integrand, symbol) def _parts_rule(integrand, symbol): # LIATE rule: - # log, inverse trig, algebraic (polynomial), trigonometric, exponential - def pull_out_polys(integrand): - integrand = integrand.together() - polys = [arg for arg in integrand.args if arg.is_polynomial(symbol)] - if polys: - u = sympy.Mul(*polys) - dv = integrand / u + # log, inverse trig, algebraic, trigonometric, exponential + def pull_out_algebraic(integrand): + integrand = integrand.cancel().together() + algebraic = [arg for arg in integrand.args if arg.is_algebraic_expr(symbol)] + if algebraic: + u = sympy.Mul(*algebraic) + dv = (integrand / u).cancel() + if not u.is_polynomial() and isinstance(dv, sympy.exp): + return return u, dv def pull_out_u(*functions): @@ -361,7 +364,7 @@ def pull_out_u_rl(integrand): return pull_out_u_rl liate_rules = [pull_out_u(sympy.log), pull_out_u(sympy.atan, sympy.asin, sympy.acos), - pull_out_polys, pull_out_u(sympy.sin, sympy.cos), + pull_out_algebraic, pull_out_u(sympy.sin, sympy.cos), pull_out_u(sympy.exp)] @@ -386,9 +389,9 @@ def pull_out_u_rl(integrand): for rule in liate_rules[index + 1:]: r = rule(integrand) # make sure dv is amenable to integration - if r and r[0].subs(dummy, 1) == dv: + if r and sympy.simplify(r[0].subs(dummy, 1)) == sympy.simplify(dv): du = u.diff(symbol) - v_step = integral_steps(dv, symbol) + v_step = integral_steps(sympy.simplify(dv), symbol) v = _manualintegrate(v_step) return u, dv, v, du, v_step @@ -408,6 +411,8 @@ def parts_rule(integral): return while True: + if (integrand / (v * du)).cancel() == 1: + break if symbol not in (integrand / (v * du)).cancel().free_symbols: coefficient = ((v * du) / integrand).cancel() rule = CyclicPartsRule( @@ -416,7 +421,7 @@ def parts_rule(integral): (-1) ** len(steps) * coefficient, integrand, symbol ) - if constant != 1: + if (constant != 1) and rule: rule = ConstantTimesRule(constant, integrand, rule, constant * integrand, symbol) return rule @@ -436,14 +441,18 @@ def make_second_step(steps, integrand): make_second_step(steps[1:], v * du), integrand, symbol) else: - return integral_steps(integrand, symbol) + steps = integral_steps(integrand, symbol) + if steps: + return steps + else: + return DontKnowRule(integrand, symbol) if steps: u, dv, v, du, v_step = steps[0] rule = PartsRule(u, dv, v_step, make_second_step(steps[1:], v * du), integrand, symbol) - if constant != 1: + if (constant != 1) and rule: rule = ConstantTimesRule(constant, integrand, rule, constant * integrand, symbol) return rule @@ -498,7 +507,7 @@ def trig_product_rule(integral): if symbol not in q.free_symbols: rule = TrigRule('sec*tan', symbol, sectan, symbol) - if q != 1: + if q != 1 and rule: rule = ConstantTimesRule(q, sectan, rule, integrand, symbol) return rule @@ -508,11 +517,53 @@ def trig_product_rule(integral): if symbol not in q.free_symbols: rule = TrigRule('csc*cot', symbol, csccot, symbol) - if q != 1: + if q != 1 and rule: rule = ConstantTimesRule(q, csccot, rule, integrand, symbol) return rule +def quadratic_denom_rule(integral): + integrand, symbol = integral + a = sympy.Wild('a', exclude=[symbol]) + b = sympy.Wild('b', exclude=[symbol]) + c = sympy.Wild('c', exclude=[symbol]) + match = integrand.match(a / (b * symbol ** 2 + c)) + + if not match: + return + + a, b, c = match[a], match[b], match[c] + return PiecewiseRule([(ArctanRule(a, b, c, integrand, symbol), sympy.Gt(c / b, 0)), + (ArccothRule(a, b, c, integrand, symbol), sympy.And(sympy.Gt(symbol ** 2, -c / b), sympy.Lt(c / b, 0))), + (ArctanhRule(a, b, c, integrand, symbol), sympy.And(sympy.Lt(symbol ** 2, -c / b), sympy.Lt(c / b, 0))), + ], integrand, symbol) + +def root_mul_rule(integral): + integrand, symbol = integral + a = sympy.Wild('a', exclude=[symbol]) + b = sympy.Wild('b', exclude=[symbol]) + c = sympy.Wild('c') + match = integrand.match(sympy.sqrt(a * symbol + b) * c) + + if not match: + return + + a, b, c = match[a], match[b], match[c] + d = sympy.Wild('d', exclude=[symbol]) + e = sympy.Wild('e', exclude=[symbol]) + f = sympy.Wild('f') + recursion_test = c.match(sympy.sqrt(d * symbol + e) * f) + if recursion_test: + return + + u = sympy.Dummy('u') + u_func = sympy.sqrt(a * symbol + b) + integrand = integrand.subs(u_func, u) + integrand = integrand.subs(symbol, (u**2 - b) / a) + integrand = integrand * 2 * u / a + next_step = integral_steps(integrand, u) + if next_step: + return URule(u, u_func, None, next_step, integrand, symbol) @sympy.cacheit def make_wilds(symbol): @@ -761,7 +812,8 @@ def substitution_rule(integral): if sympy.simplify(c - 1) != 0: _, denom = c.as_numer_denom() - subrule = ConstantTimesRule(c, substituted, subrule, substituted, u_var) + if subrule: + subrule = ConstantTimesRule(c, substituted, subrule, substituted, u_var) if denom.free_symbols: piecewise = [] @@ -808,6 +860,12 @@ def substitution_rule(integral): lambda integrand, symbol: integrand.is_rational_function(), lambda integrand, symbol: integrand.apart(symbol)) +cancel_rule = rewriter( + # lambda integrand, symbol: integrand.is_algebraic_expr(), + # lambda integrand, symbol: isinstance(integrand, sympy.Mul), + lambda integrand, symbol: True, + lambda integrand, symbol: integrand.cancel()) + distribute_expand_rule = rewriter( lambda integrand, symbol: ( all(arg.is_Pow or arg.is_polynomial(symbol) for arg in integrand.args) @@ -855,8 +913,10 @@ def integral_steps(integrand, symbol, **options): >>> print(repr(integral_steps(exp(x) / (1 + exp(2 * x)), x))) \ # doctest: +NORMALIZE_WHITESPACE URule(u_var=_u, u_func=exp(x), constant=1, - substep=ArctanRule(context=1/(_u**2 + 1), symbol=_u), - context=exp(x)/(exp(2*x) + 1), symbol=x) + substep=PiecewiseRule(subfunctions=[(ArctanRule(a=1, b=1, c=1, context=1/(_u**2 + 1), symbol=_u), True), + (ArccothRule(a=1, b=1, c=1, context=1/(_u**2 + 1), symbol=_u), False), + (ArctanhRule(a=1, b=1, c=1, context=1/(_u**2 + 1), symbol=_u), False)], + context=1/(_u**2 + 1), symbol=_u), context=exp(x)/(exp(2*x) + 1), symbol=x) >>> print(repr(integral_steps(sin(x), x))) \ # doctest: +NORMALIZE_WHITESPACE TrigRule(func='sin', arg=x, context=sin(x), symbol=x) @@ -914,12 +974,14 @@ def _integral_is_subclass(integral): result = do_one( null_safe(switch(key, { - sympy.Pow: do_one(null_safe(power_rule), null_safe(inverse_trig_rule)), + sympy.Pow: do_one(null_safe(power_rule), null_safe(inverse_trig_rule), \ + null_safe(quadratic_denom_rule)), sympy.Symbol: power_rule, sympy.exp: exp_rule, sympy.Add: add_rule, sympy.Mul: do_one(null_safe(mul_rule), null_safe(trig_product_rule), \ - null_safe(heaviside_rule)), + null_safe(heaviside_rule), null_safe(quadratic_denom_rule), \ + null_safe(root_mul_rule)), sympy.Derivative: derivative_rule, TrigonometricFunction: trig_rule, sympy.Heaviside: heaviside_rule, @@ -933,6 +995,9 @@ def _integral_is_subclass(integral): condition( integral_is_subclass(sympy.Mul, sympy.Pow), partial_fractions_rule), + condition( + integral_is_subclass(sympy.Mul, sympy.Pow), + cancel_rule), condition( integral_is_subclass(sympy.Mul, sympy.log, sympy.atan, sympy.asin, sympy.acos), parts_rule), @@ -975,6 +1040,7 @@ def eval_u(u_var, u_func, constant, substep, integrand, symbol): @evaluates(PartsRule) def eval_parts(u, dv, v_step, second_step, integrand, symbol): v = _manualintegrate(v_step) + return u * v - _manualintegrate(second_step) @evaluates(CyclicPartsRule) @@ -1004,14 +1070,22 @@ def eval_trig(func, arg, integrand, symbol): elif func == 'csc**2': return -sympy.cot(arg) +@evaluates(ArctanRule) +def eval_arctan(a, b, c, integrand, symbol): + return a / b * 1 / sympy.sqrt(c / b) * sympy.atan(symbol / sympy.sqrt(c / b)) + +@evaluates(ArccothRule) +def eval_arccoth(a, b, c, integrand, symbol): + return - a / b * 1 / sympy.sqrt(-c / b) * sympy.acoth(symbol / sympy.sqrt(-c / b)) + +@evaluates(ArctanhRule) +def eval_arctanh(a, b, c, integrand, symbol): + return - a / b * 1 / sympy.sqrt(-c / b) * sympy.atanh(symbol / sympy.sqrt(-c / b)) + @evaluates(ReciprocalRule) def eval_reciprocal(func, integrand, symbol): return sympy.ln(func) -@evaluates(ArctanRule) -def eval_arctan(integrand, symbol): - return sympy.atan(symbol) - @evaluates(ArcsinRule) def eval_arcsin(integrand, symbol): return sympy.asin(symbol) @@ -1093,6 +1167,7 @@ def eval_dontknowrule(integrand, symbol): def _manualintegrate(rule): evaluator = evaluators.get(rule.__class__) if not evaluator: + raise ValueError("Cannot evaluate rule %s" % repr(rule)) return evaluator(*rule)
integrate(sqrt(x - y) * log(z / x), x) has no result but with Mathematica I can get a solution: 2/9 (6 y^(3/2) ArcTan(Sqrt(x - y)/Sqrt(y)) + Sqrt(x - y) (2 (x - 4 y) + 3 (x - y) Log(z/x))) Where in sympy would we have to do work to implement a solution?
sympy/sympy
diff --git a/sympy/integrals/tests/test_manual.py b/sympy/integrals/tests/test_manual.py index 6c968fb059..f6ee9ab49e 100644 --- a/sympy/integrals/tests/test_manual.py +++ b/sympy/integrals/tests/test_manual.py @@ -1,11 +1,11 @@ from sympy import (sin, cos, tan, sec, csc, cot, log, exp, atan, asin, acos, Symbol, Integral, integrate, pi, Dummy, Derivative, - diff, I, sqrt, erf, Piecewise, Eq, symbols, - And, Heaviside, S, asinh, acosh) + diff, I, sqrt, erf, Piecewise, Eq, symbols, Rational, + And, Heaviside, S, asinh, acosh, atanh, acoth, expand) from sympy.integrals.manualintegrate import manualintegrate, find_substitutions, \ _parts_rule -x, y, u, n, a, b = symbols('x y u n a b') +x, y, z, u, n, a, b, c = symbols('x y z u n a b c') def test_find_substitutions(): @@ -45,7 +45,7 @@ def test_manualintegrate_parts(): assert manualintegrate(x * log(x), x) == x**2*log(x)/2 - x**2/4 assert manualintegrate(log(x), x) == x * log(x) - x assert manualintegrate((3*x**2 + 5) * exp(x), x) == \ - -6*x*exp(x) + (3*x**2 + 5)*exp(x) + 6*exp(x) + 3*x**2*exp(x) - 6*x*exp(x) + 11*exp(x) assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2 # Make sure _parts_rule doesn't pick u = constant but can pick dv = @@ -99,11 +99,17 @@ def test_manualintegrate_inversetrig(): assert manualintegrate(1 / (4 + x**2), x) == atan(x / 2) / 2 assert manualintegrate(1 / (1 + 4 * x**2), x) == atan(2*x) / 2 assert manualintegrate(1/(a + b*x**2), x) == \ - Piecewise(((sqrt(a/b)*atan(x*sqrt(b/a))/a), And(a > 0, b > 0))) + Piecewise((atan(x/sqrt(a/b))/(b*sqrt(a/b)), a/b > 0), \ + (-acoth(x/sqrt(-a/b))/(b*sqrt(-a/b)), And(a/b < 0, x**2 > -a/b)), \ + (-atanh(x/sqrt(-a/b))/(b*sqrt(-a/b)), And(a/b < 0, x**2 < -a/b))) assert manualintegrate(1/(4 + b*x**2), x) == \ - Piecewise((sqrt(1/b)*atan(sqrt(b)*x/2)/2, b > 0)) + Piecewise((atan(x/(2*sqrt(1/b)))/(2*b*sqrt(1/b)), 4/b > 0), \ + (-acoth(x/(2*sqrt(-1/b)))/(2*b*sqrt(-1/b)), And(4/b < 0, x**2 > -4/b)), \ + (-atanh(x/(2*sqrt(-1/b)))/(2*b*sqrt(-1/b)), And(4/b < 0, x**2 < -4/b))) assert manualintegrate(1/(a + 4*x**2), x) == \ - Piecewise((atan(2*x*sqrt(1/a))/(2*sqrt(a)), a > 0)) + Piecewise((atan(2*x/sqrt(a))/(2*sqrt(a)), a/4 > 0), \ + (-acoth(2*x/sqrt(-a))/(2*sqrt(-a)), And(a/4 < 0, x**2 > -a/4)), \ + (-atanh(2*x/sqrt(-a))/(2*sqrt(-a)), And(a/4 < 0, x**2 < -a/4))) assert manualintegrate(1/(4 + 4*x**2), x) == atan(x) / 4 # asin @@ -165,8 +171,8 @@ def test_manualintegrate_trig_substitution(): def test_manualintegrate_rational(): - assert manualintegrate(1/(4 - x**2), x) == -log(x - 2)/4 + log(x + 2)/4 - assert manualintegrate(1/(-1 + x**2), x) == log(x - 1)/2 - log(x + 1)/2 + assert manualintegrate(1/(4 - x**2), x) == Piecewise((acoth(x/2)/2, x**2 > 4), (atanh(x/2)/2, x**2 < 4)) + assert manualintegrate(1/(-1 + x**2), x) == Piecewise((-acoth(x), x**2 > 1), (-atanh(x), x**2 < 1)) def test_manualintegrate_derivative(): @@ -247,7 +253,10 @@ def test_issue_6746(): (y + 1)**(n*x)/(n*log(y + 1)) a = Symbol('a', negative=True) assert manualintegrate(1 / (a + b*x**2), x) == \ - Integral(1/(a + b*x**2), x) + Piecewise((atan(x/sqrt(a/b))/(b*sqrt(a/b)), a/b > 0), \ + (-acoth(x/sqrt(-a/b))/(b*sqrt(-a/b)), And(a/b < 0, x**2 > -a/b)), \ + (-atanh(x/sqrt(-a/b))/(b*sqrt(-a/b)), And(a/b < 0, x**2 < -a/b))) + def test_issue_2850(): @@ -258,6 +267,46 @@ def test_issue_2850(): assert manualintegrate(atan(x)*log(x), x) == -x*atan(x) + (x*atan(x) - \ log(x**2 + 1)/2)*log(x) + log(x**2 + 1)/2 + Integral(log(x**2 + 1)/x, x)/2 +def test_issue_9462(): + assert manualintegrate(sin(2*x)*exp(x), x) == -3*exp(x)*sin(2*x) \ + - 2*exp(x)*cos(2*x) + 4*Integral(2*exp(x)*cos(2*x), x) + assert manualintegrate((x - 3) / (x**2 - 2*x + 2)**2, x) == \ + Integral(x/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) \ + - 3*Integral(1/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) + +def test_issue_10847(): + assert manualintegrate(x**2 / (x**2 - c), x) == c*Piecewise((atan(x/sqrt(-c))/sqrt(-c), -c > 0), \ + (-acoth(x/sqrt(c))/sqrt(c), And(-c < 0, x**2 > c)), \ + (-atanh(x/sqrt(c))/sqrt(c), And(-c < 0, x**2 < c))) + x + assert manualintegrate(sqrt(x - y) * log(z / x), x) == 4*y**2*Piecewise((atan(sqrt(x - y)/sqrt(y))/sqrt(y), y > 0), \ + (-acoth(sqrt(x - y)/sqrt(-y))/sqrt(-y), \ + And(x - y > -y, y < 0)), \ + (-atanh(sqrt(x - y)/sqrt(-y))/sqrt(-y), \ + And(x - y < -y, y < 0)))/3 \ + - 4*y*sqrt(x - y)/3 + 2*(x - y)**(3/2)*log(z/x)/3 \ + + 4*(x - y)**(3/2)/9 + + assert manualintegrate(sqrt(x) * log(x), x) == 2*x**(3/2)*log(x)/3 - 4*x**(3/2)/9 + assert manualintegrate(sqrt(a*x + b) / x, x) == -2*b*Piecewise((-atan(sqrt(a*x + b)/sqrt(-b))/sqrt(-b), -b > 0), \ + (acoth(sqrt(a*x + b)/sqrt(b))/sqrt(b), And(-b < 0, a*x + b > b)), \ + (atanh(sqrt(a*x + b)/sqrt(b))/sqrt(b), And(-b < 0, a*x + b < b))) \ + + 2*sqrt(a*x + b) + + assert expand(manualintegrate(sqrt(a*x + b) / (x + c), x)) == -2*a*c*Piecewise((atan(sqrt(a*x + b)/sqrt(a*c - b))/sqrt(a*c - b), \ + a*c - b > 0), (-acoth(sqrt(a*x + b)/sqrt(-a*c + b))/sqrt(-a*c + b), And(a*c - b < 0, a*x + b > -a*c + b)), \ + (-atanh(sqrt(a*x + b)/sqrt(-a*c + b))/sqrt(-a*c + b), And(a*c - b < 0, a*x + b < -a*c + b))) \ + + 2*b*Piecewise((atan(sqrt(a*x + b)/sqrt(a*c - b))/sqrt(a*c - b), a*c - b > 0), \ + (-acoth(sqrt(a*x + b)/sqrt(-a*c + b))/sqrt(-a*c + b), And(a*c - b < 0, a*x + b > -a*c + b)), \ + (-atanh(sqrt(a*x + b)/sqrt(-a*c + b))/sqrt(-a*c + b), And(a*c - b < 0, a*x + b < -a*c + b))) + 2*sqrt(a*x + b) + + assert manualintegrate((4*x**4 + 4*x**3 + 16*x**2 + 12*x + 8) \ + / (x**6 + 2*x**5 + 3*x**4 + 4*x**3 + 3*x**2 + 2*x + 1), x) == \ + 2*x/(x**2 + 1) + 3*atan(x) - 1/(x**2 + 1) - 3/(x + 1) + assert manualintegrate(sqrt(2*x + 3) / (x + 1), x) == 2*sqrt(2*x + 3) - log(sqrt(2*x + 3) + 1) + log(sqrt(2*x + 3) - 1) + assert manualintegrate(sqrt(2*x + 3) / 2 * x, x) == (2*x + 3)**(5/2)/20 - (2*x + 3)**(3/2)/4 + assert manualintegrate(x**Rational(3,2) * log(x), x) == 2*x**Rational(5,2)*log(x)/5 - 4*x**Rational(5/2)/25 + assert manualintegrate(x**(-3) * log(x), x) == -log(x)/(2*x**2) - 1/(4*x**2) + assert manualintegrate(log(y)/(y**2*(1 - 1/y)), y) == (-log(y) + log(y - 1))*log(y) + log(y)**2/2 - Integral(log(y - 1)/y, y) def test_constant_independent_of_symbol(): assert manualintegrate(Integral(y, (x, 1, 2)), x) == x*Integral(y, (x, 1, 2)) diff --git a/sympy/integrals/tests/test_prde.py b/sympy/integrals/tests/test_prde.py index b4ba49f756..dd1821acd3 100644 --- a/sympy/integrals/tests/test_prde.py +++ b/sympy/integrals/tests/test_prde.py @@ -221,8 +221,10 @@ def test_parametric_log_deriv(): def test_issue_10798(): - from sympy import integrate, pi, I, log, polylog, exp_polar + from sympy import integrate, pi, I, log, polylog, exp_polar, Piecewise, meijerg, Abs from sympy.abc import x, y assert integrate(1/(1-(x*y)**2), (x, 0, 1), y) == \ - I*pi*log(y)/2 + polylog(2, exp_polar(I*pi)/y)/2 - \ - polylog(2, exp_polar(2*I*pi)/y)/2 + -Piecewise((I*pi*log(y) - polylog(2, y), Abs(y) < 1), (-I*pi*log(1/y) - polylog(2, y), Abs(1/y) < 1), \ + (-I*pi*meijerg(((), (1, 1)), ((0, 0), ()), y) + I*pi*meijerg(((1, 1), ()), ((), (0, 0)), y) - polylog(2, y), True))/2 \ + - log(y)*log(1 - 1/y)/2 + log(y)*log(1 + 1/y)/2 + log(y)*log(y - 1)/2 \ + - log(y)*log(y + 1)/2 + I*pi*log(y)/2 - polylog(2, y*exp_polar(I*pi))/2
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "mpmath>=0.19", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 importlib-metadata==4.8.3 iniconfig==1.1.1 mpmath==1.2.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 -e git+https://github.com/sympy/sympy.git@ef47677483b2f29d0b8e6a0eb45de72b2e34477d#egg=sympy tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: sympy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - mpmath=1.2.1=py36h06a4308_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/sympy
[ "sympy/integrals/tests/test_manual.py::test_manualintegrate_parts", "sympy/integrals/tests/test_manual.py::test_manualintegrate_inversetrig", "sympy/integrals/tests/test_manual.py::test_manualintegrate_rational", "sympy/integrals/tests/test_manual.py::test_issue_6746", "sympy/integrals/tests/test_manual.py::test_issue_9462", "sympy/integrals/tests/test_manual.py::test_issue_10847", "sympy/integrals/tests/test_prde.py::test_issue_10798" ]
[]
[ "sympy/integrals/tests/test_manual.py::test_find_substitutions", "sympy/integrals/tests/test_manual.py::test_manualintegrate_polynomials", "sympy/integrals/tests/test_manual.py::test_manualintegrate_exponentials", "sympy/integrals/tests/test_manual.py::test_manualintegrate_trigonometry", "sympy/integrals/tests/test_manual.py::test_manualintegrate_trigpowers", "sympy/integrals/tests/test_manual.py::test_manualintegrate_trig_substitution", "sympy/integrals/tests/test_manual.py::test_manualintegrate_derivative", "sympy/integrals/tests/test_manual.py::test_manualintegrate_Heaviside", "sympy/integrals/tests/test_manual.py::test_issue_6799", "sympy/integrals/tests/test_manual.py::test_issue_3796", "sympy/integrals/tests/test_manual.py::test_manual_true", "sympy/integrals/tests/test_manual.py::test_issue_2850", "sympy/integrals/tests/test_manual.py::test_constant_independent_of_symbol", "sympy/integrals/tests/test_prde.py::test_prde_normal_denom", "sympy/integrals/tests/test_prde.py::test_prde_special_denom", "sympy/integrals/tests/test_prde.py::test_prde_linear_constraints", "sympy/integrals/tests/test_prde.py::test_constant_system", "sympy/integrals/tests/test_prde.py::test_prde_spde", "sympy/integrals/tests/test_prde.py::test_prde_no_cancel", "sympy/integrals/tests/test_prde.py::test_limited_integrate_reduce", "sympy/integrals/tests/test_prde.py::test_limited_integrate", "sympy/integrals/tests/test_prde.py::test_is_log_deriv_k_t_radical", "sympy/integrals/tests/test_prde.py::test_is_deriv_k", "sympy/integrals/tests/test_prde.py::test_is_log_deriv_k_t_radical_in_field", "sympy/integrals/tests/test_prde.py::test_parametric_log_deriv" ]
[]
BSD
522
imageio__imageio-150
8f0efc08ae98db69c02dc2820e4e76985cf0e60d
2016-05-06 23:57:09
0a390e31561cf06c495c622626319e9ffdacc007
diff --git a/imageio/core/__init__.py b/imageio/core/__init__.py index 0347ec7..b5cedf0 100644 --- a/imageio/core/__init__.py +++ b/imageio/core/__init__.py @@ -6,7 +6,7 @@ (everything but the plugins). """ -from .util import Image, Dict, asarray, image_as_uint8, urlopen # noqa +from .util import Image, Dict, asarray, image_as_uint, urlopen # noqa from .util import BaseProgressIndicator, StdoutProgressIndicator # noqa from .util import string_types, text_type, binary_type, IS_PYPY # noqa from .util import get_platform, appdata_dir, resource_dirs, has_module # noqa diff --git a/imageio/core/util.py b/imageio/core/util.py index 12463c2..70d0b99 100644 --- a/imageio/core/util.py +++ b/imageio/core/util.py @@ -13,6 +13,7 @@ import os import sys import time import struct +from warnings import warn import numpy as np @@ -46,39 +47,71 @@ def urlopen(*args, **kwargs): return urlopen(*args, **kwargs) -def image_as_uint8(im): - """ Convert the given image to uint8 - - If the dtype is already uint8, it is returned as-is. If the image - is float, and all values are between 0 and 1, the values are - multiplied by 255. In all other situations, the values are scaled - such that the minimum value becomes 0 and the maximum value becomes - 255. +def image_as_uint(im, bitdepth=None): + """ Convert the given image to uint (default: uint8) + + If the dtype already matches the desired format, it is returned + as-is. If the image is float, and all values are between 0 and 1, + the values are multiplied by np.power(2.0, bitdepth). In all other + situations, the values are scaled such that the minimum value + becomes 0 and the maximum value becomes np.power(2.0, bitdepth)-1 + (255 for 8-bit and 65535 for 16-bit). """ + if not bitdepth: + bitdepth = 8 if not isinstance(im, np.ndarray): - raise ValueError('image must be a numpy array') + raise ValueError('Image must be a numpy array') + if bitdepth == 8: + out_type = np.uint8 + elif bitdepth == 16: + out_type = np.uint16 + else: + raise ValueError('Bitdepth must be either 8 or 16') dtype_str = str(im.dtype) - # Already uint8? - if dtype_str == 'uint8': + if ((im.dtype == np.uint8 and bitdepth == 8) or + (im.dtype == np.uint16 and bitdepth == 16)): + # Already the correct format? Return as-is return im - # Handle float - mi, ma = np.nanmin(im), np.nanmax(im) - if dtype_str.startswith('float'): - if mi >= 0 and ma <= 1: - mi, ma = 0, 1 - # Now make float copy before we scale - im = im.astype('float32') - # Scale the values between 0 and 255 - if np.isfinite(mi) and np.isfinite(ma): - if mi: - im -= mi - if ma != 255: - im *= 255.0 / (ma - mi) - assert np.nanmax(im) < 256 - return im.astype(np.uint8) + if (dtype_str.startswith('float') and + np.nanmin(im) >= 0 and np.nanmax(im) <= 1): + warn('Lossy conversion from {0} to {1}, range [0, 1]'.format( + dtype_str, out_type.__name__)) + im = im.astype(np.float64) * (np.power(2.0, bitdepth)-1) + elif im.dtype == np.uint16 and bitdepth == 8: + warn('Lossy conversion from uint16 to uint8, ' + 'loosing 8 bits of resolution') + im = np.right_shift(im, 8) + elif im.dtype == np.uint32: + warn('Lossy conversion from uint32 to {0}, ' + 'loosing {1} bits of resolution'.format(out_type.__name__, + 32-bitdepth)) + im = np.right_shift(im, 32-bitdepth) + elif im.dtype == np.uint64: + warn('Lossy conversion from uint64 to {0}, ' + 'loosing {1} bits of resolution'.format(out_type.__name__, + 64-bitdepth)) + im = np.right_shift(im, 64-bitdepth) + else: + mi = np.nanmin(im) + ma = np.nanmax(im) + if not np.isfinite(mi): + raise ValueError('Minimum image value is not finite') + if not np.isfinite(ma): + raise ValueError('Maximum image value is not finite') + if ma == mi: + raise ValueError('Max value == min value, ambiguous given dtype') + warn('Conversion from {0} to {1}, ' + 'range [{2}, {3}]'.format(dtype_str, out_type.__name__, mi, ma)) + # Now make float copy before we scale + im = im.astype('float64') + # Scale the values between 0 and 1 then multiply by the max value + im = (im - mi) / (ma - mi) * (np.power(2.0, bitdepth)-1) + assert np.nanmin(im) >= 0 + assert np.nanmax(im) < np.power(2.0, bitdepth) + return im.astype(out_type) -# currently not used ... the only use it to easly provide the global meta info +# currently not used ... the only use it to easily provide the global meta info class ImageList(list): def __init__(self, meta=None): list.__init__(self) diff --git a/imageio/plugins/_freeimage.py b/imageio/plugins/_freeimage.py index b6541c7..90c9310 100644 --- a/imageio/plugins/_freeimage.py +++ b/imageio/plugins/_freeimage.py @@ -559,16 +559,15 @@ class Freeimage(object): # Test if ok if ftype == -1: - raise ValueError('Cannot determine format of file "%s"' % + raise ValueError('Cannot determine format of file "%s"' % filename) elif mode == 'w' and not lib.FreeImage_FIFSupportsWriting(ftype): - raise ValueError('Cannot write the format of file "%s"' % + raise ValueError('Cannot write the format of file "%s"' % filename) elif mode == 'r' and not lib.FreeImage_FIFSupportsReading(ftype): - raise ValueError('Cannot read the format of file "%s"' % + raise ValueError('Cannot read the format of file "%s"' % filename) - else: - return ftype + return ftype def create_bitmap(self, filename, ftype, flags=0): """ create_bitmap(filename, ftype, flags=0) @@ -796,8 +795,7 @@ class FIBitmap(FIBaseBitmap): if not bitmap: # pragma: no cover raise RuntimeError('Could not allocate bitmap for storage: %s' % self._fi._get_error_message()) - else: - self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap)) + self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap)) def load_from_filename(self, filename=None): if filename is None: @@ -814,8 +812,7 @@ class FIBitmap(FIBaseBitmap): raise ValueError('Could not load bitmap "%s": %s' % (self._filename, self._fi._get_error_message())) - else: - self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap)) + self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap)) # def load_from_bytes(self, bytes): # with self._fi as lib: @@ -1144,12 +1141,12 @@ class FIBitmap(FIBaseBitmap): raise ValueError('Could not quantize bitmap "%s": %s' % (self._filename, self._fi._get_error_message())) - else: - new = FIBitmap(self._fi, self._filename, self._ftype, - self._flags) - new._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap)) - new._fi_type = self._fi_type - return new + + new = FIBitmap(self._fi, self._filename, self._ftype, + self._flags) + new._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap)) + new._fi_type = self._fi_type + return new # def convert_to_32bit(self): # """ Convert to 32bit image. @@ -1201,9 +1198,8 @@ class FIMultipageBitmap(FIBaseBitmap): err = self._fi._get_error_message() raise ValueError('Could not open file "%s" as multi-image: %s' % (self._filename, err)) - else: - self._set_bitmap(multibitmap, - (lib.FreeImage_CloseMultiBitmap, multibitmap)) + self._set_bitmap(multibitmap, + (lib.FreeImage_CloseMultiBitmap, multibitmap)) # def load_from_bytes(self, bytes): # with self._fi as lib: @@ -1248,9 +1244,8 @@ class FIMultipageBitmap(FIBaseBitmap): msg = ('Could not open file "%s" for writing multi-image: %s' % (self._filename, self._fi._get_error_message())) raise ValueError(msg) - else: - self._set_bitmap(multibitmap, - (lib.FreeImage_CloseMultiBitmap, multibitmap)) + self._set_bitmap(multibitmap, + (lib.FreeImage_CloseMultiBitmap, multibitmap)) def __len__(self): with self._fi as lib: diff --git a/imageio/plugins/ffmpeg.py b/imageio/plugins/ffmpeg.py index 8356c5c..0e08670 100644 --- a/imageio/plugins/ffmpeg.py +++ b/imageio/plugins/ffmpeg.py @@ -25,7 +25,7 @@ import numpy as np from .. import formats from ..core import (Format, get_remote_file, string_types, read_n_bytes, - image_as_uint8, get_platform, InternetNotAllowedError) + image_as_uint, get_platform, InternetNotAllowedError) FNAME_PER_PLATFORM = { 'osx32': 'ffmpeg.osx', @@ -575,7 +575,7 @@ class FfmpegFormat(Format): depth = 1 if im.ndim == 2 else im.shape[2] # Ensure that image is in uint8 - im = image_as_uint8(im) + im = image_as_uint(im, bitdepth=8) # Set size and initialize if not initialized yet if self._size is None: diff --git a/imageio/plugins/freeimage.py b/imageio/plugins/freeimage.py index 818ba39..af0b242 100644 --- a/imageio/plugins/freeimage.py +++ b/imageio/plugins/freeimage.py @@ -11,9 +11,8 @@ from __future__ import absolute_import, print_function, division import numpy as np - from .. import formats -from ..core import Format, image_as_uint8 +from ..core import Format, image_as_uint from ._freeimage import fi, IO_FLAGS, FNAME_PER_PLATFORM # noqa @@ -165,7 +164,7 @@ class FreeimageBmpFormat(FreeimageFormat): return FreeimageFormat.Writer._open(self, flags) def _append_data(self, im, meta): - im = image_as_uint8(im) + im = image_as_uint(im, bitdepth=8) return FreeimageFormat.Writer._append_data(self, im, meta) @@ -222,7 +221,10 @@ class FreeimagePngFormat(FreeimageFormat): return FreeimageFormat.Writer._open(self, flags) def _append_data(self, im, meta): - im = image_as_uint8(im) + if str(im.dtype) == 'uint16': + im = image_as_uint(im, bitdepth=16) + else: + im = image_as_uint(im, bitdepth=8) FreeimageFormat.Writer._append_data(self, im, meta) # Quantize? q = int(self.request.kwargs.get('quantize', False)) @@ -335,7 +337,7 @@ class FreeimageJpegFormat(FreeimageFormat): def _append_data(self, im, meta): if im.ndim == 3 and im.shape[-1] == 4: raise IOError('JPEG does not support alpha channel.') - im = image_as_uint8(im) + im = image_as_uint(im, bitdepth=8) return FreeimageFormat.Writer._append_data(self, im, meta) diff --git a/imageio/plugins/freeimagemulti.py b/imageio/plugins/freeimagemulti.py index 1d0fd1f..1e7b6e7 100644 --- a/imageio/plugins/freeimagemulti.py +++ b/imageio/plugins/freeimagemulti.py @@ -10,7 +10,7 @@ from __future__ import absolute_import, print_function, division import numpy as np from .. import formats -from ..core import Format, image_as_uint8 +from ..core import Format, image_as_uint from ._freeimage import fi, IO_FLAGS from .freeimage import FreeimageFormat @@ -73,7 +73,7 @@ class FreeimageMulti(FreeimageFormat): # Prepare data if im.ndim == 3 and im.shape[-1] == 1: im = im[:, :, 0] - im = image_as_uint8(im) + im = image_as_uint(im, bitdepth=8) # Create sub bitmap sub1 = fi.create_bitmap(self._bm._filename, self.format.fif) # Let subclass add data to bitmap, optionally return new diff --git a/imageio/plugins/swf.py b/imageio/plugins/swf.py index df7cd78..2006524 100644 --- a/imageio/plugins/swf.py +++ b/imageio/plugins/swf.py @@ -14,7 +14,7 @@ from io import BytesIO import numpy as np from .. import formats -from ..core import Format, read_n_bytes, image_as_uint8 +from ..core import Format, read_n_bytes, image_as_uint _swf = None # lazily loaded in lib() @@ -301,7 +301,7 @@ class SWFFormat(Format): # Correct shape and type if im.ndim == 3 and im.shape[-1] == 1: im = im[:, :, 0] - im = image_as_uint8(im) + im = image_as_uint(im, bitdepth=8) # Get frame size wh = im.shape[1], im.shape[0] # Write header on first frame
Support writing 16-bit color channels for PNG I'm trying to transition away from MATLAB and imageio has been incredibly helpful. However, I need to work with 64-bit PNGs (16-bit color channels and 16-bit alpha channel) and although it looks like reading 16-bit channels is supported, writing is not supported. I created some 64-bit pngs in MATLAB using the following code: img_out = zeros(256, 256, 3, 'uint16'); img_alpha = zeros(256, 256, 'uint16'); color_grad = uint16(reshape(0:2^16-1, 256, [])); img_out(:, :, 1) = color_grad; img_out(:, :, 2) = rot90(color_grad, 1); img_out(:, :, 3) = rot90(color_grad, 2); img_out_alpha = rot90(color_grad, 3); fprintf('Write unique values: R=%u, G=%u, B=%u, A=%u\n', ... length(unique(img_out(:, :, 1))), ... length(unique(img_out(:, :, 2))), ... length(unique(img_out(:, :, 3))), ... length(unique(img_out_alpha))) imwrite(img_out, '64bit_MATLAB.png', 'Alpha', img_out_alpha, 'BitDepth', 16) [img_in, ~, img_in_alpha] = imread('64bit_MATLAB.png'); fprintf('MATLAB PNG unique values: R=%u, G=%u, B=%u, A=%u\n', ... length(unique(img_in(:, :, 1))), ... length(unique(img_in(:, :, 2))), ... length(unique(img_in(:, :, 3))), ... length(unique(img_in_alpha))) This gives me the following output: > Write unique values: R=65536, G=65536, B=65536, A=65536 > MATLAB PNG unique values: R=65536, G=65536, B=65536, A=65536 If I try the same with imageio in Python: import imageio import numpy as np img_out = np.zeros((256, 256, 4), dtype=np.uint16) color_grad = np.reshape(np.arange(2**16), (256,-1)) img_out[:, :, 0] = color_grad img_out[:, :, 1] = np.rot90(color_grad, 1) img_out[:, :, 2] = np.rot90(color_grad, 2) img_out[:, :, 3] = np.rot90(color_grad, 3) print('Write unique values: R={}, G={}, B={}, A={}'.format( len(set(img_out[:, :, 0].flatten().tolist())), len(set(img_out[:, :, 1].flatten().tolist())), len(set(img_out[:, :, 2].flatten().tolist())), len(set(img_out[:, :, 3].flatten().tolist())))) imageio.imwrite('64bit_imageio.png', img_out) img_in = imageio.imread('64bit_imageio.png') print('imageio PNG unique values: R={}, G={}, B={}, A={}'.format( len(set(img_in[:, :, 0].flatten().tolist())), len(set(img_in[:, :, 1].flatten().tolist())), len(set(img_in[:, :, 2].flatten().tolist())), len(set(img_in[:, :, 3].flatten().tolist())))) I get the following: > Write unique values: R=65536, G=65536, B=65536, A=65536 > imageio PNG unique values: R=256, G=256, B=256, A=256 To confirm, imageio is able to read the 64-bit PNG: img_in = imageio.imread('64bit_MATLAB.png') print('MATLAB PNG unique values: R={}, G={}, B={}, A={}'.format( len(set(img_in[:, :, 0].flatten().tolist())), len(set(img_in[:, :, 1].flatten().tolist())), len(set(img_in[:, :, 2].flatten().tolist())), len(set(img_in[:, :, 3].flatten().tolist())))) > MATLAB PNG unique values: R=65536, G=65536, B=65536, A=65536 Any idea how difficult this would be to implement?
imageio/imageio
diff --git a/tests/test_core.py b/tests/test_core.py index 1f35e77..8425930 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -738,34 +738,65 @@ def test_util_progres_bar(sleep=0): return -def test_util_image_as_uint8(): - - raises(ValueError, core.image_as_uint8, 4) - raises(ValueError, core.image_as_uint8, "not an image") - - res = core.image_as_uint8(np.array([0, 1], 'uint8')) - assert res[0] == 0 and res[1] == 1 - res = core.image_as_uint8(np.array([4, 255], 'uint8')) - assert res[0] == 4 and res[1] == 255 - - res = core.image_as_uint8(np.array([0, 1], 'int8')) - assert res[0] == 0 and res[1] == 255 - res = core.image_as_uint8(np.array([-4, 100], 'int8')) - assert res[0] == 0 and res[1] == 255 - - res = core.image_as_uint8(np.array([0, 1], 'int16')) - assert res[0] == 0 and res[1] == 255 - res = core.image_as_uint8(np.array([-4, 100], 'int16')) - assert res[0] == 0 and res[1] == 255 - res = core.image_as_uint8(np.array([-1000, 8000], 'int16')) - assert res[0] == 0 and res[1] == 255 - - res = core.image_as_uint8(np.array([0, 1], 'float32')) - assert res[0] == 0 and res[1] == 255 - res = core.image_as_uint8(np.array([0.099, 0.785], 'float32')) - assert res[0] == 25 and res[1] == 200 - res = core.image_as_uint8(np.array([4, 200], 'float32')) - assert res[0] == 0 and res[1] == 255 +def test_util_image_as_uint(): + ''' Tests the various type conversions when writing to uint''' + raises(ValueError, core.image_as_uint, 4) + raises(ValueError, core.image_as_uint, "not an image") + raises(ValueError, core.image_as_uint, np.array([0, 1]), bitdepth=13) + raises(ValueError, core.image_as_uint, np.array([2.0, 2.0], 'float32')) + raises(ValueError, core.image_as_uint, np.array([0.0, np.inf], 'float32')) + raises(ValueError, core.image_as_uint, np.array([-np.inf, 0.0], 'float32')) + + test_arrays = ( # (input, output bitdepth, expected output) + # No bitdepth specified, assumed to be 8-bit + (np.array([0, 2 ** 8 - 1], 'uint8'), None, np.uint8([0, 255])), + (np.array([0, 2 ** 16 - 1], 'uint16'), None, np.uint8([0, 255])), + (np.array([0, 2 ** 32 - 1], 'uint32'), None, np.uint8([0, 255])), + (np.array([0, 2 ** 64 - 1], 'uint64'), None, np.uint8([0, 255])), + (np.array([-2, 2], 'int8'), None, np.uint8([0, 255])), + (np.array([-2, 2], 'int16'), None, np.uint8([0, 255])), + (np.array([-2, 2], 'int32'), None, np.uint8([0, 255])), + (np.array([-2, 2], 'int64'), None, np.uint8([0, 255])), + (np.array([0, 1], 'float16'), None, np.uint8([0, 255])), + (np.array([0, 1], 'float32'), None, np.uint8([0, 255])), + (np.array([0, 1], 'float64'), None, np.uint8([0, 255])), + (np.array([-1.0, 1.0], 'float16'), None, np.uint8([0, 255])), + (np.array([-1.0, 1.0], 'float32'), None, np.uint8([0, 255])), + (np.array([-1.0, 1.0], 'float64'), None, np.uint8([0, 255])), + # 8-bit output + (np.array([0, 2 ** 8 - 1], 'uint8'), 8, np.uint8([0, 255])), + (np.array([0, 2 ** 16 - 1], 'uint16'), 8, np.uint8([0, 255])), + (np.array([0, 2 ** 32 - 1], 'uint32'), 8, np.uint8([0, 255])), + (np.array([0, 2 ** 64 - 1], 'uint64'), 8, np.uint8([0, 255])), + (np.array([-2, 2], 'int8'), 8, np.uint8([0, 255])), + (np.array([-2, 2], 'int16'), 8, np.uint8([0, 255])), + (np.array([-2, 2], 'int32'), 8, np.uint8([0, 255])), + (np.array([-2, 2], 'int64'), 8, np.uint8([0, 255])), + (np.array([0, 1], 'float16'), 8, np.uint8([0, 255])), + (np.array([0, 1], 'float32'), 8, np.uint8([0, 255])), + (np.array([0, 1], 'float64'), 8, np.uint8([0, 255])), + (np.array([-1.0, 1.0], 'float16'), 8, np.uint8([0, 255])), + (np.array([-1.0, 1.0], 'float32'), 8, np.uint8([0, 255])), + (np.array([-1.0, 1.0], 'float64'), 8, np.uint8([0, 255])), + # 16-bit output + (np.array([0, 2 ** 8 - 1], 'uint8'), 16, np.uint16([0, 65535])), + (np.array([0, 2 ** 16 - 1], 'uint16'), 16, np.uint16([0, 65535])), + (np.array([0, 2 ** 32 - 1], 'uint32'), 16, np.uint16([0, 65535])), + (np.array([0, 2 ** 64 - 1], 'uint64'), 16, np.uint16([0, 65535])), + (np.array([-2, 2], 'int8'), 16, np.uint16([0, 65535])), + (np.array([-2, 2], 'int16'), 16, np.uint16([0, 65535])), + (np.array([-2, 2], 'int32'), 16, np.uint16([0, 65535])), + (np.array([-2, 2], 'int64'), 16, np.uint16([0, 65535])), + (np.array([0, 1], 'float16'), 16, np.uint16([0, 65535])), + (np.array([0, 1], 'float32'), 16, np.uint16([0, 65535])), + (np.array([0, 1], 'float64'), 16, np.uint16([0, 65535])), + (np.array([-1.0, 1.0], 'float16'), 16, np.uint16([0, 65535])), + (np.array([-1.0, 1.0], 'float32'), 16, np.uint16([0, 65535])), + (np.array([-1.0, 1.0], 'float64'), 16, np.uint16([0, 65535])),) + + for tup in test_arrays: + res = core.image_as_uint(tup[0], bitdepth=tup[1]) + assert res[0] == tup[2][0] and res[1] == tup[2][1] def test_util_has_has_module(): diff --git a/tests/test_freeimage.py b/tests/test_freeimage.py index 6a75fb5..1b5ab83 100644 --- a/tests/test_freeimage.py +++ b/tests/test_freeimage.py @@ -37,7 +37,7 @@ im4[20:, :, 3] = 120 fnamebase = os.path.join(test_dir, 'test') -def get_ref_im(colors, crop, float): +def get_ref_im(colors, crop, isfloat): """ Get reference image with * colors: 0, 1, 3, 4 * cropping: 0-> none, 1-> crop, 2-> crop with non-contiguous data @@ -45,9 +45,9 @@ def get_ref_im(colors, crop, float): """ assert colors in (0, 1, 3, 4) assert crop in (0, 1, 2) - assert float in (False, True) + assert isfloat in (False, True) rim = [im0, im1, None, im3, im4][colors] - if float: + if isfloat: rim = rim.astype(np.float32) / 255.0 if crop == 1: rim = rim[:-1, :-1].copy() @@ -144,27 +144,27 @@ def test_freeimage_lib(): def test_png(): - for float in (False, True): + for isfloat in (False, True): for crop in (0, 1, 2): for colors in (0, 1, 3, 4): - fname = fnamebase + '%i.%i.%i.png' % (float, crop, colors) - rim = get_ref_im(colors, crop, float) + fname = fnamebase+'%i.%i.%i.png' % (isfloat, crop, colors) + rim = get_ref_im(colors, crop, isfloat) imageio.imsave(fname, rim) im = imageio.imread(fname) - mul = 255 if float else 1 + mul = 255 if isfloat else 1 assert_close(rim * mul, im, 0.1) # lossless # Run exact same test, but now in pypy backup mode try: imageio.plugins._freeimage.TEST_NUMPY_NO_STRIDES = True - for float in (False, True): + for isfloat in (False, True): for crop in (0, 1, 2): for colors in (0, 1, 3, 4): - fname = fnamebase + '%i.%i.%i.png' % (float, crop, colors) - rim = get_ref_im(colors, crop, float) + fname = fnamebase+'%i.%i.%i.png' % (isfloat, crop, colors) + rim = get_ref_im(colors, crop, isfloat) imageio.imsave(fname, rim) im = imageio.imread(fname) - mul = 255 if float else 1 + mul = 255 if isfloat else 1 assert_close(rim * mul, im, 0.1) # lossless finally: imageio.plugins._freeimage.TEST_NUMPY_NO_STRIDES = False @@ -240,14 +240,14 @@ def test_png_dtypes(): def test_jpg(): - for float in (False, True): + for isfloat in (False, True): for crop in (0, 1, 2): for colors in (0, 1, 3): - fname = fnamebase + '%i.%i.%i.jpg' % (float, crop, colors) - rim = get_ref_im(colors, crop, float) + fname = fnamebase + '%i.%i.%i.jpg' % (isfloat, crop, colors) + rim = get_ref_im(colors, crop, isfloat) imageio.imsave(fname, rim) im = imageio.imread(fname) - mul = 255 if float else 1 + mul = 255 if isfloat else 1 assert_close(rim * mul, im, 1.1) # lossy # No alpha in JPEG @@ -303,14 +303,14 @@ def test_jpg_more(): def test_bmp(): - for float in (False, True): + for isfloat in (False, True): for crop in (0, 1, 2): for colors in (0, 1, 3, 4): - fname = fnamebase + '%i.%i.%i.bmp' % (float, crop, colors) - rim = get_ref_im(colors, crop, float) + fname = fnamebase + '%i.%i.%i.bmp' % (isfloat, crop, colors) + rim = get_ref_im(colors, crop, isfloat) imageio.imsave(fname, rim) im = imageio.imread(fname) - mul = 255 if float else 1 + mul = 255 if isfloat else 1 assert_close(rim * mul, im, 0.1) # lossless # Compression @@ -328,16 +328,16 @@ def test_bmp(): def test_gif(): # The not-animated gif - for float in (False, True): + for isfloat in (False, True): for crop in (0, 1, 2): for colors in (0, 3, 4): if colors > 1 and sys.platform.startswith('darwin'): continue # quantize fails, see also png - fname = fnamebase + '%i.%i.%i.gif' % (float, crop, colors) - rim = get_ref_im(colors, crop, float) + fname = fnamebase + '%i.%i.%i.gif' % (isfloat, crop, colors) + rim = get_ref_im(colors, crop, isfloat) imageio.imsave(fname, rim) im = imageio.imread(fname) - mul = 255 if float else 1 + mul = 255 if isfloat else 1 if colors in (0, 1): im = im[:, :, 0] else: @@ -364,10 +364,10 @@ def test_animated_gif(): ims.append(im) # Store - animated GIF always poops out RGB - for float in (False, True): + for isfloat in (False, True): for colors in (3, 4): ims1 = ims[:] - if float: + if isfloat: ims1 = [x.astype(np.float32) / 256 for x in ims1] ims1 = [x[:, :, :colors] for x in ims1] fname = fnamebase + '.animated.%i.gif' % colors @@ -420,15 +420,15 @@ def test_ico(): if os.getenv('TRAVIS', '') == 'true' and sys.version_info >= (3, 4): skip('Freeimage ico is unstable for this Travis build') - for float in (False, True): + for isfloat in (False, True): for crop in (0, ): for colors in (1, 3, 4): - fname = fnamebase + '%i.%i.%i.ico' % (float, crop, colors) - rim = get_ref_im(colors, crop, float) + fname = fnamebase + '%i.%i.%i.ico' % (isfloat, crop, colors) + rim = get_ref_im(colors, crop, isfloat) rim = rim[:32, :32] # ico needs nice size imageio.imsave(fname, rim) im = imageio.imread(fname) - mul = 255 if float else 1 + mul = 255 if isfloat else 1 assert_close(rim * mul, im, 0.1) # lossless # Meta data diff --git a/tests/test_swf.py b/tests/test_swf.py index 9cabec2..22b2622 100644 --- a/tests/test_swf.py +++ b/tests/test_swf.py @@ -168,9 +168,12 @@ def test_types(): fname1 = get_remote_file('images/stent.swf', test_dir) fname2 = fname1[:-4] + '.out3.swf' - for dtype in [np.uint8, np.float32]: - for shape in [(100, 100), (100, 100, 1), (100, 100, 3)]: - im1 = np.empty(shape, dtype) # empty is nice for testing nan + for dtype in [np.uint8, np.uint16, np.uint32, np.uint64, + np.int8, np.int16, np.int32, np.int64, + np.float16, np.float32, np.float64]: + for shape in [(100, 1), (100, 3)]: + # Repeats an identity matrix, just for testing + im1 = np.dstack((np.identity(shape[0], dtype=dtype), )*shape[1]) imageio.mimsave(fname2, [im1], 'swf') im2 = imageio.mimread(fname2, 'swf')[0] assert im2.shape == (100, 100, 4)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 7 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy", "pip_packages": [ "pytest", "pytest-cov", "coveralls" ], "pre_install": [ "apt-get update", "apt-get install -y libfreeimage3" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 exceptiongroup==1.2.2 idna==3.10 -e git+https://github.com/imageio/imageio.git@8f0efc08ae98db69c02dc2820e4e76985cf0e60d#egg=imageio iniconfig==2.1.0 numpy @ file:///croot/numpy_and_numpy_base_1736283260865/work/dist/numpy-2.0.2-cp39-cp39-linux_x86_64.whl#sha256=3387e3e62932fa288bc18e8f445ce19e998b418a65ed2064dd40a054f976a6c7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 tomli==2.2.1 urllib3==2.3.0
name: imageio channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=openblas - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - numpy=2.0.2=py39heeff2f4_0 - numpy-base=2.0.2=py39h8a23956_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=72.1.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/imageio
[ "tests/test_core.py::test_util_image_as_uint" ]
[ "tests/test_core.py::test_findlib", "tests/test_core.py::test_util_image", "tests/test_freeimage.py::test_png", "tests/test_freeimage.py::test_animated_gif" ]
[ "tests/test_core.py::test_format", "tests/test_core.py::test_reader_and_writer", "tests/test_core.py::test_default_can_read_and_can_write", "tests/test_core.py::test_format_selection", "tests/test_core.py::test_format_manager", "tests/test_core.py::test_fetching", "tests/test_core.py::test_request", "tests/test_core.py::test_request_read_sources", "tests/test_core.py::test_request_save_sources", "tests/test_core.py::test_request_file_no_seek", "tests/test_core.py::test_util_imagelist", "tests/test_core.py::test_util_dict", "tests/test_core.py::test_util_get_platform", "tests/test_core.py::test_util_asarray", "tests/test_core.py::test_util_progres_bar", "tests/test_core.py::test_util_has_has_module", "tests/test_core.py::test_functions", "tests/test_core.py::test_example_plugin", "tests/test_freeimage.py::test_get_ref_im", "tests/test_freeimage.py::test_get_fi_lib", "tests/test_freeimage.py::test_freeimage_format", "tests/test_freeimage.py::test_freeimage_lib", "tests/test_freeimage.py::test_png_dtypes", "tests/test_freeimage.py::test_jpg", "tests/test_freeimage.py::test_jpg_more", "tests/test_freeimage.py::test_bmp", "tests/test_freeimage.py::test_gif", "tests/test_freeimage.py::test_ico", "tests/test_freeimage.py::test_mng", "tests/test_freeimage.py::test_other", "tests/test_swf.py::test_format_selection", "tests/test_swf.py::test_reading_saving", "tests/test_swf.py::test_read_from_url", "tests/test_swf.py::test_invalid", "tests/test_swf.py::test_lowlevel", "tests/test_swf.py::test_types" ]
[]
BSD 2-Clause "Simplified" License
523
Juniper__py-junos-eznc-509
ae516980deb810d9935cb62222fa7a4c522e1175
2016-05-07 11:04:54
3ca08f81e0be85394c6fa3e94675dfe03e958e28
diff --git a/lib/jnpr/junos/device.py b/lib/jnpr/junos/device.py index 3dcb71df..3438b910 100644 --- a/lib/jnpr/junos/device.py +++ b/lib/jnpr/junos/device.py @@ -496,7 +496,7 @@ class Device(object): self.connected = True self._nc_transform = self.transform - self._norm_transform = lambda: JXML.normalize_xslt.encode('UTF-8') + self._norm_transform = lambda: JXML.normalize_xslt normalize = kvargs.get('normalize', self._normalize) if normalize is True: diff --git a/lib/jnpr/junos/utils/start_shell.py b/lib/jnpr/junos/utils/start_shell.py index 61f97df4..5d735ad5 100644 --- a/lib/jnpr/junos/utils/start_shell.py +++ b/lib/jnpr/junos/utils/start_shell.py @@ -3,7 +3,7 @@ from select import select import re _JUNOS_PROMPT = '> ' -_SHELL_PROMPT = '% ' +_SHELL_PROMPT = '(%|#) ' _SELECT_WAIT = 0.1 _RECVSZ = 1024 @@ -35,8 +35,8 @@ class StartShell(object): :param str this: expected string/pattern. - :returns: resulting string of data - :rtype: str + :returns: resulting string of data in a list + :rtype: list .. warning:: need to add a timeout safeguard """ @@ -82,8 +82,8 @@ class StartShell(object): self._client = client self._chan = chan - got = self.wait_for('(%|>)') - if not got[-1].endswith(_SHELL_PROMPT): + got = self.wait_for(r'(%|>|#)') + if got[-1].endswith(_JUNOS_PROMPT): self.send('start shell') self.wait_for(_SHELL_PROMPT) @@ -116,7 +116,7 @@ class StartShell(object): rc = ''.join(self.wait_for(this)) self.last_ok = True if rc.find('0') > 0 else False - return (self.last_ok,got) + return (self.last_ok, got) # ------------------------------------------------------------------------- # CONTEXT MANAGER
Shell session does not work for root user. I'm using the below example program. ``` #!/usr/bin/env python import jnpr.junos.utils from jnpr.junos import Device from jnpr.junos.utils import * from jnpr.junos.utils.start_shell import * from jnpr.junos.utils.start_shell import StartShell DUT = Device(host='10.252.191.104', user="root", passwd = "password!") DUT.open() print "Device opened!" DUT_ss = StartShell(DUT) DUT_ss.open() print "got thru shell open." print DUT_ss.run("pwd") print DUT_ss.run("ls") ``` We never print the line "got thru shell open" because the library hangs while waiting for the "% " shell prompt to appear. I have a fix i'll be suggesting.
Juniper/py-junos-eznc
diff --git a/tests/unit/utils/test_start_shell.py b/tests/unit/utils/test_start_shell.py index b3812937..ee728b02 100644 --- a/tests/unit/utils/test_start_shell.py +++ b/tests/unit/utils/test_start_shell.py @@ -19,9 +19,17 @@ class TestStartShell(unittest.TestCase): @patch('paramiko.SSHClient') @patch('jnpr.junos.utils.start_shell.StartShell.wait_for') - def test_startshell_open(self, mock_connect, mock_wait): + def test_startshell_open_with_shell_term(self, mock_wait, mock_connect): + mock_wait.return_value = ["user # "] self.shell.open() - mock_connect.assert_called_with('(%|>)') + mock_wait.assert_called_with('(%|>|#)') + + @patch('paramiko.SSHClient') + @patch('jnpr.junos.utils.start_shell.StartShell.wait_for') + def test_startshell_open_with_junos_term(self, mock_wait, mock_connect): + mock_wait.return_value = ["user > "] + self.shell.open() + mock_wait.assert_called_with('(%|#) ') @patch('paramiko.SSHClient') def test_startshell_close(self, mock_connect):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 2 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "pep8", "pyflakes", "coveralls", "ntc_templates", "cryptography==3.2", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
bcrypt==4.2.1 certifi @ file:///croot/certifi_1671487769961/work/certifi cffi==1.15.1 charset-normalizer==3.4.1 coverage==6.5.0 coveralls==3.3.1 cryptography==44.0.2 docopt==0.6.2 exceptiongroup==1.2.2 future==1.0.0 idna==3.10 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 -e git+https://github.com/Juniper/py-junos-eznc.git@ae516980deb810d9935cb62222fa7a4c522e1175#egg=junos_eznc lxml==5.3.1 MarkupSafe==2.1.5 mock==5.2.0 ncclient==0.6.19 netaddr==1.3.0 nose==1.3.7 ntc_templates==4.0.1 packaging==24.0 paramiko==3.5.1 pep8==1.7.1 pluggy==1.2.0 pycparser==2.21 pyflakes==3.0.1 PyNaCl==1.5.0 pytest==7.4.4 PyYAML==6.0.1 requests==2.31.0 scp==0.15.0 six==1.17.0 textfsm==1.1.3 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: py-junos-eznc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bcrypt==4.2.1 - cffi==1.15.1 - charset-normalizer==3.4.1 - coverage==6.5.0 - coveralls==3.3.1 - cryptography==44.0.2 - docopt==0.6.2 - exceptiongroup==1.2.2 - future==1.0.0 - idna==3.10 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - lxml==5.3.1 - markupsafe==2.1.5 - mock==5.2.0 - ncclient==0.6.19 - netaddr==1.3.0 - nose==1.3.7 - ntc-templates==4.0.1 - packaging==24.0 - paramiko==3.5.1 - pep8==1.7.1 - pluggy==1.2.0 - pycparser==2.21 - pyflakes==3.0.1 - pynacl==1.5.0 - pytest==7.4.4 - pyyaml==6.0.1 - requests==2.31.0 - scp==0.15.0 - six==1.17.0 - textfsm==1.1.3 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/py-junos-eznc
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_open_with_junos_term", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_open_with_shell_term" ]
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_context" ]
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_close", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_run", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_wait_for", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_wait_for_regex" ]
[]
Apache License 2.0
524
terryyin__lizard-120
bdcc784bd22d8e48db22884dfeb42647ffb67fbf
2016-05-08 06:41:31
bdcc784bd22d8e48db22884dfeb42647ffb67fbf
rakhimov: Hi @terryyin, do not yet merge this PR. I sense there are bugs in implementation of C++ ``current_nesting_level``. The initial code works with Python, for which the nesting level metric is producing what is expected. However, the C++ ``current_nesting_level`` doesn't seem to be fully conformant. Your suggestions are welcome.
diff --git a/lizard.py b/lizard.py index 4d21e8a..cac8020 100755 --- a/lizard.py +++ b/lizard.py @@ -316,7 +316,7 @@ class NestingStack(object): self.pending_function = None self.nesting_stack.append(Namespace(token)) - def start_new_funciton_nesting(self, function): + def start_new_function_nesting(self, function): self.pending_function = function def _create_nesting(self): @@ -386,7 +386,7 @@ class FileInfoBuilder(object): self.fileinfo.filename, self.current_line) self.current_function.top_nesting_level = self.current_nesting_level - self.start_new_funciton_nesting(self.current_function) + self.start_new_function_nesting(self.current_function) def add_condition(self, inc=1): self.current_function.cyclomatic_complexity += inc diff --git a/lizard_ext/lizardns.py b/lizard_ext/lizardns.py index e057e73..4ee09bf 100644 --- a/lizard_ext/lizardns.py +++ b/lizard_ext/lizardns.py @@ -1,13 +1,16 @@ """ This extension counts nested control structures within a function. -The extension is implemented with C++ in mind. + +The extension is implemented with C++ and Python in mind, +but it is expected to work with other languages supported by Lizard +with its language reader implementing 'nesting_level' metric for tokens. The code borrows heavily from implementation of Nesting Depth extension originally written by Mehrdad Meh and Terry Yin. """ -from lizard import FileInfoBuilder, FunctionInfo -from lizard_ext.lizardnd import patch, patch_append_method +from lizard import FunctionInfo +from lizard_ext.lizardnd import patch_append_method DEFAULT_NS_THRESHOLD = 3 @@ -32,106 +35,90 @@ class LizardExtension(object): # pylint: disable=R0903 def __call__(self, tokens, reader): """The intent of the code is to detect control structures as entities. - The complexity arises from tracking of - control structures without brackets. - The termination of such control structures in C-like languages - is the next statement or control structure with a compound statement. - - Moreover, control structures with two or more tokens complicates - the proper counting, for example, 'else if'. + The implementation relies on nesting level metric for tokens + provided by language readers. + If the following contract for the nesting level metric does not hold, + this implementation of nested structure counting is invalid. - In Python with meaningful indentation, - tracking the indentation levels becomes crucial - to identify boundaries of the structures. - The following code is not designed for Python. - """ - structures = set(['if', 'else', 'foreach', 'for', 'while', 'do', - 'try', 'catch', 'switch']) + If a control structure has started its block (eg. '{'), + and its level is **less** than the next structure, + the next structure is nested. - structure_indicator = "{" - structure_end = "}" - indent_indicator = ";" - - for token in tokens: - if reader.context.is_within_structure(): - if token == "(": - reader.context.add_parentheses(1) - elif token == ")": - reader.context.add_parentheses(-1) + If a control structure has *not* started its block, + and its level is **no more** than the next structure, + the next structure is nested (compound statement). - if not reader.context.is_within_parentheses(): - if token in structures: - reader.context.add_nested_structure(token) + If a control structure level is **higher** than the next structure, + it is considered closed. - elif token == structure_indicator: - reader.context.add_brace() - - elif token == structure_end: - reader.context.pop_brace() - reader.context.pop_nested_structure() - - elif token == indent_indicator: - reader.context.pop_nested_structure() - - yield token + If a control structure has started its block, + and its level is **equal** to the next structure, + it is considered closed. - -# TODO: Some weird false positive from pylint. # pylint: disable=fixme -# pylint: disable=E1101 -class NSFileInfoAddition(FileInfoBuilder): - - def add_nested_structure(self, token): - """Conditionally adds nested structures.""" - # Handle compound else-if. - if token == "if" and self.current_function.structure_stack: - prev_token, br_state = self.current_function.structure_stack[-1] - if (prev_token == "else" and - br_state == self.current_function.brace_count): + The level of any non-structure tokens is treated + with the same logic as for the next structures + for control block **starting** and **closing** purposes. + """ + # TODO: Delegate this to language readers # pylint: disable=fixme + structures = set(['if', 'else', 'elif', 'for', 'foreach', 'while', 'do', + 'try', 'catch', 'switch', 'finally', 'except', + 'with']) + + cur_level = 0 + start_structure = [False] # Just to make it mutable. + structure_stack = [] # [(token, ns_level)] + + def add_nested_structure(token): + """Conditionally adds nested structures.""" + if structure_stack: + prev_token, ns_level = structure_stack[-1] + if cur_level == ns_level: + if (token == "if" and prev_token == "else" and + not start_structure[0]): + return # Compound 'else if' in C-like languages. + if start_structure[0]: + structure_stack.pop() + elif cur_level < ns_level: + while structure_stack and ns_level >= cur_level: + _, ns_level = structure_stack.pop() + + structure_stack.append((token, cur_level)) + start_structure[0] = False # Starts on the next level with body. + + ns_cur = len(structure_stack) + if reader.context.current_function.max_nested_structures < ns_cur: + reader.context.current_function.max_nested_structures = ns_cur + + def pop_nested_structure(): + """Conditionally pops the nested structures if levels match.""" + if not structure_stack: return - self.current_function.structure_stack.append( - (token, self.current_function.brace_count)) - - ns_cur = len(self.current_function.structure_stack) - if self.current_function.max_nested_structures < ns_cur: - self.current_function.max_nested_structures = ns_cur + _, ns_level = structure_stack[-1] - def pop_nested_structure(self): - """Conditionally pops the structure count if braces match.""" - if not self.current_function.structure_stack: - return + if cur_level > ns_level: + start_structure[0] = True - _, br_state = self.current_function.structure_stack[-1] - if br_state == self.current_function.brace_count: - self.current_function.structure_stack.pop() + elif cur_level < ns_level: + while structure_stack and ns_level >= cur_level: + _, ns_level = structure_stack.pop() + start_structure[0] = bool(structure_stack) - def add_brace(self): - self.current_function.brace_count += 1 + elif start_structure[0]: + structure_stack.pop() - def pop_brace(self): - # pylint: disable=fixme - # TODO: For some reason, brace count goes negative. - # assert self.current_function.brace_count > 0 - self.current_function.brace_count -= 1 - - def add_parentheses(self, inc): - """Dual purpose parentheses manipulator.""" - self.current_function.paren_count += inc - - def is_within_parentheses(self): - assert self.current_function.paren_count >= 0 - return self.current_function.paren_count != 0 + for token in tokens: + cur_level = reader.context.current_nesting_level + if token in structures: + add_nested_structure(token) + else: + pop_nested_structure() - def is_within_structure(self): - return bool(self.current_function.structure_stack) + yield token def _init_nested_structure_data(self, *_): self.max_nested_structures = 0 - self.brace_count = 0 - self.paren_count = 0 - self.structure_stack = [] -patch(NSFileInfoAddition, FileInfoBuilder) patch_append_method(_init_nested_structure_data, FunctionInfo, "__init__")
Detection of Deeply Nested Control Structures This metric may not apply to the whole function, but the maximum 'nestedness' (nesting for-loops, if-statements, etc.) may be an interesting metric to detect code smell. It closely relates to indentation. Got this from the Linux kernel coding style: >The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.
terryyin/lizard
diff --git a/test/testNestedStructures.py b/test/testNestedStructures.py old mode 100755 new mode 100644 index 7eee514..1a2d826 --- a/test/testNestedStructures.py +++ b/test/testNestedStructures.py @@ -1,5 +1,7 @@ import unittest -from .testHelpers import get_cpp_function_list_with_extnesion + +from .testHelpers import get_cpp_function_list_with_extnesion, \ + get_python_function_list_with_extnesion from lizard_ext.lizardns import LizardExtension as NestedStructure @@ -7,6 +9,10 @@ def process_cpp(source): return get_cpp_function_list_with_extnesion(source, NestedStructure()) +def process_python(source): + return get_python_function_list_with_extnesion(source, NestedStructure()) + + class TestCppNestedStructures(unittest.TestCase): def test_no_structures(self): @@ -209,3 +215,122 @@ class TestCppNestedStructures(unittest.TestCase): } """) self.assertEqual(3, result[0].max_nested_structures) + + +class TestPythonNestedStructures(unittest.TestCase): + + def test_no_structures(self): + result = process_python("def fun():\n pass") + self.assertEqual(0, result[0].max_nested_structures) + + def test_if_structure(self): + result = process_python("def fun():\n if a:\n return") + self.assertEqual(1, result[0].max_nested_structures) + + def test_for_structure(self): + result = process_python("def fun():\n for a in b:\n foo()") + self.assertEqual(1, result[0].max_nested_structures) + + def test_condition_in_if_structure(self): + result = process_python("def fun():\n if a and b:\n return") + self.assertEqual(1, result[0].max_nested_structures) + + def test_elif(self): + result = process_python(""" + def c(): + if a: + baz() + elif c: + foo() + """) + self.assertEqual(1, result[0].max_nested_structures) + + def test_nested_if_structures(self): + result = process_python(""" + def c(): + if a: + if b: + baz() + else: + foo() + """) + self.assertEqual(2, result[0].max_nested_structures) + + def test_equal_metric_structures(self): + result = process_python(""" + def c(): + if a: + if b: + baz() + else: + foo() + + for a in b: + if c: + bar() + """) + self.assertEqual(2, result[0].max_nested_structures) + + def test_while(self): + result = process_python(""" + def c(): + while a: + baz() + """) + self.assertEqual(1, result[0].max_nested_structures) + + def test_try_catch(self): + result = process_python(""" + def c(): + try: + f.open() + catch Exception as err: + print(err) + finally: + f.close() + """) + self.assertEqual(1, result[0].max_nested_structures) + + def test_two_functions(self): + result = process_python(""" + def c(): + try: + if a: + foo() + catch Exception as err: + print(err) + + def d(): + for a in b: + for x in y: + if i: + return j + """) + self.assertEqual(2, result[0].max_nested_structures) + self.assertEqual(3, result[1].max_nested_structures) + + def test_nested_functions(self): + result = process_python(""" + def c(): + def d(): + for a in b: + for x in y: + if i: + return j + try: + if a: + foo() + catch Exception as err: + print(err) + + """) + self.assertEqual(3, result[0].max_nested_structures) + self.assertEqual(2, result[1].max_nested_structures) + + def test_with_structure(self): + result = process_python(""" + def c(): + with open(f) as input_file: + foo(f) + """) + self.assertEqual(1, result[0].max_nested_structures)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt", "dev_requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 dill==0.3.9 exceptiongroup==1.2.2 iniconfig==2.1.0 isort==6.0.1 -e git+https://github.com/terryyin/lizard.git@bdcc784bd22d8e48db22884dfeb42647ffb67fbf#egg=lizard mccabe==0.7.0 mock==5.2.0 nose==1.3.7 packaging==24.2 pep8==1.7.1 platformdirs==4.3.7 pluggy==1.5.0 pylint==3.3.6 pytest==8.3.5 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0
name: lizard channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - dill==0.3.9 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - isort==6.0.1 - mccabe==0.7.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pep8==1.7.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pylint==3.3.6 - pytest==8.3.5 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 prefix: /opt/conda/envs/lizard
[ "test/testNestedStructures.py::TestPythonNestedStructures::test_equal_metric_structures", "test/testNestedStructures.py::TestPythonNestedStructures::test_nested_functions", "test/testNestedStructures.py::TestPythonNestedStructures::test_nested_if_structures", "test/testNestedStructures.py::TestPythonNestedStructures::test_try_catch", "test/testNestedStructures.py::TestPythonNestedStructures::test_two_functions", "test/testNestedStructures.py::TestPythonNestedStructures::test_with_structure" ]
[]
[ "test/testNestedStructures.py::TestCppNestedStructures::test_and_condition_in_if_structure", "test/testNestedStructures.py::TestCppNestedStructures::test_do", "test/testNestedStructures.py::TestCppNestedStructures::test_forever_loop", "test/testNestedStructures.py::TestCppNestedStructures::test_if_structure", "test/testNestedStructures.py::TestCppNestedStructures::test_nested_if_structures", "test/testNestedStructures.py::TestCppNestedStructures::test_nested_loop_mixed_brackets", "test/testNestedStructures.py::TestCppNestedStructures::test_no_structures", "test/testNestedStructures.py::TestCppNestedStructures::test_non_r_value_ref_in_body", "test/testNestedStructures.py::TestCppNestedStructures::test_scope", "test/testNestedStructures.py::TestCppNestedStructures::test_switch_case", "test/testNestedStructures.py::TestCppNestedStructures::test_terminator_in_parentheses", "test/testNestedStructures.py::TestCppNestedStructures::test_ternary_operator", "test/testNestedStructures.py::TestCppNestedStructures::test_try_catch", "test/testNestedStructures.py::TestCppNestedStructures::test_while", "test/testNestedStructures.py::TestPythonNestedStructures::test_condition_in_if_structure", "test/testNestedStructures.py::TestPythonNestedStructures::test_elif", "test/testNestedStructures.py::TestPythonNestedStructures::test_for_structure", "test/testNestedStructures.py::TestPythonNestedStructures::test_if_structure", "test/testNestedStructures.py::TestPythonNestedStructures::test_no_structures", "test/testNestedStructures.py::TestPythonNestedStructures::test_while" ]
[ "test/testNestedStructures.py::TestCppNestedStructures::test_else_if", "test/testNestedStructures.py::TestCppNestedStructures::test_equal_metric_structures", "test/testNestedStructures.py::TestCppNestedStructures::test_gotcha_if_else" ]
MIT License
525
sympy__sympy-11093
d15efa225684da73ca1921c0b5d3d52068eb5ecd
2016-05-09 19:08:05
8bb5814067cfa0348fb8b708848f35dba2b55ff4
smichr: ping @isuruf -- please take a look at the mods here in contrast to #11089 isuruf: > I wonder if it might be better to use Fraction as the underlying representation and then update methods like Rational.p and Rational.args to return the correct args of the Fraction Implementation of Fractions doesn't do the `gcd` hint trick introduced in #11019, therefore will be slower to use. Also, arithmetic operators would use `gcd` instead of `igcd` and therefore caching will not be used in that case. smichr: ping @isuruf - ok, have a look now. I benchmark with ``` for I in range(10**4): for J in range(10**4): g = igcd(I,j) ``` I think it is now more similar to the original `igcd` now.
diff --git a/doc/src/modules/stats.rst b/doc/src/modules/stats.rst index 7b301a4ba5..d53f8b44d1 100644 --- a/doc/src/modules/stats.rst +++ b/doc/src/modules/stats.rst @@ -64,16 +64,11 @@ Interface ^^^^^^^^^ .. autofunction:: P -.. autoclass:: Probability .. autofunction:: E -.. autoclass:: Expectation .. autofunction:: density .. autofunction:: given .. autofunction:: where .. autofunction:: variance -.. autoclass:: Variance -.. autofunction:: covariance -.. autoclass:: Covariance .. autofunction:: std .. autofunction:: sample .. autofunction:: sample_iter diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py index aeff883ef7..dde9bb8713 100644 --- a/sympy/core/numbers.py +++ b/sympy/core/numbers.py @@ -140,7 +140,7 @@ def _literal_float(f): def igcd(*args): - """Computes positive integer greatest common divisor. + """Computes nonnegative integer greatest common divisor. The algorithm is based on the well known Euclid's algorithm. To improve speed, igcd() has its own caching mechanism implemented. @@ -155,25 +155,37 @@ def igcd(*args): 5 """ - a = args[0] - for b in args[1:]: - try: - a = _gcdcache[(a, b)] - except KeyError: - a, b = as_int(a), as_int(b) - - if a and b: + if len(args) < 2: + raise TypeError( + 'igcd() takes at least 2 arguments (%s given)' % len(args)) + if 1 in args: + a = 1 + k = 0 + else: + a = abs(as_int(args[0])) + k = 1 + if a != 1: + while k < len(args): + b = args[k] + k += 1 + try: + a = _gcdcache[(a, b)] + except KeyError: + b = as_int(b) + if not b: + continue + if b == 1: + a = 1 + break if b < 0: b = -b - + t = a, b while b: a, b = b, a % b - else: - a = abs(a or b) - - _gcdcache[(a, b)] = a - if a == 1 or b == 1: - return 1 + _gcdcache[t] = _gcdcache[t[1], t[0]] = a + while k < len(args): + ok = as_int(args[k]) + k += 1 return a @@ -192,6 +204,9 @@ def ilcm(*args): 30 """ + if len(args) < 2: + raise TypeError( + 'ilcm() takes at least 2 arguments (%s given)' % len(args)) if 0 in args: return 0 a = args[0] @@ -1233,37 +1248,36 @@ def __new__(cls, p, q=None, gcd=None): return p if isinstance(p, string_types): + if p.count('/') > 1: + raise TypeError('invalid input: %s' % p) + pq = p.rsplit('/', 1) + if len(pq) == 2: + p, q = pq + fp = fractions.Fraction(p) + fq = fractions.Fraction(q) + f = fp/fq + return Rational(f.numerator, f.denominator, 1) p = p.replace(' ', '') try: - # we might have a Float - neg_pow, digits, expt = decimal.Decimal(p).as_tuple() - p = [1, -1][neg_pow]*int("".join(str(x) for x in digits)) - if expt > 0: - return Rational(p*Pow(10, expt), 1) - return Rational(p, Pow(10, -expt)) - except decimal.InvalidOperation: - f = regex.match('^([-+]?[0-9]+)/([0-9]+)$', p) - if f: - n, d = f.groups() - return Rational(int(n), int(d)) - elif p.count('/') == 1: - p, q = p.split('/') - return Rational(Rational(p), Rational(q)) - else: - pass # error will raise below - else: + p = fractions.Fraction(p) + except ValueError: + pass # error will raise below + elif isinstance(p, float): + p = fractions.Fraction(p) + + if not isinstance(p, string_types): try: if isinstance(p, fractions.Fraction): return Rational(p.numerator, p.denominator, 1) except NameError: pass # error will raise below - if isinstance(p, (float, Float)): + if isinstance(p, Float): return Rational(*float(p).as_integer_ratio()) if not isinstance(p, SYMPY_INTS + (Rational,)): raise TypeError('invalid input: %s' % p) - q = S.One + q = q or S.One gcd = 1 else: p = Rational(p) @@ -1311,49 +1325,8 @@ def limit_denominator(self, max_denominator=1000000): 311/99 """ - # Algorithm notes: For any real number x, define a *best upper - # approximation* to x to be a rational number p/q such that: - # - # (1) p/q >= x, and - # (2) if p/q > r/s >= x then s > q, for any rational r/s. - # - # Define *best lower approximation* similarly. Then it can be - # proved that a rational number is a best upper or lower - # approximation to x if, and only if, it is a convergent or - # semiconvergent of the (unique shortest) continued fraction - # associated to x. - # - # To find a best rational approximation with denominator <= M, - # we find the best upper and lower approximations with - # denominator <= M and take whichever of these is closer to x. - # In the event of a tie, the bound with smaller denominator is - # chosen. If both denominators are equal (which can happen - # only when max_denominator == 1 and self is midway between - # two integers) the lower bound---i.e., the floor of self, is - # taken. - - if max_denominator < 1: - raise ValueError("max_denominator should be at least 1") - if self.q <= max_denominator: - return self - - p0, q0, p1, q1 = 0, 1, 1, 0 - n, d = self.p, self.q - while True: - a = n//d - q2 = q0 + a*q1 - if q2 > max_denominator: - break - p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2 - n, d = d, n - a*d - - k = (max_denominator - q0)//q1 - bound1 = Rational(p0 + k*p1, q0 + k*q1) - bound2 = Rational(p1, q1) - if abs(bound2 - self) <= abs(bound1 - self): - return bound2 - else: - return bound1 + f = fractions.Fraction(self.p, self.q) + return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator)))) def __getnewargs__(self): return (self.p, self.q) diff --git a/sympy/core/power.py b/sympy/core/power.py index ac07ca460f..91835e8679 100644 --- a/sympy/core/power.py +++ b/sympy/core/power.py @@ -12,19 +12,9 @@ from .logic import fuzzy_bool, fuzzy_not from .compatibility import as_int, range from .evaluate import global_evaluate -from sympy.utilities.iterables import sift from mpmath.libmp import sqrtrem as mpmath_sqrtrem - -from math import sqrt as _sqrt - - - -def isqrt(n): - """Return the largest integer less than or equal to sqrt(n).""" - if n < 17984395633462800708566937239552: - return int(_sqrt(n)) - return integer_nthroot(int(n), 2)[0] +from sympy.utilities.iterables import sift def integer_nthroot(y, n): @@ -96,7 +86,7 @@ def integer_nthroot(y, n): while t > y: x -= 1 t = x**n - return int(x), t == y # int converts long to int if possible + return x, t == y class Pow(Expr): diff --git a/sympy/functions/elementary/miscellaneous.py b/sympy/functions/elementary/miscellaneous.py index 82cdb8b7bc..43dc9affc1 100644 --- a/sympy/functions/elementary/miscellaneous.py +++ b/sympy/functions/elementary/miscellaneous.py @@ -454,7 +454,7 @@ def _eval_derivative(self, s): return Add(*l) def evalf(self, prec=None, **options): - return self.func(*[a.evalf(prec, **options) for a in self.args]) + return self.func(*[a.evalf(prec, options) for a in self.args]) n = evalf _eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args) diff --git a/sympy/integrals/deltafunctions.py b/sympy/integrals/deltafunctions.py index fc53923b31..098179ae74 100644 --- a/sympy/integrals/deltafunctions.py +++ b/sympy/integrals/deltafunctions.py @@ -3,7 +3,6 @@ from sympy.core import Mul from sympy.functions import DiracDelta, Heaviside from sympy.core.compatibility import default_sort_key -from sympy.core.singleton import S def change_mul(node, x): @@ -41,6 +40,9 @@ def change_mul(node, x): sympy.functions.special.delta_functions.DiracDelta deltaintegrate """ + if not (node.is_Mul or node.is_Pow): + return node + new_args = [] dirac = None @@ -54,7 +56,8 @@ def change_mul(node, x): if arg.is_Pow and arg.base.func is DiracDelta: new_args.append(arg.func(arg.base, arg.exp - 1)) arg = arg.base - if dirac is None and (arg.func is DiracDelta and arg.is_simple(x)): + if dirac is None and (arg.func is DiracDelta and arg.is_simple(x) + and (len(arg.args) <= 1 or arg.args[1] == 0)): dirac = arg else: new_args.append(arg) @@ -66,7 +69,7 @@ def change_mul(node, x): elif arg.is_Pow and arg.base.func is DiracDelta: new_args.append(arg.func(arg.base.simplify(x), arg.exp)) else: - new_args.append(arg) + new_args.append(change_mul(arg, x)) if new_args != sorted_args: nnode = Mul(*new_args).expand() else: # if the node didn't change there is nothing to do @@ -157,41 +160,17 @@ def deltaintegrate(f, x): return fh else: # no expansion performed, try to extract a simple DiracDelta term - deltaterm, rest_mult = change_mul(f, x) + dg, rest_mult = change_mul(f, x) - if not deltaterm: + if not dg: if rest_mult: fh = integrate(rest_mult, x) return fh else: - deltaterm = deltaterm.simplify(x) - if deltaterm.is_Mul: # Take out any extracted factors - deltaterm, rest_mult_2 = change_mul(deltaterm, x) + dg = dg.simplify(x) + if dg.is_Mul: # Take out any extracted factors + dg, rest_mult_2 = change_mul(dg, x) rest_mult = rest_mult*rest_mult_2 - point = solve(deltaterm.args[0], x)[0] - - # Return the largest hyperreal term left after - # repeated integration by parts. For example, - # - # integrate(y*DiracDelta(x, 1),x) == y*DiracDelta(x,0), not 0 - # - # This is so Integral(y*DiracDelta(x).diff(x),x).doit() - # will return y*DiracDelta(x) instead of 0 or DiracDelta(x), - # both of which are correct everywhere the value is defined - # but give wrong answers for nested integration. - n = (0 if len(deltaterm.args)==1 else deltaterm.args[1]) - m = 0 - while n >= 0: - r = (-1)**n*rest_mult.diff(x, n).subs(x, point) - if r is S.Zero: - n -= 1 - m += 1 - else: - if m == 0: - return r*Heaviside(x - point) - else: - return r*DiracDelta(x,m-1) - # In some very weak sense, x=0 is still a singularity, - # but we hope will not be of any practial consequence. - return S.Zero + point = solve(dg.args[0], x)[0] + return (rest_mult.subs(x, point)*Heaviside(x - point)) return None diff --git a/sympy/matrices/densesolve.py b/sympy/matrices/densesolve.py index bfbfc31660..9bac3f5587 100644 --- a/sympy/matrices/densesolve.py +++ b/sympy/matrices/densesolve.py @@ -7,14 +7,10 @@ from sympy.matrices.densetools import col, eye, augment from sympy.matrices.densetools import rowadd, rowmul, conjugate_transpose -from sympy.core.symbol import symbols +from sympy import sqrt, var from sympy.core.compatibility import range -from sympy.core.power import isqrt - import copy - - def row_echelon(matlist, K): """ Returns the row echelon form of a matrix with diagonal elements @@ -139,7 +135,7 @@ def cholesky(matlist, K): for k in range(j): a += L[i][k]*L[j][k] if i == j: - L[i][j] = isqrt(new_matlist[i][j] - a) + L[i][j] = int(sqrt(new_matlist[i][j] - a)) else: L[i][j] = (new_matlist[i][j] - a)/L[j][j] return L, conjugate_transpose(L, K) @@ -308,8 +304,10 @@ def LU_solve(matlist, variable, constant, K): """ new_matlist = copy.deepcopy(matlist) nrow = len(new_matlist) + y = [] L, U = LU(new_matlist, K) - y = [[i] for i in symbols('y:%i' % nrow)] + for i in range(nrow): + y.append([var('y' + str(i))]) forward_substitution(L, y, constant, K) backward_substitution(U, variable, y, K) return variable @@ -351,8 +349,10 @@ def cholesky_solve(matlist, variable, constant, K): """ new_matlist = copy.deepcopy(matlist) nrow = len(new_matlist) + y = [] L, Lstar = cholesky(new_matlist, K) - y = [[i] for i in symbols('y:%i' % nrow)] + for i in range(nrow): + y.append([var('y' + str(i))]) forward_substitution(L, y, constant, K) backward_substitution(Lstar, variable, y, K) return variable diff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py index 7c8f2b03a3..706c578d74 100644 --- a/sympy/matrices/expressions/matexpr.py +++ b/sympy/matrices/expressions/matexpr.py @@ -338,7 +338,6 @@ class MatrixElement(Expr): i = property(lambda self: self.args[1]) j = property(lambda self: self.args[2]) _diff_wrt = True - is_commutative = True def doit(self, **kwargs): deep = kwargs.get('deep', True) diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py index 41314fc251..a44a70f567 100644 --- a/sympy/matrices/matrices.py +++ b/sympy/matrices/matrices.py @@ -505,11 +505,7 @@ def __mul__(self, other): raise ShapeError("Matrices size mismatch.") if A.cols == 0: return classof(A, B)._new(A.rows, B.cols, lambda i, j: 0) - try: - blst = B.T.tolist() - except AttributeError: - # If B is a MatrixSymbol, B.T.tolist does not exist - return NotImplemented + blst = B.T.tolist() alst = A.tolist() return classof(A, B)._new(A.rows, B.cols, lambda i, j: reduce(lambda k, l: k + l, diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py index cff676835b..8a50b13f87 100644 --- a/sympy/sets/sets.py +++ b/sympy/sets/sets.py @@ -911,8 +911,6 @@ def _union(self, other): See Set._union for docstring """ - if other.is_UniversalSet: - return S.UniversalSet if other.is_Interval and self._is_comparable(other): from sympy.functions.elementary.miscellaneous import Min, Max # Non-overlapping intervals diff --git a/sympy/simplify/trigsimp.py b/sympy/simplify/trigsimp.py index 69f03cc98e..81f179f685 100644 --- a/sympy/simplify/trigsimp.py +++ b/sympy/simplify/trigsimp.py @@ -15,7 +15,7 @@ from sympy.strategies.core import identity from sympy.strategies.tree import greedy -from sympy.polys import Poly + from sympy.polys.polyerrors import PolificationFailed from sympy.polys.polytools import groebner from sympy.polys.domains import ZZ diff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py index 2b30ad0f88..a05e2e50f4 100644 --- a/sympy/solvers/diophantine.py +++ b/sympy/solvers/diophantine.py @@ -7,7 +7,7 @@ from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.numbers import igcdex, ilcm, igcd -from sympy.core.power import integer_nthroot, isqrt +from sympy.core.power import integer_nthroot from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol, symbols @@ -29,7 +29,6 @@ from sympy.utilities.misc import filldedent - # these are imported with 'from sympy.solvers.diophantine import * __all__ = ['diophantine', 'classify_diop'] @@ -856,27 +855,26 @@ def _diop_quadratic(var, coeff, t): c = C // g e = sign(B/A) - sqa = isqrt(a) - sqc = isqrt(c) - _c = e*sqc*D - sqa*E - if not _c: + + _c = e*sqrt(c)*D - sqrt(a)*E + if _c == 0: z = symbols("z", real=True) - eq = sqa*g*z**2 + D*z + sqa*F + eq = sqrt(a)*g*z**2 + D*z + sqrt(a)*F roots = solveset_real(eq, z).intersect(S.Integers) for root in roots: - ans = diop_solve(sqa*x + e*sqc*y - root) + ans = diop_solve(sqrt(a)*x + e*sqrt(c)*y - root) sol.add((ans[0], ans[1])) - elif _is_int(c): - solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t\ - - (e*sqc*g*u**2 + E*u + e*sqc*F) // _c + elif _is_int(_c): + solve_x = lambda u: -e*sqrt(c)*g*_c*t**2 - (E + 2*e*sqrt(c)*g*u)*t\ + - (e*sqrt(c)*g*u**2 + E*u + e*sqrt(c)*F) // _c - solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \ - + (sqa*g*u**2 + D*u + sqa*F) // _c + solve_y = lambda u: sqrt(a)*g*_c*t**2 + (D + 2*sqrt(a)*g*u)*t \ + + (sqrt(a)*g*u**2 + D*u + sqrt(a)*F) // _c for z0 in range(0, abs(_c)): if divisible( - sqa*g*z0**2 + D*z0 + sqa*F, + sqrt(a)*g*z0**2 + D*z0 + sqrt(a)*F, _c): sol.add((solve_x(z0), solve_y(z0))) @@ -2548,7 +2546,7 @@ def diop_general_sum_of_squares(eq, limit=1): >>> from sympy.solvers.diophantine import diop_general_sum_of_squares >>> from sympy.abc import a, b, c, d, e, f >>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345) - set([(15, 22, 22, 24, 24)]) + set([(2, 4, 4, 10, 47)]) Reference ========= @@ -2810,23 +2808,26 @@ def sum_of_three_squares(n): if n % 8 == 3: s = s if _odd(s) else s - 1 - for x in range(s, -1, -2): - N = (n - x**2) // 2 - if isprime(N): - y, z = prime_as_sum_of_two_squares(N) - return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z)) - return + for i in range(s, -1, -2): + if isprime((n - i**2) // 2): + x = i + break + + y, z = prime_as_sum_of_two_squares((n - x**2) // 2) + return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z)) if n % 8 == 2 or n % 8 == 6: s = s if _odd(s) else s - 1 else: s = s - 1 if _odd(s) else s - for x in range(s, -1, -2): - N = n - x**2 - if isprime(N): - y, z = prime_as_sum_of_two_squares(N) - return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) + for i in range(s, -1, -2): + if isprime(n - i**2): + x = i + break + + y, z = prime_as_sum_of_two_squares(n - x**2) + return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) def sum_of_four_squares(n): @@ -2901,16 +2902,16 @@ def power_representation(n, p, k, zeros=False): >>> f = power_representation(1729, 3, 2) >>> next(f) - (9, 10) - >>> next(f) (1, 12) + >>> next(f) + (9, 10) If the flag `zeros` is True, the solution may contain tuples with zeros; any such solutions will be generated after the solutions without zeros: >>> list(power_representation(125, 2, 3, zeros=True)) - [(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)] + [(3, 4, 10), (5, 6, 8), (0, 2, 11), (0, 5, 10)] For even `p` the `permute_sign` function can be used to get all signed values: @@ -2981,13 +2982,13 @@ def power_representation(n, p, k, zeros=False): if n >= k: a = integer_nthroot(n - (k - 1), p)[0] for t in pow_rep_recursive(a, k, n, [], p): - yield tuple(reversed(t)) + yield t if zeros: a = integer_nthroot(n, p)[0] for i in range(1, k): for t in pow_rep_recursive(a, i, n, [], p): - yield tuple(reversed(t + (0,) * (k - i))) + yield (0,) * (k - i) + t sum_of_powers = power_representation @@ -2996,15 +2997,15 @@ def power_representation(n, p, k, zeros=False): def pow_rep_recursive(n_i, k, n_remaining, terms, p): if k == 0 and n_remaining == 0: - yield tuple(terms) + yield _sorted_tuple(*terms) else: - if n_i >= 1 and k > 0: + if n_i >= 1 and k > 0 and n_remaining >= 0: + if n_i**p <= n_remaining: + for t in pow_rep_recursive(n_i, k - 1, n_remaining - n_i**p, terms + [n_i], p): + yield _sorted_tuple(*t) + for t in pow_rep_recursive(n_i - 1, k, n_remaining, terms, p): - yield t - residual = n_remaining - pow(n_i, p) - if residual >= 0: - for t in pow_rep_recursive(n_i, k - 1, residual, terms + [n_i], p): - yield t + yield _sorted_tuple(*t) def sum_of_squares(n, k, zeros=False): diff --git a/sympy/stats/__init__.py b/sympy/stats/__init__.py index f426633dd0..d34f8f93a1 100644 --- a/sympy/stats/__init__.py +++ b/sympy/stats/__init__.py @@ -68,7 +68,3 @@ from . import drv_types from .drv_types import (Geometric, Poisson) __all__.extend(drv_types.__all__) - -from . import symbolic_probability -from .symbolic_probability import Probability, Expectation, Variance, Covariance -__all__.extend(symbolic_probability.__all__) diff --git a/sympy/stats/symbolic_probability.py b/sympy/stats/symbolic_probability.py index 4f8de12702..8ac27c4696 100644 --- a/sympy/stats/symbolic_probability.py +++ b/sympy/stats/symbolic_probability.py @@ -9,24 +9,10 @@ from sympy.stats import variance, covariance from sympy.stats.rv import RandomSymbol, probability, expectation -__all__ = ['Probability', 'Expectation', 'Variance', 'Covariance'] - class Probability(Expr): """ Symbolic expression for the probability. - - Examples - ======== - - >>> from sympy.stats import Probability, Normal - >>> X = Normal("X", 0, 1) - >>> prob = Probability(X > 1) - >>> prob - Probability(X > 1) - >>> prob.doit() - sqrt(2)*(-sqrt(2)*sqrt(pi)*erf(sqrt(2)/2) + sqrt(2)*sqrt(pi))/(4*sqrt(pi)) - """ def __new__(cls, prob, condition=None, **kwargs): prob = _sympify(prob) @@ -45,37 +31,6 @@ def doit(self, **kwargs): class Expectation(Expr): """ Symbolic expression for the expectation. - - Examples - ======== - - >>> from sympy.stats import Expectation, Normal - >>> from sympy import symbols - >>> mu = symbols("mu") - >>> sigma = symbols("sigma", positive=True) - >>> X = Normal("X", mu, sigma) - >>> Expectation(X) - Expectation(X) - >>> Expectation(X).doit().simplify() - mu - >>> Expectation(X).doit(evaluate=False) - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) - - This class is aware of some properties of the expectation: - - >>> from sympy.abc import a - >>> Expectation(a*X) - a*Expectation(X) - >>> Y = Normal("Y", 0, 1) - >>> Expectation(X + Y) - Expectation(X) + Expectation(Y) - - To prevent this kind of automatic evaluation, use ``evaluate=False``: - - >>> Expectation(a*X + Y) - a*Expectation(X) + Expectation(Y) - >>> Expectation(a*X + Y, evaluate=False) - Expectation(a*X + Y) """ def __new__(cls, expr, condition=None, **kwargs): expr = _sympify(expr) @@ -120,39 +75,6 @@ def doit(self, **kwargs): class Variance(Expr): """ Symbolic expression for the variance. - - Examples - ======== - - >>> from sympy import symbols - >>> from sympy.stats import Normal, Expectation, Variance - >>> mu = symbols("mu", positive=True) - >>> sigma = symbols("sigma", positive=True) - >>> X = Normal("X", mu, sigma) - >>> Variance(X) - Variance(X) - >>> Variance(X).doit() - sigma**2 - - Rewrite the variance in terms of the expectation - - >>> Variance(X).rewrite(Expectation) - -Expectation(X)**2 + Expectation(X**2) - - Some transformations based on the properties of the variance may happen: - - >>> from sympy.abc import a - >>> Y = Normal("Y", 0, 1) - >>> Variance(a*X) - a**2*Variance(X) - - To prevent automatic evaluation, use ``evaluate=False``: - - >>> Variance(X + Y) - 2*Covariance(X, Y) + Variance(X) + Variance(Y) - >>> Variance(X + Y, evaluate=False) - Variance(X + Y) - """ def __new__(cls, arg, condition=None, **kwargs): arg = _sympify(arg) @@ -208,11 +130,6 @@ def __new__(cls, arg, condition=None, **kwargs): # this expression contains a RandomSymbol somehow: return Variance(arg, condition, evaluate=False) - def _eval_rewrite_as_Expectation(self, arg, condition=None): - e1 = Expectation(arg**2, condition) - e2 = Expectation(arg, condition)**2 - return e1 - e2 - def doit(self, **kwargs): return variance(self.args[0], self._condition, **kwargs) @@ -220,57 +137,23 @@ def doit(self, **kwargs): class Covariance(Expr): """ Symbolic expression for the covariance. - - Examples - ======== - - >>> from sympy.stats import Covariance - >>> from sympy.stats import Normal - >>> X = Normal("X", 3, 2) - >>> Y = Normal("Y", 0, 1) - >>> Z = Normal("Z", 0, 1) - >>> W = Normal("W", 0, 1) - >>> cexpr = Covariance(X, Y) - >>> cexpr - Covariance(X, Y) - - Evaluate the covariance, `X` and `Y` are independent, - therefore zero is the result: - - >>> cexpr.doit() - 0 - - Rewrite the covariance expression in terms of expectations: - - >>> from sympy.stats import Expectation - >>> cexpr.rewrite(Expectation) - Expectation(X*Y) - Expectation(X)*Expectation(Y) - - This class is aware of some properties of the covariance: - - >>> Covariance(X, X) - Variance(X) - >>> from sympy.abc import a, b, c, d - >>> Covariance(a*X, b*Y) - a*b*Covariance(X, Y) - - In order to prevent such transformations, use ``evaluate=False``: - - >>> Covariance(a*X + b*Y, c*Z + d*W) - a*c*Covariance(X, Z) + a*d*Covariance(W, X) + b*c*Covariance(Y, Z) + b*d*Covariance(W, Y) - >>> Covariance(a*X + b*Y, c*Z + d*W, evaluate=False) - Covariance(a*X + b*Y, c*Z + d*W) """ def __new__(cls, arg1, arg2, condition=None, **kwargs): arg1 = _sympify(arg1) arg2 = _sympify(arg2) + if not kwargs.pop('evaluate', global_evaluate[0]): + if condition is None: + obj = Expr.__new__(cls, arg1, arg2) + else: + condition = _sympify(condition) + obj = Expr.__new__(cls, arg1, arg2, condition) + obj._condition = condition + return obj + if condition is not None: condition = _sympify(condition) - if not kwargs.pop('evaluate', global_evaluate[0]): - return cls._call_super_constructor(arg1, arg2, condition) - if arg1 == arg2: return Variance(arg1, condition) @@ -282,24 +165,15 @@ def __new__(cls, arg1, arg2, condition=None, **kwargs): arg1, arg2 = sorted([arg1, arg2], key=default_sort_key) if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol): - return cls._call_super_constructor(arg1, arg2, condition) + return Expr.__new__(cls, arg1, arg2) coeff_rv_list1 = cls._expand_single_argument(arg1.expand()) coeff_rv_list2 = cls._expand_single_argument(arg2.expand()) - addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), condition=condition, evaluate=False) + addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), evaluate=False) for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2] return Add(*addends) - @classmethod - def _call_super_constructor(cls, arg1, arg2, condition): - if condition is not None: - obj = Expr.__new__(cls, arg1, arg2, condition) - else: - obj = Expr.__new__(cls, arg1, arg2) - obj._condition = condition - return obj - @classmethod def _expand_single_argument(cls, expr): # return (coefficient, random_symbol) pairs: @@ -330,10 +204,5 @@ def _get_mul_nonrv_rv_tuple(cls, m): nonrv.append(a) return (Mul(*nonrv), Mul(*rv)) - def _eval_rewrite_as_Expectation(self, arg1, arg2, condition=None): - e1 = Expectation(arg1*arg2, condition) - e2 = Expectation(arg1, condition)*Expectation(arg2, condition) - return e1 - e2 - def doit(self, **kwargs): return covariance(self.args[0], self.args[1], self._condition, **kwargs) diff --git a/sympy/tensor/tensor.py b/sympy/tensor/tensor.py index ceb19944c3..1f14351c3b 100644 --- a/sympy/tensor/tensor.py +++ b/sympy/tensor/tensor.py @@ -828,16 +828,8 @@ def _get(self, key): if any([i is None for i in data_list]): raise ValueError("Mixing tensors with associated components "\ "data with tensors without components data") - - free_args_list = [[x[0] for x in arg.free] for arg in key.args] - numpy = import_module("numpy") - for data, free_args in zip(data_list, free_args_list): - if len(free_args) < 2: - sumvar += data - else: - free_args_pos = {y: x for x, y in enumerate(free_args)} - axes = [free_args_pos[arg] for arg in key.free_args] - sumvar += numpy.transpose(data, axes) + for i in data_list: + sumvar += i return sumvar return None
where possible, use python fractions for Rational Since we have dropped support for 2.5 we can use the [fractions module](https://docs.python.org/2/library/fractions.html?highlight=rational) for Rational internals. The `gcd` method could also replace `igcd`: ```python >>> timeit('gcd(12,3)','from fractions import gcd') 0.5296611342553904 >>> timeit('gcd(12,3)','from sympy import igcd as gcd') 6.766568780548827 ```
sympy/sympy
diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py index 0df107ec5d..1ebb1c31a9 100644 --- a/sympy/core/tests/test_numbers.py +++ b/sympy/core/tests/test_numbers.py @@ -4,14 +4,18 @@ Number, zoo, log, Mul, Pow, Tuple, latex, Gt, Lt, Ge, Le, AlgebraicNumber, simplify, sin) from sympy.core.compatibility import long, u -from sympy.core.power import integer_nthroot, isqrt +from sympy.core.power import integer_nthroot from sympy.core.logic import fuzzy_not from sympy.core.numbers import (igcd, ilcm, igcdex, seterr, _intcache, mpf_norm, comp, mod_inverse) -from mpmath import mpf +from sympy.utilities.iterables import permutations from sympy.utilities.pytest import XFAIL, raises + +from mpmath import mpf import mpmath + + t = Symbol('t', real=False) def same_and_same_prec(a, b): @@ -203,8 +207,14 @@ def test_igcd(): assert igcd(-7, 3) == 1 assert igcd(-7, -3) == 1 assert igcd(*[10, 20, 30]) == 10 - raises(ValueError, lambda: igcd(45.1, 30)) - raises(ValueError, lambda: igcd(45, 30.1)) + raises(TypeError, lambda: igcd()) + raises(TypeError, lambda: igcd(2)) + raises(ValueError, lambda: igcd(0, None)) + raises(ValueError, lambda: igcd(1, 2.2)) + for args in permutations((45.1, 1, 30)): + raises(ValueError, lambda: igcd(*args)) + for args in permutations((1, 2, None)): + raises(ValueError, lambda: igcd(*args)) def test_ilcm(): @@ -855,24 +865,12 @@ def test_powers(): # Test that this is fast assert integer_nthroot(2, 10**10) == (1, False) - # output should be int if possible - assert type(integer_nthroot(2**61, 2)[0]) is int - def test_integer_nthroot_overflow(): assert integer_nthroot(10**(50*50), 50) == (10**50, True) assert integer_nthroot(10**100000, 10000) == (10**10, True) -def test_isqrt(): - from math import sqrt as _sqrt - limit = 17984395633462800708566937239551 - assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0] - assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0] - assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0] - assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0] - - def test_powers_Integer(): """Test Integer._eval_power""" # check infinity diff --git a/sympy/functions/elementary/tests/test_miscellaneous.py b/sympy/functions/elementary/tests/test_miscellaneous.py index 1fb2ccd184..6e4b301f2c 100644 --- a/sympy/functions/elementary/tests/test_miscellaneous.py +++ b/sympy/functions/elementary/tests/test_miscellaneous.py @@ -351,21 +351,3 @@ def test_rewrite_MaxMin_as_Heaviside(): x*Heaviside(-2*x)*Heaviside(-x - 2) - \ x*Heaviside(2*x)*Heaviside(x - 2) \ - 2*Heaviside(-x + 2)*Heaviside(x + 2) - - -def test_issue_11099(): - from sympy.abc import x, y - # some fixed value tests - fixed_test_data = {x: -2, y: 3} - assert Min(x, y).evalf(subs=fixed_test_data) == \ - Min(x, y).subs(fixed_test_data).evalf() - assert Max(x, y).evalf(subs=fixed_test_data) == \ - Max(x, y).subs(fixed_test_data).evalf() - # randomly generate some test data - from random import randint - for i in range(20): - random_test_data = {x: randint(-100, 100), y: randint(-100, 100)} - assert Min(x, y).evalf(subs=random_test_data) == \ - Min(x, y).subs(random_test_data).evalf() - assert Max(x, y).evalf(subs=random_test_data) == \ - Max(x, y).subs(random_test_data).evalf() diff --git a/sympy/functions/special/tests/test_delta_functions.py b/sympy/functions/special/tests/test_delta_functions.py index e120380a3d..dd14bbdf7e 100644 --- a/sympy/functions/special/tests/test_delta_functions.py +++ b/sympy/functions/special/tests/test_delta_functions.py @@ -18,10 +18,6 @@ def test_DiracDelta(): assert DiracDelta(nan) == nan assert DiracDelta(0).func is DiracDelta assert DiracDelta(x).func is DiracDelta - # FIXME: this is generally undefined @ x=0 - # But then limit(Delta(c)*Heaviside(x),x,-oo) - # need's to be implemented. - #assert 0*DiracDelta(x) == 0 assert adjoint(DiracDelta(x)) == DiracDelta(x) assert adjoint(DiracDelta(x - y)) == DiracDelta(x - y) diff --git a/sympy/integrals/tests/test_deltafunctions.py b/sympy/integrals/tests/test_deltafunctions.py index e1977280ca..8b3789aca0 100644 --- a/sympy/integrals/tests/test_deltafunctions.py +++ b/sympy/integrals/tests/test_deltafunctions.py @@ -7,7 +7,7 @@ def test_change_mul(): - assert change_mul(x, x) == (None, None) + assert change_mul(x, x) == x assert change_mul(x*y, x) == (None, None) assert change_mul(x*y*DiracDelta(x), x) == (DiracDelta(x), x*y) assert change_mul(x*y*DiracDelta(x)*DiracDelta(y), x) == \ @@ -35,11 +35,8 @@ def test_deltaintegrate(): assert deltaintegrate(DiracDelta(x)**2, x) == DiracDelta(0)*Heaviside(x) assert deltaintegrate(y*DiracDelta(x)**2, x) == \ y*DiracDelta(0)*Heaviside(x) - assert deltaintegrate(DiracDelta(x, 1), x) == DiracDelta(x, 0) - assert deltaintegrate(y*DiracDelta(x, 1), x) == y*DiracDelta(x, 0) - assert deltaintegrate(DiracDelta(x, 1)**2, x) == -DiracDelta(0, 2)*Heaviside(x) - assert deltaintegrate(y*DiracDelta(x, 1)**2, x) == -y*DiracDelta(0, 2)*Heaviside(x) - + assert deltaintegrate(DiracDelta(x, 1)**2, x) is None + assert deltaintegrate(y*DiracDelta(x, 1)**2, x) is None assert deltaintegrate(DiracDelta(x) * f(x), x) == f(0) * Heaviside(x) assert deltaintegrate(DiracDelta(-x) * f(x), x) == f(0) * Heaviside(x) diff --git a/sympy/matrices/expressions/tests/test_matrix_exprs.py b/sympy/matrices/expressions/tests/test_matrix_exprs.py index 851df5a622..0dc25a0dc7 100644 --- a/sympy/matrices/expressions/tests/test_matrix_exprs.py +++ b/sympy/matrices/expressions/tests/test_matrix_exprs.py @@ -204,24 +204,6 @@ def test_single_indexing(): B = MatrixSymbol('B', n, m) raises(IndexError, lambda: B[1]) -def test_MatrixElement_commutative(): - assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1] - -def test_MatrixSymbol_determinant(): - A = MatrixSymbol('A', 4, 4) - assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \ - A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \ - A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \ - A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \ - A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \ - A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \ - A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \ - A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \ - A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \ - A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \ - A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \ - A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \ - A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0] def test_MatrixElement_diff(): assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0] diff --git a/sympy/matrices/tests/test_interactions.py b/sympy/matrices/tests/test_interactions.py index 7bb0d7991c..bdccd438f6 100644 --- a/sympy/matrices/tests/test_interactions.py +++ b/sympy/matrices/tests/test_interactions.py @@ -14,7 +14,6 @@ from sympy.utilities.pytest import raises SM = MatrixSymbol('X', 3, 3) -SV = MatrixSymbol('v', 3, 1) MM = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) IM = ImmutableMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) meye = eye(3) @@ -50,16 +49,6 @@ def test_matrix_symbol_MM(): assert Y[1, 1] == 1 + X[1, 1] -def test_matrix_symbol_vector_matrix_multiplication(): - A = MM * SV - B = IM * SV - assert A == B - C = (SV.T * MM.T).T - assert B == C - D = (SV.T * IM.T).T - assert C == D - - def test_indexing_interactions(): assert (a * IM)[1, 1] == 5*a assert (SM + IM)[1, 1] == SM[1, 1] + IM[1, 1] diff --git a/sympy/polys/tests/test_polytools.py b/sympy/polys/tests/test_polytools.py index b9145f01f6..e2c796fd9a 100644 --- a/sympy/polys/tests/test_polytools.py +++ b/sympy/polys/tests/test_polytools.py @@ -58,7 +58,6 @@ from sympy.core.compatibility import iterable from sympy.core.mul import _keep_coeff from sympy.utilities.pytest import raises, XFAIL -from sympy.simplify import simplify from sympy.abc import a, b, c, d, p, q, t, w, x, y, z from sympy import MatrixSymbol @@ -2882,7 +2881,8 @@ def test_cancel(): M = MatrixSymbol('M', 5, 5) assert cancel(M[0,0] + 7) == M[0,0] + 7 expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z - assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z + assert cancel(expr) == expr + def test_reduced(): f = 2*x**4 + y**2 - x**2 + y**3 diff --git a/sympy/printing/tests/test_ccode.py b/sympy/printing/tests/test_ccode.py index 26062c507e..b97368a2f8 100644 --- a/sympy/printing/tests/test_ccode.py +++ b/sympy/printing/tests/test_ccode.py @@ -446,8 +446,8 @@ def test_Matrix_printing(): "M[3] = q[1] + q[2];\n" "M[4] = q[3];\n" "M[5] = 5;\n" - "M[6] = 2*q[4]/q[1];\n" - "M[7] = sqrt(q[0]) + 4;\n" + "M[6] = 2*q[4]*1.0/q[1];\n" + "M[7] = 4 + sqrt(q[0]);\n" "M[8] = 0;") diff --git a/sympy/printing/tests/test_fcode.py b/sympy/printing/tests/test_fcode.py index bdb96a69d2..c077a6b8c0 100644 --- a/sympy/printing/tests/test_fcode.py +++ b/sympy/printing/tests/test_fcode.py @@ -658,10 +658,10 @@ def test_Matrix_printing(): assert fcode(m, M) == ( " M(1, 1) = sin(q(2, 1))\n" " M(2, 1) = q(2, 1) + q(3, 1)\n" - " M(3, 1) = 2*q(5, 1)/q(2, 1)\n" + " M(3, 1) = 2*q(5, 1)*1.0/q(2, 1)\n" " M(1, 2) = 0\n" " M(2, 2) = q(4, 1)\n" - " M(3, 2) = sqrt(q(1, 1)) + 4\n" + " M(3, 2) = 4 + sqrt(q(1, 1))\n" " M(1, 3) = cos(q(3, 1))\n" " M(2, 3) = 5\n" " M(3, 3) = 0") diff --git a/sympy/printing/tests/test_jscode.py b/sympy/printing/tests/test_jscode.py index bff26227e9..588039f440 100644 --- a/sympy/printing/tests/test_jscode.py +++ b/sympy/printing/tests/test_jscode.py @@ -361,6 +361,6 @@ def test_Matrix_printing(): "M[3] = q[1] + q[2];\n" "M[4] = q[3];\n" "M[5] = 5;\n" - "M[6] = 2*q[4]/q[1];\n" - "M[7] = Math.sqrt(q[0]) + 4;\n" + "M[6] = 2*q[4]*1/q[1];\n" + "M[7] = 4 + Math.sqrt(q[0]);\n" "M[8] = 0;") diff --git a/sympy/sets/tests/test_sets.py b/sympy/sets/tests/test_sets.py index 4d4a5175f6..f1871c3022 100644 --- a/sympy/sets/tests/test_sets.py +++ b/sympy/sets/tests/test_sets.py @@ -1009,17 +1009,6 @@ def test_issue_10326(): assert Interval(-oo, oo).contains(-oo) is S.false -def test_issue_2799(): - U = S.UniversalSet - a = Symbol('a', real=True) - inf_interval = Interval(a, oo) - R = S.Reals - - assert U + inf_interval == inf_interval + U - assert U + R == R + U - assert R + inf_interval == inf_interval + R - - def test_issue_9706(): assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False) assert Interval(0, oo).closure == Interval(0, oo, False, True) diff --git a/sympy/simplify/tests/test_trigsimp.py b/sympy/simplify/tests/test_trigsimp.py index 641ed67bed..d753c844a8 100644 --- a/sympy/simplify/tests/test_trigsimp.py +++ b/sympy/simplify/tests/test_trigsimp.py @@ -316,7 +316,7 @@ def test_trigsimp_groebner(): results = [resnum/resdenom, (-resnum)/(-resdenom)] assert trigsimp_groebner(ex) in results assert trigsimp_groebner(s/c, hints=[tan]) == tan(x) - assert trigsimp_groebner(c*s) == c*s + assert trigsimp((-s + 1)/c + c/(-s + 1), method='groebner') == 2/c assert trigsimp((-s + 1)/c + c/(-s + 1), diff --git a/sympy/solvers/tests/test_diophantine.py b/sympy/solvers/tests/test_diophantine.py index c502425159..95ed44ad4b 100644 --- a/sympy/solvers/tests/test_diophantine.py +++ b/sympy/solvers/tests/test_diophantine.py @@ -794,7 +794,7 @@ def test_diop_sum_of_even_powers(): raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2)) neg = symbols('neg', negative=True) eq = x**4 + y**4 + neg**4 - 2673 - assert diop_general_sum_of_even_powers(eq) == set([(-3, 6, 6)]) + assert diop_general_sum_of_even_powers(eq) == set([(-2, 4, 7)]) assert diophantine(x**4 + y**4 + 2) == set() assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set() @@ -816,7 +816,7 @@ def test_sum_of_squares_powers(): assert list(sum_of_squares(0, 3)) == [] assert list(sum_of_squares(4, 1)) == [(2,)] assert list(sum_of_squares(5, 1)) == [] - assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)] + assert list(sum_of_squares(50, 2)) == [(1, 7), (5, 5)] assert list(sum_of_squares(11, 5, True)) == [ (1, 1, 1, 2, 2), (0, 0, 1, 1, 3)] assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)] diff --git a/sympy/stats/tests/test_symbolic_probability.py b/sympy/stats/tests/test_symbolic_probability.py index e578a3e063..baabbd5d0f 100644 --- a/sympy/stats/tests/test_symbolic_probability.py +++ b/sympy/stats/tests/test_symbolic_probability.py @@ -1,7 +1,7 @@ from sympy import symbols, Mul, sin from sympy.stats import Normal, Poisson, variance from sympy.stats.rv import probability, expectation -from sympy.stats import Covariance, Variance, Probability, Expectation +from sympy.stats.symbolic_probability import Covariance, Variance, Probability, Expectation def test_literal_probability(): @@ -56,22 +56,3 @@ def test_literal_probability(): assert Covariance(X, X**2) == Covariance(X, X**2, evaluate=False) assert Covariance(X, sin(X)) == Covariance(sin(X), X, evaluate=False) assert Covariance(X**2, sin(X)*Y) == Covariance(sin(X)*Y, X**2, evaluate=False) - - -def test_probability_rewrite(): - X = Normal('X', 2, 3) - Y = Normal('Y', 3, 4) - Z = Poisson('Z', 4) - W = Poisson('W', 3) - x, y, w, z = symbols('x, y, w, z') - - assert Variance(w).rewrite(Expectation) == 0 - assert Variance(X).rewrite(Expectation) == Expectation(X ** 2) - Expectation(X) ** 2 - assert Variance(X, condition=Y).rewrite(Expectation) == Expectation(X ** 2, Y) - Expectation(X, Y) ** 2 - assert Variance(X, Y) != Expectation(X**2) - Expectation(X)**2 - assert Variance(X + z).rewrite(Expectation) == Expectation(X ** 2) - Expectation(X) ** 2 - assert Variance(X * Y).rewrite(Expectation) == Expectation(X ** 2 * Y ** 2) - Expectation(X * Y) ** 2 - - assert Covariance(w, X).rewrite(Expectation) == 0 - assert Covariance(X, Y).rewrite(Expectation) == Expectation(X*Y) - Expectation(X)*Expectation(Y) - assert Covariance(X, Y, condition=W).rewrite(Expectation) == Expectation(X * Y, W) - Expectation(X, W) * Expectation(Y, W) diff --git a/sympy/tensor/tests/test_tensor.py b/sympy/tensor/tests/test_tensor.py index bb8fcc5927..5a171d63df 100644 --- a/sympy/tensor/tests/test_tensor.py +++ b/sympy/tensor/tests/test_tensor.py @@ -1777,60 +1777,3 @@ def test_TensMul_data(): assert ((F(alpha, mu) * F(beta, nu) * u(-alpha) * u(-beta)).data == (E(mu) * E(nu)).data ).all() - - S2 = TensorType([Lorentz] * 2, tensorsymmetry([1] * 2)) - g = S2('g') - g.data = Lorentz.data - - # tensor 'perp' is orthogonal to vector 'u' - perp = u(mu) * u(nu) + g(mu, nu) - - mul_1 = u(-mu) * perp(mu, nu) - assert (mul_1.data == numpy.array([0, 0, 0, 0])).all() - - mul_2 = u(-mu) * perp(mu, alpha) * perp(nu, beta) - assert (mul_2.data == numpy.zeros(shape=(4, 4, 4))).all() - - Fperp = perp(mu, alpha) * perp(nu, beta) * F(-alpha, -beta) - assert (Fperp.data[0, :] == numpy.array([0, 0, 0, 0])).all() - assert (Fperp.data[:, 0] == numpy.array([0, 0, 0, 0])).all() - - mul_3 = u(-mu) * Fperp(mu, nu) - assert (mul_3.data == numpy.array([0, 0, 0, 0])).all() - - -def test_issue_11020_TensAdd_data(): - numpy = import_module('numpy') - if numpy is None: - return - - Lorentz = TensorIndexType('Lorentz', metric=False, dummy_fmt='i', dim=2) - Lorentz.data = [-1, 1] - - a, b, c, d = tensor_indices('a, b, c, d', Lorentz) - i0, i1 = tensor_indices('i_0:2', Lorentz) - - Vec = TensorType([Lorentz], tensorsymmetry([1])) - S2 = TensorType([Lorentz] * 2, tensorsymmetry([1] * 2)) - - # metric tensor - g = S2('g') - g.data = Lorentz.data - - u = Vec('u') - u.data = [1, 0] - - add_1 = g(b, c) * g(d, i0) * u(-i0) - g(b, c) * u(d) - assert (add_1.data == numpy.zeros(shape=(2, 2, 2))).all() - # Now let us replace index `d` with `a`: - add_2 = g(b, c) * g(a, i0) * u(-i0) - g(b, c) * u(a) - assert (add_2.data == numpy.zeros(shape=(2, 2, 2))).all() - - # some more tests - # perp is tensor orthogonal to u^\mu - perp = u(a) * u(b) + g(a, b) - mul_1 = u(-a) * perp(a, b) - assert (mul_1.data == numpy.array([0, 0])).all() - - mul_2 = u(-c) * perp(c, a) * perp(d, b) - assert (mul_2.data == numpy.zeros(shape=(2, 2, 2))).all()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 14 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mpmath>=0.19", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi exceptiongroup==1.2.2 importlib-metadata==6.7.0 iniconfig==2.0.0 mpmath==1.3.0 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 -e git+https://github.com/sympy/sympy.git@d15efa225684da73ca1921c0b5d3d52068eb5ecd#egg=sympy tomli==2.0.1 typing_extensions==4.7.1 zipp==3.15.0
name: sympy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - mpmath==1.3.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - tomli==2.0.1 - typing-extensions==4.7.1 - zipp==3.15.0 prefix: /opt/conda/envs/sympy
[ "sympy/core/tests/test_numbers.py::test_igcd", "sympy/integrals/tests/test_deltafunctions.py::test_change_mul", "sympy/integrals/tests/test_deltafunctions.py::test_deltaintegrate", "sympy/polys/tests/test_polytools.py::test_cancel", "sympy/printing/tests/test_ccode.py::test_Matrix_printing", "sympy/printing/tests/test_fcode.py::test_Matrix_printing", "sympy/printing/tests/test_jscode.py::test_Matrix_printing", "sympy/solvers/tests/test_diophantine.py::test_diop_sum_of_even_powers", "sympy/solvers/tests/test_diophantine.py::test_sum_of_squares_powers" ]
[ "sympy/core/tests/test_numbers.py::test_mpmath_issues", "sympy/polys/tests/test_polytools.py::test_factor_noeval", "sympy/polys/tests/test_polytools.py::test_poly_matching_consistency", "sympy/polys/tests/test_polytools.py::test_issue_5786", "sympy/sets/tests/test_sets.py::test_image_Intersection", "sympy/sets/tests/test_sets.py::test_union_boundary_of_joining_sets", "sympy/simplify/tests/test_trigsimp.py::test_issue_6811_fail", "sympy/solvers/tests/test_diophantine.py::test_quadratic_non_perfect_square", "sympy/solvers/tests/test_diophantine.py::test_issue_9106", "sympy/solvers/tests/test_diophantine.py::test_quadratic_non_perfect_slow", "sympy/solvers/tests/test_diophantine.py::test_DN", "sympy/solvers/tests/test_diophantine.py::test_diop_ternary_quadratic_normal", "sympy/solvers/tests/test_diophantine.py::test_diop_ternary_quadratic", "sympy/solvers/tests/test_diophantine.py::test_descent", "sympy/solvers/tests/test_diophantine.py::test_diopcoverage", "sympy/solvers/tests/test_diophantine.py::test_fail_holzer", "sympy/solvers/tests/test_diophantine.py::test_issue_8943", "sympy/tensor/tests/test_tensor.py::test_valued_tensor_iter", "sympy/tensor/tests/test_tensor.py::test_valued_tensor_covariant_contravariant_elements", "sympy/tensor/tests/test_tensor.py::test_valued_tensor_get_matrix", "sympy/tensor/tests/test_tensor.py::test_valued_tensor_contraction", "sympy/tensor/tests/test_tensor.py::test_valued_tensor_self_contraction", "sympy/tensor/tests/test_tensor.py::test_valued_tensor_pow", "sympy/tensor/tests/test_tensor.py::test_valued_tensor_expressions", "sympy/tensor/tests/test_tensor.py::test_noncommuting_components", "sympy/tensor/tests/test_tensor.py::test_valued_non_diagonal_metric", "sympy/tensor/tests/test_tensor.py::test_valued_assign_numpy_ndarray" ]
[ "sympy/core/tests/test_numbers.py::test_integers_cache", "sympy/core/tests/test_numbers.py::test_seterr", "sympy/core/tests/test_numbers.py::test_mod", "sympy/core/tests/test_numbers.py::test_divmod", "sympy/core/tests/test_numbers.py::test_ilcm", "sympy/core/tests/test_numbers.py::test_igcdex", "sympy/core/tests/test_numbers.py::test_Integer_new", "sympy/core/tests/test_numbers.py::test_Rational_new", "sympy/core/tests/test_numbers.py::test_Number_new", "sympy/core/tests/test_numbers.py::test_Rational_cmp", "sympy/core/tests/test_numbers.py::test_Float", "sympy/core/tests/test_numbers.py::test_Float_default_to_highprec_from_str", "sympy/core/tests/test_numbers.py::test_Float_eval", "sympy/core/tests/test_numbers.py::test_Float_issue_2107", "sympy/core/tests/test_numbers.py::test_Infinity", "sympy/core/tests/test_numbers.py::test_Infinity_2", "sympy/core/tests/test_numbers.py::test_Mul_Infinity_Zero", "sympy/core/tests/test_numbers.py::test_Div_By_Zero", "sympy/core/tests/test_numbers.py::test_Infinity_inequations", "sympy/core/tests/test_numbers.py::test_NaN", "sympy/core/tests/test_numbers.py::test_special_numbers", "sympy/core/tests/test_numbers.py::test_powers", "sympy/core/tests/test_numbers.py::test_integer_nthroot_overflow", "sympy/core/tests/test_numbers.py::test_powers_Integer", "sympy/core/tests/test_numbers.py::test_powers_Rational", "sympy/core/tests/test_numbers.py::test_powers_Float", "sympy/core/tests/test_numbers.py::test_abs1", "sympy/core/tests/test_numbers.py::test_accept_int", "sympy/core/tests/test_numbers.py::test_dont_accept_str", "sympy/core/tests/test_numbers.py::test_int", "sympy/core/tests/test_numbers.py::test_long", "sympy/core/tests/test_numbers.py::test_real_bug", "sympy/core/tests/test_numbers.py::test_bug_sqrt", "sympy/core/tests/test_numbers.py::test_pi_Pi", "sympy/core/tests/test_numbers.py::test_no_len", "sympy/core/tests/test_numbers.py::test_issue_3321", "sympy/core/tests/test_numbers.py::test_issue_3692", "sympy/core/tests/test_numbers.py::test_issue_3423", "sympy/core/tests/test_numbers.py::test_issue_3449", "sympy/core/tests/test_numbers.py::test_Integer_factors", "sympy/core/tests/test_numbers.py::test_Rational_factors", "sympy/core/tests/test_numbers.py::test_issue_4107", "sympy/core/tests/test_numbers.py::test_IntegerInteger", "sympy/core/tests/test_numbers.py::test_Rational_gcd_lcm_cofactors", "sympy/core/tests/test_numbers.py::test_Float_gcd_lcm_cofactors", "sympy/core/tests/test_numbers.py::test_issue_4611", "sympy/core/tests/test_numbers.py::test_conversion_to_mpmath", "sympy/core/tests/test_numbers.py::test_relational", "sympy/core/tests/test_numbers.py::test_Integer_as_index", "sympy/core/tests/test_numbers.py::test_Rational_int", "sympy/core/tests/test_numbers.py::test_zoo", "sympy/core/tests/test_numbers.py::test_issue_4122", "sympy/core/tests/test_numbers.py::test_GoldenRatio_expand", "sympy/core/tests/test_numbers.py::test_as_content_primitive", "sympy/core/tests/test_numbers.py::test_hashing_sympy_integers", "sympy/core/tests/test_numbers.py::test_issue_4172", "sympy/core/tests/test_numbers.py::test_Catalan_EulerGamma_prec", "sympy/core/tests/test_numbers.py::test_Float_eq", "sympy/core/tests/test_numbers.py::test_int_NumberSymbols", "sympy/core/tests/test_numbers.py::test_issue_6640", "sympy/core/tests/test_numbers.py::test_issue_6349", "sympy/core/tests/test_numbers.py::test_mpf_norm", "sympy/core/tests/test_numbers.py::test_latex", "sympy/core/tests/test_numbers.py::test_issue_7742", "sympy/core/tests/test_numbers.py::test_simplify_AlgebraicNumber", "sympy/core/tests/test_numbers.py::test_Float_idempotence", "sympy/core/tests/test_numbers.py::test_comp", "sympy/core/tests/test_numbers.py::test_issue_9491", "sympy/core/tests/test_numbers.py::test_issue_10063", "sympy/core/tests/test_numbers.py::test_issue_10020", "sympy/core/tests/test_numbers.py::test_invert_numbers", "sympy/core/tests/test_numbers.py::test_mod_inverse", "sympy/core/tests/test_numbers.py::test_golden_ratio_rewrite_as_sqrt", "sympy/functions/elementary/tests/test_miscellaneous.py::test_Min", "sympy/functions/elementary/tests/test_miscellaneous.py::test_Max", "sympy/functions/elementary/tests/test_miscellaneous.py::test_minmax_assumptions", "sympy/functions/elementary/tests/test_miscellaneous.py::test_issue_8413", "sympy/functions/elementary/tests/test_miscellaneous.py::test_root", "sympy/functions/elementary/tests/test_miscellaneous.py::test_real_root", "sympy/functions/elementary/tests/test_miscellaneous.py::test_rewrite_MaxMin_as_Heaviside", "sympy/functions/special/tests/test_delta_functions.py::test_DiracDelta", "sympy/functions/special/tests/test_delta_functions.py::test_heaviside", "sympy/functions/special/tests/test_delta_functions.py::test_rewrite", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_shape", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matexpr", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_subs", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix_doit", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity_doit", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_addition", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_multiplication", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatPow", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixSymbol", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_dense_conversion", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_free_symbols", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_zero_matmul", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matadd_simplify", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matmul_simplify", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_invariants", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_indexing", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_single_indexing", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixElement_diff", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixElement_doit", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_identity_powers", "sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Zero_power", "sympy/matrices/tests/test_interactions.py::test_IM_MM", "sympy/matrices/tests/test_interactions.py::test_ME_MM", "sympy/matrices/tests/test_interactions.py::test_equality", "sympy/matrices/tests/test_interactions.py::test_matrix_symbol_MM", "sympy/matrices/tests/test_interactions.py::test_indexing_interactions", "sympy/matrices/tests/test_interactions.py::test_classof", "sympy/polys/tests/test_polytools.py::test_Poly_from_dict", "sympy/polys/tests/test_polytools.py::test_Poly_from_list", "sympy/polys/tests/test_polytools.py::test_Poly_from_poly", "sympy/polys/tests/test_polytools.py::test_Poly_from_expr", "sympy/polys/tests/test_polytools.py::test_Poly__new__", "sympy/polys/tests/test_polytools.py::test_Poly__args", "sympy/polys/tests/test_polytools.py::test_Poly__gens", "sympy/polys/tests/test_polytools.py::test_Poly_zero", "sympy/polys/tests/test_polytools.py::test_Poly_one", "sympy/polys/tests/test_polytools.py::test_Poly__unify", "sympy/polys/tests/test_polytools.py::test_Poly_free_symbols", "sympy/polys/tests/test_polytools.py::test_PurePoly_free_symbols", "sympy/polys/tests/test_polytools.py::test_Poly__eq__", "sympy/polys/tests/test_polytools.py::test_PurePoly__eq__", "sympy/polys/tests/test_polytools.py::test_PurePoly_Poly", "sympy/polys/tests/test_polytools.py::test_Poly_get_domain", "sympy/polys/tests/test_polytools.py::test_Poly_set_domain", "sympy/polys/tests/test_polytools.py::test_Poly_get_modulus", "sympy/polys/tests/test_polytools.py::test_Poly_set_modulus", "sympy/polys/tests/test_polytools.py::test_Poly_add_ground", "sympy/polys/tests/test_polytools.py::test_Poly_sub_ground", "sympy/polys/tests/test_polytools.py::test_Poly_mul_ground", "sympy/polys/tests/test_polytools.py::test_Poly_quo_ground", "sympy/polys/tests/test_polytools.py::test_Poly_exquo_ground", "sympy/polys/tests/test_polytools.py::test_Poly_abs", "sympy/polys/tests/test_polytools.py::test_Poly_neg", "sympy/polys/tests/test_polytools.py::test_Poly_add", "sympy/polys/tests/test_polytools.py::test_Poly_sub", "sympy/polys/tests/test_polytools.py::test_Poly_mul", "sympy/polys/tests/test_polytools.py::test_Poly_sqr", "sympy/polys/tests/test_polytools.py::test_Poly_pow", "sympy/polys/tests/test_polytools.py::test_Poly_divmod", "sympy/polys/tests/test_polytools.py::test_Poly_eq_ne", "sympy/polys/tests/test_polytools.py::test_Poly_nonzero", "sympy/polys/tests/test_polytools.py::test_Poly_properties", "sympy/polys/tests/test_polytools.py::test_Poly_is_irreducible", "sympy/polys/tests/test_polytools.py::test_Poly_subs", "sympy/polys/tests/test_polytools.py::test_Poly_replace", "sympy/polys/tests/test_polytools.py::test_Poly_reorder", "sympy/polys/tests/test_polytools.py::test_Poly_ltrim", "sympy/polys/tests/test_polytools.py::test_Poly_has_only_gens", "sympy/polys/tests/test_polytools.py::test_Poly_to_ring", "sympy/polys/tests/test_polytools.py::test_Poly_to_field", "sympy/polys/tests/test_polytools.py::test_Poly_to_exact", "sympy/polys/tests/test_polytools.py::test_Poly_retract", "sympy/polys/tests/test_polytools.py::test_Poly_slice", "sympy/polys/tests/test_polytools.py::test_Poly_coeffs", "sympy/polys/tests/test_polytools.py::test_Poly_monoms", "sympy/polys/tests/test_polytools.py::test_Poly_terms", "sympy/polys/tests/test_polytools.py::test_Poly_all_coeffs", "sympy/polys/tests/test_polytools.py::test_Poly_all_monoms", "sympy/polys/tests/test_polytools.py::test_Poly_all_terms", "sympy/polys/tests/test_polytools.py::test_Poly_termwise", "sympy/polys/tests/test_polytools.py::test_Poly_length", "sympy/polys/tests/test_polytools.py::test_Poly_as_dict", "sympy/polys/tests/test_polytools.py::test_Poly_as_expr", "sympy/polys/tests/test_polytools.py::test_Poly_lift", "sympy/polys/tests/test_polytools.py::test_Poly_deflate", "sympy/polys/tests/test_polytools.py::test_Poly_inject", "sympy/polys/tests/test_polytools.py::test_Poly_eject", "sympy/polys/tests/test_polytools.py::test_Poly_exclude", "sympy/polys/tests/test_polytools.py::test_Poly__gen_to_level", "sympy/polys/tests/test_polytools.py::test_Poly_degree", "sympy/polys/tests/test_polytools.py::test_Poly_degree_list", "sympy/polys/tests/test_polytools.py::test_Poly_total_degree", "sympy/polys/tests/test_polytools.py::test_Poly_homogenize", "sympy/polys/tests/test_polytools.py::test_Poly_homogeneous_order", "sympy/polys/tests/test_polytools.py::test_Poly_LC", "sympy/polys/tests/test_polytools.py::test_Poly_TC", "sympy/polys/tests/test_polytools.py::test_Poly_EC", "sympy/polys/tests/test_polytools.py::test_Poly_coeff", "sympy/polys/tests/test_polytools.py::test_Poly_nth", "sympy/polys/tests/test_polytools.py::test_Poly_LM", "sympy/polys/tests/test_polytools.py::test_Poly_LM_custom_order", "sympy/polys/tests/test_polytools.py::test_Poly_EM", "sympy/polys/tests/test_polytools.py::test_Poly_LT", "sympy/polys/tests/test_polytools.py::test_Poly_ET", "sympy/polys/tests/test_polytools.py::test_Poly_max_norm", "sympy/polys/tests/test_polytools.py::test_Poly_l1_norm", "sympy/polys/tests/test_polytools.py::test_Poly_clear_denoms", "sympy/polys/tests/test_polytools.py::test_Poly_rat_clear_denoms", "sympy/polys/tests/test_polytools.py::test_Poly_integrate", "sympy/polys/tests/test_polytools.py::test_Poly_diff", "sympy/polys/tests/test_polytools.py::test_issue_9585", "sympy/polys/tests/test_polytools.py::test_Poly_eval", "sympy/polys/tests/test_polytools.py::test_Poly___call__", "sympy/polys/tests/test_polytools.py::test_parallel_poly_from_expr", "sympy/polys/tests/test_polytools.py::test_pdiv", "sympy/polys/tests/test_polytools.py::test_div", "sympy/polys/tests/test_polytools.py::test_gcdex", "sympy/polys/tests/test_polytools.py::test_revert", "sympy/polys/tests/test_polytools.py::test_subresultants", "sympy/polys/tests/test_polytools.py::test_resultant", "sympy/polys/tests/test_polytools.py::test_discriminant", "sympy/polys/tests/test_polytools.py::test_dispersion", "sympy/polys/tests/test_polytools.py::test_gcd_list", "sympy/polys/tests/test_polytools.py::test_lcm_list", "sympy/polys/tests/test_polytools.py::test_gcd", "sympy/polys/tests/test_polytools.py::test_gcd_numbers_vs_polys", "sympy/polys/tests/test_polytools.py::test_terms_gcd", "sympy/polys/tests/test_polytools.py::test_trunc", "sympy/polys/tests/test_polytools.py::test_monic", "sympy/polys/tests/test_polytools.py::test_content", "sympy/polys/tests/test_polytools.py::test_primitive", "sympy/polys/tests/test_polytools.py::test_compose", "sympy/polys/tests/test_polytools.py::test_shift", "sympy/polys/tests/test_polytools.py::test_sturm", "sympy/polys/tests/test_polytools.py::test_gff", "sympy/polys/tests/test_polytools.py::test_sqf_norm", "sympy/polys/tests/test_polytools.py::test_sqf", "sympy/polys/tests/test_polytools.py::test_factor", "sympy/polys/tests/test_polytools.py::test_factor_large", "sympy/polys/tests/test_polytools.py::test_intervals", "sympy/polys/tests/test_polytools.py::test_refine_root", "sympy/polys/tests/test_polytools.py::test_count_roots", "sympy/polys/tests/test_polytools.py::test_Poly_root", "sympy/polys/tests/test_polytools.py::test_real_roots", "sympy/polys/tests/test_polytools.py::test_all_roots", "sympy/polys/tests/test_polytools.py::test_nroots", "sympy/polys/tests/test_polytools.py::test_ground_roots", "sympy/polys/tests/test_polytools.py::test_nth_power_roots_poly", "sympy/polys/tests/test_polytools.py::test_torational_factor_list", "sympy/polys/tests/test_polytools.py::test_reduced", "sympy/polys/tests/test_polytools.py::test_groebner", "sympy/polys/tests/test_polytools.py::test_fglm", "sympy/polys/tests/test_polytools.py::test_is_zero_dimensional", "sympy/polys/tests/test_polytools.py::test_GroebnerBasis", "sympy/polys/tests/test_polytools.py::test_poly", "sympy/polys/tests/test_polytools.py::test_keep_coeff", "sympy/polys/tests/test_polytools.py::test_noncommutative", "sympy/polys/tests/test_polytools.py::test_to_rational_coeffs", "sympy/polys/tests/test_polytools.py::test_factor_terms", "sympy/printing/tests/test_ccode.py::test_printmethod", "sympy/printing/tests/test_ccode.py::test_ccode_sqrt", "sympy/printing/tests/test_ccode.py::test_ccode_Pow", "sympy/printing/tests/test_ccode.py::test_ccode_constants_mathh", "sympy/printing/tests/test_ccode.py::test_ccode_constants_other", "sympy/printing/tests/test_ccode.py::test_ccode_Rational", "sympy/printing/tests/test_ccode.py::test_ccode_Integer", "sympy/printing/tests/test_ccode.py::test_ccode_functions", "sympy/printing/tests/test_ccode.py::test_ccode_inline_function", "sympy/printing/tests/test_ccode.py::test_ccode_exceptions", "sympy/printing/tests/test_ccode.py::test_ccode_user_functions", "sympy/printing/tests/test_ccode.py::test_ccode_boolean", "sympy/printing/tests/test_ccode.py::test_ccode_Piecewise", "sympy/printing/tests/test_ccode.py::test_ccode_Piecewise_deep", "sympy/printing/tests/test_ccode.py::test_ccode_ITE", "sympy/printing/tests/test_ccode.py::test_ccode_settings", "sympy/printing/tests/test_ccode.py::test_ccode_Indexed", "sympy/printing/tests/test_ccode.py::test_ccode_Indexed_without_looking_for_contraction", "sympy/printing/tests/test_ccode.py::test_ccode_loops_matrix_vector", "sympy/printing/tests/test_ccode.py::test_dummy_loops", "sympy/printing/tests/test_ccode.py::test_ccode_loops_add", "sympy/printing/tests/test_ccode.py::test_ccode_loops_multiple_contractions", "sympy/printing/tests/test_ccode.py::test_ccode_loops_addfactor", "sympy/printing/tests/test_ccode.py::test_ccode_loops_multiple_terms", "sympy/printing/tests/test_ccode.py::test_dereference_printing", "sympy/printing/tests/test_ccode.py::test_ccode_reserved_words", "sympy/printing/tests/test_ccode.py::test_ccode_sign", "sympy/printing/tests/test_fcode.py::test_printmethod", "sympy/printing/tests/test_fcode.py::test_fcode_Pow", "sympy/printing/tests/test_fcode.py::test_fcode_Rational", "sympy/printing/tests/test_fcode.py::test_fcode_Integer", "sympy/printing/tests/test_fcode.py::test_fcode_Float", "sympy/printing/tests/test_fcode.py::test_fcode_functions", "sympy/printing/tests/test_fcode.py::test_fcode_functions_with_integers", "sympy/printing/tests/test_fcode.py::test_fcode_NumberSymbol", "sympy/printing/tests/test_fcode.py::test_fcode_complex", "sympy/printing/tests/test_fcode.py::test_implicit", "sympy/printing/tests/test_fcode.py::test_not_fortran", "sympy/printing/tests/test_fcode.py::test_user_functions", "sympy/printing/tests/test_fcode.py::test_inline_function", "sympy/printing/tests/test_fcode.py::test_assign_to", "sympy/printing/tests/test_fcode.py::test_line_wrapping", "sympy/printing/tests/test_fcode.py::test_fcode_precedence", "sympy/printing/tests/test_fcode.py::test_fcode_Logical", "sympy/printing/tests/test_fcode.py::test_fcode_Xlogical", "sympy/printing/tests/test_fcode.py::test_fcode_Relational", "sympy/printing/tests/test_fcode.py::test_fcode_Piecewise", "sympy/printing/tests/test_fcode.py::test_wrap_fortran", "sympy/printing/tests/test_fcode.py::test_wrap_fortran_keep_d0", "sympy/printing/tests/test_fcode.py::test_settings", "sympy/printing/tests/test_fcode.py::test_free_form_code_line", "sympy/printing/tests/test_fcode.py::test_free_form_continuation_line", "sympy/printing/tests/test_fcode.py::test_free_form_comment_line", "sympy/printing/tests/test_fcode.py::test_loops", "sympy/printing/tests/test_fcode.py::test_dummy_loops", "sympy/printing/tests/test_fcode.py::test_fcode_Indexed_without_looking_for_contraction", "sympy/printing/tests/test_fcode.py::test_derived_classes", "sympy/printing/tests/test_fcode.py::test_indent", "sympy/printing/tests/test_jscode.py::test_printmethod", "sympy/printing/tests/test_jscode.py::test_jscode_sqrt", "sympy/printing/tests/test_jscode.py::test_jscode_Pow", "sympy/printing/tests/test_jscode.py::test_jscode_constants_mathh", "sympy/printing/tests/test_jscode.py::test_jscode_constants_other", "sympy/printing/tests/test_jscode.py::test_jscode_Rational", "sympy/printing/tests/test_jscode.py::test_jscode_Integer", "sympy/printing/tests/test_jscode.py::test_jscode_functions", "sympy/printing/tests/test_jscode.py::test_jscode_inline_function", "sympy/printing/tests/test_jscode.py::test_jscode_exceptions", "sympy/printing/tests/test_jscode.py::test_jscode_boolean", "sympy/printing/tests/test_jscode.py::test_jscode_Piecewise", "sympy/printing/tests/test_jscode.py::test_jscode_Piecewise_deep", "sympy/printing/tests/test_jscode.py::test_jscode_settings", "sympy/printing/tests/test_jscode.py::test_jscode_Indexed", "sympy/printing/tests/test_jscode.py::test_jscode_loops_matrix_vector", "sympy/printing/tests/test_jscode.py::test_dummy_loops", "sympy/printing/tests/test_jscode.py::test_jscode_loops_add", "sympy/printing/tests/test_jscode.py::test_jscode_loops_multiple_contractions", "sympy/printing/tests/test_jscode.py::test_jscode_loops_addfactor", "sympy/printing/tests/test_jscode.py::test_jscode_loops_multiple_terms", "sympy/sets/tests/test_sets.py::test_imageset", "sympy/sets/tests/test_sets.py::test_interval_arguments", "sympy/sets/tests/test_sets.py::test_interval_symbolic_end_points", "sympy/sets/tests/test_sets.py::test_union", "sympy/sets/tests/test_sets.py::test_union_iter", "sympy/sets/tests/test_sets.py::test_difference", "sympy/sets/tests/test_sets.py::test_Complement", "sympy/sets/tests/test_sets.py::test_complement", "sympy/sets/tests/test_sets.py::test_intersect", "sympy/sets/tests/test_sets.py::test_intersection", "sympy/sets/tests/test_sets.py::test_issue_9623", "sympy/sets/tests/test_sets.py::test_is_disjoint", "sympy/sets/tests/test_sets.py::test_ProductSet_of_single_arg_is_arg", "sympy/sets/tests/test_sets.py::test_interval_subs", "sympy/sets/tests/test_sets.py::test_interval_to_mpi", "sympy/sets/tests/test_sets.py::test_measure", "sympy/sets/tests/test_sets.py::test_is_subset", "sympy/sets/tests/test_sets.py::test_is_proper_subset", "sympy/sets/tests/test_sets.py::test_is_superset", "sympy/sets/tests/test_sets.py::test_is_proper_superset", "sympy/sets/tests/test_sets.py::test_contains", "sympy/sets/tests/test_sets.py::test_interval_symbolic", "sympy/sets/tests/test_sets.py::test_union_contains", "sympy/sets/tests/test_sets.py::test_is_number", "sympy/sets/tests/test_sets.py::test_Interval_is_left_unbounded", "sympy/sets/tests/test_sets.py::test_Interval_is_right_unbounded", "sympy/sets/tests/test_sets.py::test_Interval_as_relational", "sympy/sets/tests/test_sets.py::test_Finite_as_relational", "sympy/sets/tests/test_sets.py::test_Union_as_relational", "sympy/sets/tests/test_sets.py::test_Intersection_as_relational", "sympy/sets/tests/test_sets.py::test_EmptySet", "sympy/sets/tests/test_sets.py::test_finite_basic", "sympy/sets/tests/test_sets.py::test_powerset", "sympy/sets/tests/test_sets.py::test_product_basic", "sympy/sets/tests/test_sets.py::test_real", "sympy/sets/tests/test_sets.py::test_supinf", "sympy/sets/tests/test_sets.py::test_universalset", "sympy/sets/tests/test_sets.py::test_Union_of_ProductSets_shares", "sympy/sets/tests/test_sets.py::test_Interval_free_symbols", "sympy/sets/tests/test_sets.py::test_image_interval", "sympy/sets/tests/test_sets.py::test_image_piecewise", "sympy/sets/tests/test_sets.py::test_image_FiniteSet", "sympy/sets/tests/test_sets.py::test_image_Union", "sympy/sets/tests/test_sets.py::test_image_EmptySet", "sympy/sets/tests/test_sets.py::test_issue_5724_7680", "sympy/sets/tests/test_sets.py::test_boundary", "sympy/sets/tests/test_sets.py::test_boundary_Union", "sympy/sets/tests/test_sets.py::test_boundary_ProductSet", "sympy/sets/tests/test_sets.py::test_boundary_ProductSet_line", "sympy/sets/tests/test_sets.py::test_is_open", "sympy/sets/tests/test_sets.py::test_is_closed", "sympy/sets/tests/test_sets.py::test_closure", "sympy/sets/tests/test_sets.py::test_interior", "sympy/sets/tests/test_sets.py::test_issue_7841", "sympy/sets/tests/test_sets.py::test_Eq", "sympy/sets/tests/test_sets.py::test_SymmetricDifference", "sympy/sets/tests/test_sets.py::test_issue_9536", "sympy/sets/tests/test_sets.py::test_issue_9637", "sympy/sets/tests/test_sets.py::test_issue_9808", "sympy/sets/tests/test_sets.py::test_issue_9956", "sympy/sets/tests/test_sets.py::test_issue_Symbol_inter", "sympy/sets/tests/test_sets.py::test_issue_10113", "sympy/sets/tests/test_sets.py::test_issue_10248", "sympy/sets/tests/test_sets.py::test_issue_9447", "sympy/sets/tests/test_sets.py::test_issue_10337", "sympy/sets/tests/test_sets.py::test_issue_10326", "sympy/sets/tests/test_sets.py::test_issue_9706", "sympy/sets/tests/test_sets.py::test_issue_10285", "sympy/sets/tests/test_sets.py::test_issue_10931", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp1", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp1a", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp2", "sympy/simplify/tests/test_trigsimp.py::test_issue_4373", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp3", "sympy/simplify/tests/test_trigsimp.py::test_issue_4661", "sympy/simplify/tests/test_trigsimp.py::test_issue_4494", "sympy/simplify/tests/test_trigsimp.py::test_issue_5948", "sympy/simplify/tests/test_trigsimp.py::test_issue_4775", "sympy/simplify/tests/test_trigsimp.py::test_issue_4280", "sympy/simplify/tests/test_trigsimp.py::test_issue_3210", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp_issues", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp_issue_2515", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp_issue_3826", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp_issue_4032", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp_issue_7761", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp_noncommutative", "sympy/simplify/tests/test_trigsimp.py::test_hyperbolic_simp", "sympy/simplify/tests/test_trigsimp.py::test_trigsimp_groebner", "sympy/simplify/tests/test_trigsimp.py::test_issue_2827_trigsimp_methods", "sympy/simplify/tests/test_trigsimp.py::test_exptrigsimp", "sympy/simplify/tests/test_trigsimp.py::test_powsimp_on_numbers", "sympy/simplify/tests/test_trigsimp.py::test_Piecewise", "sympy/solvers/tests/test_diophantine.py::test_input_format", "sympy/solvers/tests/test_diophantine.py::test_univariate", "sympy/solvers/tests/test_diophantine.py::test_classify_diop", "sympy/solvers/tests/test_diophantine.py::test_linear", "sympy/solvers/tests/test_diophantine.py::test_quadratic_simple_hyperbolic_case", "sympy/solvers/tests/test_diophantine.py::test_quadratic_elliptical_case", "sympy/solvers/tests/test_diophantine.py::test_quadratic_parabolic_case", "sympy/solvers/tests/test_diophantine.py::test_quadratic_perfect_square", "sympy/solvers/tests/test_diophantine.py::test_bf_pell", "sympy/solvers/tests/test_diophantine.py::test_length", "sympy/solvers/tests/test_diophantine.py::test_transformation_to_pell", "sympy/solvers/tests/test_diophantine.py::test_find_DN", "sympy/solvers/tests/test_diophantine.py::test_ldescent", "sympy/solvers/tests/test_diophantine.py::test_transformation_to_normal", "sympy/solvers/tests/test_diophantine.py::test_square_factor", "sympy/solvers/tests/test_diophantine.py::test_parametrize_ternary_quadratic", "sympy/solvers/tests/test_diophantine.py::test_no_square_ternary_quadratic", "sympy/solvers/tests/test_diophantine.py::test_diophantine", "sympy/solvers/tests/test_diophantine.py::test_general_pythagorean", "sympy/solvers/tests/test_diophantine.py::test_diop_general_sum_of_squares_quick", "sympy/solvers/tests/test_diophantine.py::test_diop_partition", "sympy/solvers/tests/test_diophantine.py::test_prime_as_sum_of_two_squares", "sympy/solvers/tests/test_diophantine.py::test_sum_of_three_squares", "sympy/solvers/tests/test_diophantine.py::test_sum_of_four_squares", "sympy/solvers/tests/test_diophantine.py::test_power_representation", "sympy/solvers/tests/test_diophantine.py::test_assumptions", "sympy/solvers/tests/test_diophantine.py::test_holzer", "sympy/solvers/tests/test_diophantine.py::test_issue_9539", "sympy/solvers/tests/test_diophantine.py::test__can_do_sum_of_squares", "sympy/solvers/tests/test_diophantine.py::test_issue_9538", "sympy/stats/tests/test_symbolic_probability.py::test_literal_probability", "sympy/tensor/tests/test_tensor.py::test_canonicalize_no_slot_sym", "sympy/tensor/tests/test_tensor.py::test_canonicalize_no_dummies", "sympy/tensor/tests/test_tensor.py::test_no_metric_symmetry", "sympy/tensor/tests/test_tensor.py::test_canonicalize1", "sympy/tensor/tests/test_tensor.py::test_bug_correction_tensor_indices", "sympy/tensor/tests/test_tensor.py::test_riemann_invariants", "sympy/tensor/tests/test_tensor.py::test_riemann_products", "sympy/tensor/tests/test_tensor.py::test_canonicalize2", "sympy/tensor/tests/test_tensor.py::test_canonicalize3", "sympy/tensor/tests/test_tensor.py::test_TensorIndexType", "sympy/tensor/tests/test_tensor.py::test_indices", "sympy/tensor/tests/test_tensor.py::test_tensorsymmetry", "sympy/tensor/tests/test_tensor.py::test_TensorType", "sympy/tensor/tests/test_tensor.py::test_TensExpr", "sympy/tensor/tests/test_tensor.py::test_TensorHead", "sympy/tensor/tests/test_tensor.py::test_add1", "sympy/tensor/tests/test_tensor.py::test_special_eq_ne", "sympy/tensor/tests/test_tensor.py::test_add2", "sympy/tensor/tests/test_tensor.py::test_mul", "sympy/tensor/tests/test_tensor.py::test_substitute_indices", "sympy/tensor/tests/test_tensor.py::test_riemann_cyclic_replace", "sympy/tensor/tests/test_tensor.py::test_riemann_cyclic", "sympy/tensor/tests/test_tensor.py::test_div", "sympy/tensor/tests/test_tensor.py::test_contract_metric1", "sympy/tensor/tests/test_tensor.py::test_contract_metric2", "sympy/tensor/tests/test_tensor.py::test_metric_contract3", "sympy/tensor/tests/test_tensor.py::test_epsilon", "sympy/tensor/tests/test_tensor.py::test_contract_delta1", "sympy/tensor/tests/test_tensor.py::test_fun", "sympy/tensor/tests/test_tensor.py::test_TensorManager", "sympy/tensor/tests/test_tensor.py::test_hash", "sympy/tensor/tests/test_tensor.py::test_hidden_indices_for_matrix_multiplication", "sympy/tensor/tests/test_tensor.py::test_valued_metric_inverse", "sympy/tensor/tests/test_tensor.py::test_valued_canon_bp_swapaxes", "sympy/tensor/tests/test_tensor.py::test_pprint", "sympy/tensor/tests/test_tensor.py::test_contract_automatrix_and_data", "sympy/tensor/tests/test_tensor.py::test_valued_components_with_wrong_symmetry", "sympy/tensor/tests/test_tensor.py::test_issue_10972_TensMul_data", "sympy/tensor/tests/test_tensor.py::test_TensMul_data" ]
[]
BSD
526
yola__yoconfigurator-35
54e4dfdba21ae87e08db9621ef2c2f4fb1a9e6cf
2016-05-09 21:59:46
54e4dfdba21ae87e08db9621ef2c2f4fb1a9e6cf
diff --git a/.travis.yml b/.travis.yml index 5a893c1..07aa865 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,8 @@ language: python python: - - "2.6" - "2.7" -install: - - pip install -r requirements.txt --use-mirrors + - "3.2" + - "3.3" + - "3.4" + - "3.5" script: python setup.py test diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2f7e009..a3529c9 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,12 @@ Change Log ========== +Dev +----- + +* Update to work with Python 2.7, 3.2, 3.3, 3.4, 3.5 +* Drop support for Python <= 2.6 + 0.4.6 ----- diff --git a/requirements.txt b/requirements.txt index 05bf2df..e69de29 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +0,0 @@ -# Only for tests on Python < 2.7: -argparse -unittest2 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..2a9acf1 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal = 1 diff --git a/setup.py b/setup.py index a7d8dbe..51b1d62 100755 --- a/setup.py +++ b/setup.py @@ -1,12 +1,7 @@ #!/usr/bin/env python -import sys - from setuptools import setup, find_packages -install_requires = [] -if sys.version_info < (2, 7): - install_requires.append('argparse') setup( name='yoconfigurator', @@ -18,6 +13,21 @@ setup( version='0.4.6', packages=find_packages(), scripts=['bin/configurator.py'], - install_requires=install_requires, test_suite='yoconfigurator.tests', + classifiers=[ + 'Development Status :: 4 - Beta', + 'Environment :: Console', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Topic :: Utilities', + ] ) diff --git a/yoconfigurator/base.py b/yoconfigurator/base.py index 546ae41..f339b95 100644 --- a/yoconfigurator/base.py +++ b/yoconfigurator/base.py @@ -1,15 +1,26 @@ -import imp import json import os +import types import sys from yoconfigurator.dicts import DotDict, MissingValue +try: + # SourceFileLoader added in Python 3.3 + from importlib.machinery import SourceFileLoader +except ImportError: + # imp.load_source deprecated in Python 3.3 + from imp import load_source + _load_module = load_source +else: + def _load_module(module_name, file_name): + return SourceFileLoader(module_name, file_name).load_module() + class DetectMissingEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, MissingValue): - raise ValueError("Missing Value found in config: %s" % obj.name) + raise ValueError('Missing Value found in config: %s' % obj.name) return super(DetectMissingEncoder, self).default(obj) @@ -32,7 +43,7 @@ def get_config_module(config_pathname): """Imports the config file to yoconfigurator.configs.<config_basename>.""" configs_mod = 'yoconfigurator.configs' if configs_mod not in sys.modules: - sys.modules[configs_mod] = imp.new_module(configs_mod) - module_name = os.path.basename(config_pathname).rsplit('.', 1)[-1] + sys.modules[configs_mod] = types.ModuleType(configs_mod) + module_name = os.path.basename(config_pathname).rsplit('.', 1)[0] module_name = configs_mod + '.' + module_name - return imp.load_source(module_name, config_pathname) + return _load_module(module_name, config_pathname) diff --git a/yoconfigurator/credentials.py b/yoconfigurator/credentials.py index 8ef29f9..e703222 100644 --- a/yoconfigurator/credentials.py +++ b/yoconfigurator/credentials.py @@ -4,5 +4,5 @@ import hashlib def seeded_auth_token(client, service, seed): """Return an auth token based on the client+service+seed tuple.""" hash_func = hashlib.md5() - hash_func.update(','.join((client, service, seed))) + hash_func.update(b','.join((client, service, seed))) return hash_func.hexdigest() diff --git a/yoconfigurator/dicts.py b/yoconfigurator/dicts.py index 9a3e8c2..d3cfbaf 100644 --- a/yoconfigurator/dicts.py +++ b/yoconfigurator/dicts.py @@ -15,7 +15,7 @@ class DotDict(dict): def __init__(self, *args, **kwargs): super(DotDict, self).__init__(*args, **kwargs) - for key, value in self.iteritems(): + for key, value in self.items(): self[key] = self._convert_item(value) def __setitem__(self, dottedkey, value): @@ -90,10 +90,10 @@ class MissingValue(object): self.name = name def __getattr__(self, k): - raise AttributeError("No value provided for %s" % self.name) + raise AttributeError('No value provided for %s' % self.name) def get(self, k, default=None): - raise KeyError("No value provided for %s" % self.name) + raise KeyError('No value provided for %s' % self.name) __getitem__ = get @@ -109,7 +109,7 @@ def merge_dicts(d1, d2, _path=None): if _path is None: _path = () if isinstance(d1, dict) and isinstance(d2, dict): - for k, v in d2.iteritems(): + for k, v in d2.items(): if isinstance(v, MissingValue) and v.name is None: v.name = '.'.join(_path + (k,))
Make it Python 3.x compatible We'll need it for our new project (which will be run under Python 3.x)
yola/yoconfigurator
diff --git a/yoconfigurator/tests/__init__.py b/yoconfigurator/tests/__init__.py index 68116d5..e69de29 100644 --- a/yoconfigurator/tests/__init__.py +++ b/yoconfigurator/tests/__init__.py @@ -1,6 +0,0 @@ -import sys - -if sys.version_info >= (2, 7): - import unittest -else: - import unittest2 as unittest diff --git a/yoconfigurator/tests/samples/public-config/deploy/configuration/public-data.py b/yoconfigurator/tests/samples/public-config/deploy/configuration/public-data.py index ac49920..7f14363 100644 --- a/yoconfigurator/tests/samples/public-config/deploy/configuration/public-data.py +++ b/yoconfigurator/tests/samples/public-config/deploy/configuration/public-data.py @@ -6,8 +6,8 @@ from yoconfigurator.dicts import filter_dict def filter(config): """The subset of configuration keys to be made public.""" keys = [ - "myapp.hello", - "myapp.some.deeply.nested.value", - "myapp.oz" + 'myapp.hello', + 'myapp.some.deeply.nested.value', + 'myapp.oz' ] return filter_dict(config, keys) diff --git a/yoconfigurator/tests/test_base.py b/yoconfigurator/tests/test_base.py index 6a33f03..4aff504 100644 --- a/yoconfigurator/tests/test_base.py +++ b/yoconfigurator/tests/test_base.py @@ -1,13 +1,12 @@ import json import os import shutil +import unittest from tempfile import mkdtemp from ..base import DetectMissingEncoder, read_config, write_config from ..dicts import merge_dicts, MissingValue -from . import unittest - class TestDetectMissingEncoder(unittest.TestCase): """Not part of the public API""" diff --git a/yoconfigurator/tests/test_configurator.py b/yoconfigurator/tests/test_configurator.py index b99b63b..92f3d61 100644 --- a/yoconfigurator/tests/test_configurator.py +++ b/yoconfigurator/tests/test_configurator.py @@ -2,8 +2,7 @@ import json import os import subprocess import sys - -from yoconfigurator.tests import unittest +import unittest class TestConfigurator(unittest.TestCase): @@ -29,7 +28,7 @@ class TestConfigurator(unittest.TestCase): stderr=subprocess.PIPE, env=env) out, err = p.communicate() self.assertEqual(p.wait(), 0) - self.assertEqual(err, '') + self.assertEqual(err, b'') def tearDown(self): os.remove(self.pub_conf) @@ -43,24 +42,24 @@ class TestConfigurator(unittest.TestCase): def test_creates_a_config_that_looks_as_expected(self): expected = { - "yoconfigurator": { - "app": "myapp" + 'yoconfigurator': { + 'app': 'myapp' }, - "myapp": { - "secret": "sauce", - "some": { - "deeply": { - "nested": { - "value": "Stefano likes beer" + 'myapp': { + 'secret': 'sauce', + 'some': { + 'deeply': { + 'nested': { + 'value': 'Stefano likes beer' } } }, - "hello": "world", - "oz": { - "bears": True, - "tigers": True, - "lions": True, - "zebras": False + 'hello': 'world', + 'oz': { + 'bears': True, + 'tigers': True, + 'lions': True, + 'zebras': False } } } diff --git a/yoconfigurator/tests/test_credentials.py b/yoconfigurator/tests/test_credentials.py index 01c8438..4daa915 100644 --- a/yoconfigurator/tests/test_credentials.py +++ b/yoconfigurator/tests/test_credentials.py @@ -1,9 +1,9 @@ -from . import unittest +import unittest from ..credentials import seeded_auth_token class TestSeededAuthToken(unittest.TestCase): def test_seeded_auth(self): - self.assertEqual(seeded_auth_token('foo', 'bar', 'baz'), + self.assertEqual(seeded_auth_token(b'foo', b'bar', b'baz'), '5a9350198f854de4b2ab56f187f87707') diff --git a/yoconfigurator/tests/test_dicts.py b/yoconfigurator/tests/test_dicts.py index 626fa77..9682991 100644 --- a/yoconfigurator/tests/test_dicts.py +++ b/yoconfigurator/tests/test_dicts.py @@ -1,20 +1,14 @@ import copy +import unittest from yoconfigurator.dicts import (DeletedValue, DotDict, MissingValue, filter_dict, merge_dicts) -from yoconfigurator.tests import unittest class DotDictTestCase(unittest.TestCase): - @classmethod - def setUpClass(cls): - # Python < 2.7 compatibility: - if not hasattr(cls, 'assertIsInstance'): - cls.assertIsInstance = lambda self, a, b: self.assertTrue( - isinstance(a, b)) def test_create(self): - 'ensure that we support all dict creation methods' + """Ensure that we support all dict creation methods""" by_attr = DotDict(one=1, two=2) by_dict = DotDict({'one': 1, 'two': 2}) by_list = DotDict([['one', 1], ['two', 2]]) @@ -22,30 +16,30 @@ class DotDictTestCase(unittest.TestCase): self.assertEqual(by_attr, by_list) def test_create_tree(self): - 'ensure that nested dicts are converted to DotDicts' + """Ensure that nested dicts are converted to DotDicts""" tree = DotDict({'foo': {'bar': True}}) self.assertIsInstance(tree['foo'], DotDict) def test_list_of_dicts(self): - 'ensure that nested dicts insied lists are converted to DotDicts' + """Ensure that nested dicts insied lists are converted to DotDicts""" tree = DotDict({'foo': [{'bar': True}]}) self.assertIsInstance(tree['foo'][0], DotDict) def test_mutablity(self): - 'ensure that the whole tree is mutable' + """Ensure that the whole tree is mutable""" tree = DotDict({'foo': {'bar': True}}) self.assertTrue(tree.foo.bar) tree.foo.bar = False self.assertFalse(tree.foo.bar) def test_setdefault(self): - 'ensure that the setdefault works' + """Ensure that the setdefault works""" tree = DotDict({'foo': 'bar'}) tree.setdefault('baz', {}) self.assertIsInstance(tree.baz, DotDict) def test_update(self): - 'ensure that update works' + """Ensure that update works""" tree = DotDict({'foo': 'bar'}) tree.update({'foo': {}}) self.assertIsInstance(tree.foo, DotDict) @@ -55,17 +49,17 @@ class DotDictTestCase(unittest.TestCase): self.assertIsInstance(tree.baz, DotDict) def test_deepcopy(self): - 'ensure that DotDict can be deepcopied' + """Ensure that DotDict can be deepcopied""" tree = DotDict({'foo': 'bar'}) self.assertEqual(tree, copy.deepcopy(tree)) def test_get_dotted(self): - 'ensure that DotDict can get values using a dotted key' + """Ensure that DotDict can get values using a dotted key""" tree = DotDict({'foo': {'bar': {'baz': 'huzzah'}}}) self.assertEqual(tree['foo.bar.baz'], 'huzzah') def test_set_dotted(self): - 'ensure that DotDict can set values using a dotted key' + """Ensure that DotDict can set values using a dotted key""" tree = DotDict() tree['foo.bar.baz'] = 'huzzah' self.assertEqual(tree['foo.bar.baz'], 'huzzah') @@ -84,7 +78,7 @@ class TestMissingValue(unittest.TestCase): class TestMergeDicts(unittest.TestCase): def test_merge(self): - 'ensure that the new entries in B are merged into A' + """Ensure that the new entries in B are merged into A""" a = DotDict(a=1, b=1) b = DotDict(c=1) c = merge_dicts(a, b) @@ -93,14 +87,14 @@ class TestMergeDicts(unittest.TestCase): self.assertEqual(c.c, 1) def test_filter(self): - 'ensure that the subset of A is filtered out using keys' + """Ensure that the subset of A is filtered out using keys""" a = DotDict(a=1, b=1) keys = ['a'] b = filter_dict(a, keys) self.assertEqual(b, {'a': 1}) def test_replacement(self): - 'ensure that the new entries in B replace equivalents in A' + """Ensure that the new entries in B replace equivalents in A""" a = DotDict(a=1, b=1) b = DotDict(b=2) c = merge_dicts(a, b) @@ -108,7 +102,7 @@ class TestMergeDicts(unittest.TestCase): self.assertEqual(c.b, 2) def test_sub_merge(self): - 'ensure that a subtree from B is merged with the same subtree in A' + """Ensure that a subtree from B is merged with the same subtree in A""" a = DotDict(a=1, sub={'c': 1}) b = DotDict(b=2, sub={'d': 2}) c = merge_dicts(a, b) @@ -118,7 +112,7 @@ class TestMergeDicts(unittest.TestCase): self.assertEqual(c.sub.d, 2) def test_sub_replacement(self): - 'ensure that a subtree from B is merged with the same subtree in A' + """Ensure that a subtree from B is merged with the same subtree in A""" a = DotDict(a=1, sub={'c': 1}) b = DotDict(b=2, sub={'c': 2}) c = merge_dicts(a, b) @@ -127,7 +121,7 @@ class TestMergeDicts(unittest.TestCase): self.assertEqual(c.sub.c, 2) def test_replace_missing_with_dict(self): - 'ensure that a subtree from B replaces a MissingValue in A' + """Ensure that a subtree from B replaces a MissingValue in A""" a = DotDict(a=1, sub=MissingValue('sub')) b = DotDict(b=2, sub={'c': 2}) c = merge_dicts(a, b) @@ -136,21 +130,21 @@ class TestMergeDicts(unittest.TestCase): self.assertEqual(c.sub.c, 2) def test_unnamed_missing_value(self): - 'ensure that missing values get a name assigned' + """Ensure that missing values get a name assigned""" a = DotDict() b = DotDict(foo=MissingValue()) c = merge_dicts(a, b) self.assertEqual(c.foo.name, 'foo') def test_unnamed_missing_value_in_new_tree(self): - 'ensure that missing values in new sub-trees get a name assigned' + """Ensure that missing values in new sub-trees get a name assigned""" a = DotDict() b = DotDict(foo={'bar': MissingValue()}) c = merge_dicts(a, b) self.assertEqual(c.foo.bar.name, 'foo.bar') def test_merge_lists(self): - 'ensure that leaf lists are merged' + """Ensure that leaf lists are merged""" a = DotDict(a=1, sub=[1, 2]) b = DotDict(b=2, sub=[3, 4]) c = merge_dicts(a, b) @@ -159,7 +153,7 @@ class TestMergeDicts(unittest.TestCase): self.assertEqual(c.sub, [1, 2, 3, 4]) def test_merge_incompatible(self): - 'ensure that the merged items are of the same types' + """Ensure that the merged items are of the same types""" a = DotDict(foo=42) b = DotDict(foo='42') self.assertRaises(TypeError, merge_dicts, a, b) @@ -167,14 +161,14 @@ class TestMergeDicts(unittest.TestCase): self.assertRaises(TypeError, merge_dicts, a, b) def test_replace_none(self): - 'ensure that None can be replaced with another type' + """Ensure that None can be replaced with another type""" a = DotDict(foo=None) b = DotDict(foo='foo') c = merge_dicts(a, b) self.assertEqual(c, {'foo': 'foo'}) def test_deltedvalue(self): - 'ensure that deletedvalue deletes values' + """Ensure that deletedvalue deletes values""" a = DotDict(foo=42) b = DotDict(foo=DeletedValue()) c = merge_dicts(a, b) diff --git a/yoconfigurator/tests/test_script.py b/yoconfigurator/tests/test_script.py index 7207384..d7f61c3 100644 --- a/yoconfigurator/tests/test_script.py +++ b/yoconfigurator/tests/test_script.py @@ -1,8 +1,7 @@ import os import subprocess import sys - -from . import unittest +import unittest class TestScript(unittest.TestCase): @@ -18,4 +17,4 @@ class TestScript(unittest.TestCase): stderr=subprocess.PIPE, env=env) out, err = p.communicate() self.assertEqual(p.wait(), 0) - self.assertEqual(err, '') + self.assertEqual(err, b'') diff --git a/yoconfigurator/tests/test_smush.py b/yoconfigurator/tests/test_smush.py index 42af2d1..2bb9028 100644 --- a/yoconfigurator/tests/test_smush.py +++ b/yoconfigurator/tests/test_smush.py @@ -1,14 +1,13 @@ import json import os import shutil +import unittest from tempfile import mkdtemp from ..dicts import MissingValue from ..smush import (config_sources, available_sources, smush_config, LenientJSONEncoder) -from . import unittest - class TestLenientJSONEncoder(unittest.TestCase):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 6 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "unittest2", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 linecache2==1.0.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 six==1.17.0 tomli==2.2.1 traceback2==1.4.0 unittest2==1.1.0 -e git+https://github.com/yola/yoconfigurator.git@54e4dfdba21ae87e08db9621ef2c2f4fb1a9e6cf#egg=yoconfigurator
name: yoconfigurator channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - linecache2==1.0.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 - traceback2==1.4.0 - unittest2==1.1.0 prefix: /opt/conda/envs/yoconfigurator
[ "yoconfigurator/tests/test_base.py::TestReadWriteConfig::test_read_config", "yoconfigurator/tests/test_base.py::TestReadWriteConfig::test_substituted_missing_value", "yoconfigurator/tests/test_configurator.py::TestConfigurator::test_creates_a_config_json", "yoconfigurator/tests/test_configurator.py::TestConfigurator::test_creates_a_config_that_looks_as_expected", "yoconfigurator/tests/test_configurator.py::TestConfigurator::test_creates_a_public_config", "yoconfigurator/tests/test_configurator.py::TestConfigurator::test_creates_a_public_config_that_does_not_contain_a_secret", "yoconfigurator/tests/test_configurator.py::TestConfigurator::test_creates_a_public_config_that_looks_as_expected", "yoconfigurator/tests/test_credentials.py::TestSeededAuthToken::test_seeded_auth", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_create", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_create_tree", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_deepcopy", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_get_dotted", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_list_of_dicts", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_mutablity", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_set_dotted", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_setdefault", "yoconfigurator/tests/test_dicts.py::DotDictTestCase::test_update", "yoconfigurator/tests/test_dicts.py::TestMissingValue::test_attribute_access", "yoconfigurator/tests/test_dicts.py::TestMissingValue::test_dict_access", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_deltedvalue", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_filter", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_merge", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_merge_incompatible", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_merge_lists", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_replace_missing_with_dict", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_replace_none", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_replacement", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_sub_merge", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_sub_replacement", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_unnamed_missing_value", "yoconfigurator/tests/test_dicts.py::TestMergeDicts::test_unnamed_missing_value_in_new_tree", "yoconfigurator/tests/test_smush.py::TestSmush::test_initial", "yoconfigurator/tests/test_smush.py::TestSmush::test_missing_value", "yoconfigurator/tests/test_smush.py::TestSmush::test_multiple", "yoconfigurator/tests/test_smush.py::TestSmush::test_nop", "yoconfigurator/tests/test_smush.py::TestSmush::test_single" ]
[]
[ "yoconfigurator/tests/test_base.py::TestDetectMissingEncoder::test_encode", "yoconfigurator/tests/test_base.py::TestDetectMissingEncoder::test_missing", "yoconfigurator/tests/test_base.py::TestDetectMissingEncoder::test_other", "yoconfigurator/tests/test_base.py::TestReadWriteConfig::test_missing_value", "yoconfigurator/tests/test_base.py::TestReadWriteConfig::test_write_config", "yoconfigurator/tests/test_script.py::TestScript::test_help", "yoconfigurator/tests/test_smush.py::TestLenientJSONEncoder::test_encode", "yoconfigurator/tests/test_smush.py::TestLenientJSONEncoder::test_missing", "yoconfigurator/tests/test_smush.py::TestLenientJSONEncoder::test_unencodable", "yoconfigurator/tests/test_smush.py::TestConfigSources::test_available_sources", "yoconfigurator/tests/test_smush.py::TestConfigSources::test_build_implies_local", "yoconfigurator/tests/test_smush.py::TestConfigSources::test_build_source_order", "yoconfigurator/tests/test_smush.py::TestConfigSources::test_local_source_order", "yoconfigurator/tests/test_smush.py::TestConfigSources::test_multiple_config_dirs", "yoconfigurator/tests/test_smush.py::TestConfigSources::test_override_config_dirs", "yoconfigurator/tests/test_smush.py::TestConfigSources::test_source_order" ]
[]
MIT License
527
adamtheturtle__chroot_tasker-39
7b0b5a74595f65c1b615da9365dea300435181b7
2016-05-09 22:15:22
7b0b5a74595f65c1b615da9365dea300435181b7
diff --git a/README.rst b/README.rst index ed34f92..b95f329 100644 --- a/README.rst +++ b/README.rst @@ -67,8 +67,8 @@ To use ``tasker``: # An image to download, extract and create a chroot jail in. image_url = 'http://example.com/image.tar' - # The image will be downloaded and extracted into the parent. - parent = pathlib.Path(os.getcwd()) + # The image will be downloaded and extracted into the download_path. + download_path = pathlib.Path(os.getcwd()) # See ``args`` at # https://docs.python.org/2/library/subprocess.html#subprocess.Popen @@ -77,7 +77,7 @@ To use ``tasker``: task = Task( image_url=image_url, args=args, - parent=parent, + download_path=download_path, ) pid = task.process.pid diff --git a/cli/cli.py b/cli/cli.py index 4171093..c3e9b51 100644 --- a/cli/cli.py +++ b/cli/cli.py @@ -28,6 +28,6 @@ def create(image_url, args): task = Task( image_url=image_url, args=args.split(), - parent=pathlib.Path(os.getcwd()), + download_path=pathlib.Path(os.getcwd()), ) print(task.process.pid) diff --git a/tasker/tasker.py b/tasker/tasker.py index b1c4588..3ae608f 100644 --- a/tasker/tasker.py +++ b/tasker/tasker.py @@ -12,14 +12,14 @@ import uuid import pathlib -def _create_filesystem_dir(image_url, parent): +def _create_filesystem_dir(image_url, download_path): """ - Download a ``.tar`` file, extract it into ``parent`` and delete the + Download a ``.tar`` file, extract it into ``download_path`` and delete the ``.tar`` file. :param str image_url: The url of a ``.tar`` file. - :param pathlib.Path parent: The parent to extract the downloaded image - into. + :param pathlib.Path download_path: The parent to extract the downloaded + image into. :rtype: pathlib.Path :returns: The path to the extracted image. @@ -27,12 +27,12 @@ def _create_filesystem_dir(image_url, parent): image = urllib.request.urlopen(image_url) # Use ``image.url`` below instead of image_url in case of a redirect. image_path = pathlib.Path(urllib.parse.urlparse(image.url).path) - tar_file = parent.joinpath(image_path.name) + tar_file = download_path.joinpath(image_path.name) with open(str(tar_file), 'wb') as tf: tf.write(image.read()) unique_id = uuid.uuid4().hex - filesystem_path = parent.joinpath(image_path.stem + unique_id) + filesystem_path = download_path.joinpath(image_path.stem + unique_id) with tarfile.open(str(tar_file)) as tf: tf.extractall(str(filesystem_path)) @@ -70,14 +70,14 @@ class Task(object): A process in a chroot jail. """ - def __init__(self, image_url, args, parent): + def __init__(self, image_url, args, download_path): """ Create a new task. """ filesystem = _create_filesystem_dir( image_url=image_url, - parent=parent, + download_path=download_path, ) self.process = _run_chroot_process( filesystem=filesystem,
Remove unused stdio options
adamtheturtle/chroot_tasker
diff --git a/tasker/tests/test_tasker.py b/tasker/tests/test_tasker.py index 20cf016..90fb351 100644 --- a/tasker/tests/test_tasker.py +++ b/tasker/tests/test_tasker.py @@ -38,14 +38,14 @@ class TestCreateFilestystemDir(object): def test_filesystem_dir_created(self, tmpdir): """ The given ``.tar`` file is downloaded and extracted to the given - parent. + download path. """ image_url = self._create_tarfile(tmpdir=tmpdir.mkdir('server')) client = pathlib.Path(tmpdir.mkdir('client').strpath) extracted_filesystem = _create_filesystem_dir( image_url=image_url, - parent=client, + download_path=client, ) assert extracted_filesystem.parent == client @@ -60,12 +60,12 @@ class TestCreateFilestystemDir(object): client = pathlib.Path(tmpdir.mkdir('client').strpath) extracted_filesystem_1 = _create_filesystem_dir( image_url=image_url, - parent=client, + download_path=client, ) extracted_filesystem_2 = _create_filesystem_dir( image_url=image_url, - parent=client, + download_path=client, ) assert extracted_filesystem_1 != extracted_filesystem_2 @@ -79,7 +79,7 @@ class TestCreateFilestystemDir(object): client = pathlib.Path(tmpdir.mkdir('client').strpath) extracted_filesystem = _create_filesystem_dir( image_url=image_url, - parent=client, + download_path=client, ) client_children = [item for item in client.iterdir()] @@ -98,7 +98,7 @@ class TestRunChrootProcess(object): """ filesystem = _create_filesystem_dir( image_url=ROOTFS_URI, - parent=pathlib.Path(tmpdir.strpath), + download_path=pathlib.Path(tmpdir.strpath), ) _run_chroot_process( @@ -118,7 +118,7 @@ class TestRunChrootProcess(object): """ filesystem = _create_filesystem_dir( image_url=ROOTFS_URI, - parent=pathlib.Path(tmpdir.strpath), + download_path=pathlib.Path(tmpdir.strpath), ) old_pids = psutil.pids() @@ -135,7 +135,7 @@ class TestRunChrootProcess(object): """ filesystem = _create_filesystem_dir( image_url=ROOTFS_URI, - parent=pathlib.Path(tmpdir.strpath), + download_path=pathlib.Path(tmpdir.strpath), ) process = _run_chroot_process( @@ -156,7 +156,9 @@ class TestTask(object): A task can be created which starts a new process running a given command. """ - args = ['echo', '1'] - parent = pathlib.Path(tmpdir.strpath) - task = Task(image_url=ROOTFS_URI, args=args, parent=parent) + task = Task( + image_url=ROOTFS_URI, + args=['echo', '1'], + download_path=pathlib.Path(tmpdir.strpath), + ) assert isinstance(task.process.pid, int)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 -e git+https://github.com/adamtheturtle/chroot_tasker.git@7b0b5a74595f65c1b615da9365dea300435181b7#egg=Chroot_Tasker click==6.6 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 exceptiongroup==1.2.2 flake8==7.2.0 idna==3.10 iniconfig==2.1.0 mccabe==0.7.0 packaging==24.2 pluggy==1.5.0 psutil==4.1.0 pycodestyle==2.13.0 pyflakes==3.3.2 pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 tomli==2.2.1 urllib3==2.3.0
name: chroot_tasker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==6.6 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - exceptiongroup==1.2.2 - flake8==7.2.0 - idna==3.10 - iniconfig==2.1.0 - mccabe==0.7.0 - packaging==24.2 - pluggy==1.5.0 - psutil==4.1.0 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/chroot_tasker
[ "tasker/tests/test_tasker.py::TestCreateFilestystemDir::test_filesystem_dir_created", "tasker/tests/test_tasker.py::TestCreateFilestystemDir::test_multiple_filesystems", "tasker/tests/test_tasker.py::TestCreateFilestystemDir::test_image_removed", "tasker/tests/test_tasker.py::TestRunChrootProcess::test_run_chroot_process", "tasker/tests/test_tasker.py::TestRunChrootProcess::test_process_returned", "tasker/tests/test_tasker.py::TestRunChrootProcess::test_default_io", "tasker/tests/test_tasker.py::TestTask::test_create_task" ]
[]
[]
[]
null
528
adamtheturtle__chroot_tasker-41
a11bb67cbc42ec7a8e05c1e501386e223d1d1e85
2016-05-10 14:54:33
a11bb67cbc42ec7a8e05c1e501386e223d1d1e85
diff --git a/README.rst b/README.rst index b95f329..0c24344 100644 --- a/README.rst +++ b/README.rst @@ -36,8 +36,16 @@ One way to use this is: .. code:: sh - $ sudo $(which tasker) create <IMAGE_URL> "<COMMANDS>" - 8935 # This is the PID of the new process. + # Root permissions are necessary to create the task. + $ sudo $(which tasker) create <IMAGE_URL> "sleep 100" + 8935 # This is the ID of the new task. + $ tasker health_check 8935 + exists: True + status: sleeping + $ sudo $(which tasker) send_signal SIGINT + $ tasker health_check 8935 + exists: False + status: None ``tasker`` downloads the image from the given ``<IMAGE_URL>`` into the current working directory. Also in the directory, the image is untarred to create a "filesystem". @@ -49,38 +57,42 @@ Library ``tasker`` is a Python library. -To install ``tasker``: +Installation +^^^^^^^^^^^^ .. code:: sh pip install -e . +API +^^^ + To use ``tasker``: .. code:: python import os import pathlib + import signal from tasker.tasker import Task - # An image to download, extract and create a chroot jail in. - image_url = 'http://example.com/image.tar' - - # The image will be downloaded and extracted into the download_path. - download_path = pathlib.Path(os.getcwd()) - - # See ``args`` at - # https://docs.python.org/2/library/subprocess.html#subprocess.Popen - args = ['echo', '1'] - task = Task( - image_url=image_url, - args=args, - download_path=download_path, + # An image to download, extract and create a chroot jail in. + image_url='http://example.com/image.tar', + # A command to run in the extracted filesystem. + args=['top'], + # Where the image will be downloaded and extracted into. + download_path=pathlib.Path(os.getcwd()), ) - pid = task.process.pid + task_health = task.get_health() + # {"running": True, "time": "0:46"} + + task.send_signal(signal.SIGTERM) + + task_health = task.get_health() + # {"running": False, "time": "0:46"} Supported platforms ------------------- @@ -108,7 +120,7 @@ In the Vagrant box, create a ``virtualenv``: .. code:: sh - mkvirtualenv -p python3.5 chroot_tasker + mkvirtualenv -p python3.5 tasker Install the test dependencies: @@ -152,4 +164,12 @@ There are at least three options for the directory in which to create the filesy The current implementation is (2). Ideally there would be multiple of the above, with (2) as the default. -The issue for this is https://github.com/adamtheturtle/chroot_tasker/issues/24. \ No newline at end of file +The issue for this is https://github.com/adamtheturtle/chroot_tasker/issues/24. + +Identifiers +^^^^^^^^^^^ + +This uses PIDs as identifiers. +This is not safe - PIDs get reused and so this could end up with a user manipulating the wrong process. +This was a simple to implement strategy. +A long term solution might be stateful and have a mapping of tasks to unique identifiers. diff --git a/cli/cli.py b/cli/cli.py index 5b4afaa..f5f414e 100644 --- a/cli/cli.py +++ b/cli/cli.py @@ -5,6 +5,7 @@ CLI for creating and interacting with tasks. import os import pathlib import shlex +from signal import Signals import click @@ -35,4 +36,33 @@ def create(image_url, args): args=shlex.split(args), download_path=pathlib.Path(os.getcwd()), ) - print(task.process.pid) + + print(task.id) + + [email protected]('health_check') [email protected]('task_id') +def health_check(task_id): + """ + Check the health of a task. + + :param str task_id: The id of an existing task. + """ + task = Task(existing_task=int(task_id)) + health = task.get_health() + print('exists: ' + str(health['exists'])) + print('status: ' + str(health['status'])) + + [email protected]('send_signal') [email protected]('task_id') [email protected]('signal') +def send_signal(task_id, signal): + """ + Send a signal to a process started by an existing task. + + :param str task_id: The id of an existing task. + :param str signal: The signal to send. + """ + task = Task(existing_task=int(task_id)) + task.send_signal(Signals[signal]) diff --git a/tasker/tasker.py b/tasker/tasker.py index b1e86c9..f475971 100644 --- a/tasker/tasker.py +++ b/tasker/tasker.py @@ -3,8 +3,10 @@ Create and interact with tasks in a chroot jail. """ import os +import psutil import subprocess import tarfile +import time import urllib.parse import urllib.request import uuid @@ -62,6 +64,12 @@ def _run_chroot_process(filesystem, args): os.fchdir(real_root) os.chroot(".") os.close(real_root) + + # On some platforms it seems to take some time for a process to start, + # even after this point. Therefore sleep for 5ms to ensure platform + # parity. This seems to be necessary on Travis CI hosted. + time.sleep(0.05) + return process @@ -70,7 +78,36 @@ class Task(object): A process in a chroot jail. """ - def __init__(self, image_url, args, download_path): + def get_health(self): + """ + Get details of the task's health. + + :rtype: dict + :returns: The task's process's status. + """ + if self._process is not None: + try: + status = self._process.status() + return {'exists': True, 'status': status} + except psutil.NoSuchProcess: + pass + + return {'exists': False, 'status': None} + + def send_signal(self, signal): + """ + Send a signal to the task's process. + + :param int signal: The signal to send. + """ + self._process.send_signal(signal) + try: + os.wait() + except OSError: # pragma: no cover + pass + + def __init__(self, image_url=None, args=None, download_path=None, + existing_task=None): """ Create a new task, which is a process running inside a chroot with root being a downloaded image's root. @@ -78,13 +115,29 @@ class Task(object): :param str image_url: The url of a ``.tar`` file. :param list args: List of strings. See ``subprocess.Popen.args``. :param pathlib.Path download_path: The parent to extract the downloaded - image into. + image into. + :param existing_task: The id of an existing task. If this is given, + other parameters are ignored and no new process is started. + + :ivar int id: An identifier for the task. """ - filesystem = _create_filesystem_dir( - image_url=image_url, - download_path=download_path, - ) - self.process = _run_chroot_process( - filesystem=filesystem, - args=args, - ) + if existing_task is not None: + try: + self._process = psutil.Process(existing_task) + except psutil.NoSuchProcess: + self._process = None + + self.id = existing_task + else: + filesystem = _create_filesystem_dir( + image_url=image_url, + download_path=download_path, + ) + + process = _run_chroot_process( + filesystem=filesystem, + args=args, + ) + + self.id = process.pid + self._process = psutil.Process(self.id)
Library function for sending signals Also think how this will be presented as part of the CLI.
adamtheturtle/chroot_tasker
diff --git a/cli/tests/test_cli.py b/cli/tests/test_cli.py index c84b10c..dea2867 100644 --- a/cli/tests/test_cli.py +++ b/cli/tests/test_cli.py @@ -4,12 +4,11 @@ Tests for ``cli.cli``. import os -import psutil - from click.testing import CliRunner from cli.cli import cli from common.testtools import ROOTFS_URI +from tasker.tasker import Task class TestCreate(object): @@ -26,12 +25,27 @@ class TestCreate(object): os.chdir(tmpdir.strpath) runner = CliRunner() - subcommand = 'create' - commands = 'sleep 10' - result = runner.invoke(cli, [subcommand, ROOTFS_URI, commands]) - process = psutil.Process(int(result.output)) - cmdline = process.cmdline() - process.kill() - + commands = 'sleep 5' + result = runner.invoke(cli, ['create', ROOTFS_URI, commands]) assert result.exit_code == 0 - assert cmdline == commands.split() + task = Task(existing_task=int(result.output)) + assert task._process.cmdline() == commands.split() + + def test_send_signal_healthcheck(self, tmpdir): + """ + Sending a SIGTERM signal to a task stops the process running. + The status before and after is relayed by the healthcheck function. + """ + # Change directory to temporary directory so as not to pollute current + # working directory with downloaded filesystem. + os.chdir(tmpdir.strpath) + + runner = CliRunner() + create = runner.invoke(cli, ['create', ROOTFS_URI, 'sleep 5']) + task_id = create.output + + before_int = runner.invoke(cli, ['health_check', task_id]) + assert before_int.output == 'exists: True\nstatus: sleeping\n' + runner.invoke(cli, ['send_signal', task_id, 'SIGINT']) + after_int = runner.invoke(cli, ['health_check', task_id]) + assert after_int.output == 'exists: False\nstatus: None\n' diff --git a/tasker/tests/test_tasker.py b/tasker/tests/test_tasker.py index 77eb1ae..a491625 100644 --- a/tasker/tests/test_tasker.py +++ b/tasker/tests/test_tasker.py @@ -2,8 +2,8 @@ Tests for ``tasker.tasker``. """ +import signal import tarfile -import time import pathlib import psutil @@ -106,8 +106,6 @@ class TestRunChrootProcess(object): args=['touch', '/example.txt'], ) - # ``touch`` takes a short time to work. - time.sleep(0.01) assert filesystem.joinpath('example.txt').exists() def test_process_returned(self, tmpdir): @@ -156,7 +154,36 @@ class TestTask(object): """ task = Task( image_url=ROOTFS_URI, - args=['echo', '1'], + args=['sleep', '5'], + download_path=pathlib.Path(tmpdir.strpath), + ) + + assert task.get_health() == {'exists': True, 'status': 'sleeping'} + + def test_send_signal(self, tmpdir): + """ + Sending a ``SIGINT`` signal to ``task.send_signal`` kills the child + process. + """ + task = Task( + image_url=ROOTFS_URI, + args=['sleep', '5'], download_path=pathlib.Path(tmpdir.strpath), ) - assert isinstance(task.process.pid, int) + task.send_signal(signal.SIGINT) + assert task.get_health() == {'exists': False, 'status': None} + + def test_existing_task(self, tmpdir): + """ + It is possible to get an existing task by its id. + """ + task = Task( + image_url=ROOTFS_URI, + args=['sleep', '5'], + download_path=pathlib.Path(tmpdir.strpath), + ) + + other_task = Task(existing_task=task.id) + # Interrupting one task interrupts the other, so they are the same task + task.send_signal(signal.SIGINT) + assert other_task.get_health() == {'exists': False, 'status': None}
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "flake8", "coveralls", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 -e git+https://github.com/adamtheturtle/chroot_tasker.git@a11bb67cbc42ec7a8e05c1e501386e223d1d1e85#egg=Chroot_Tasker click==6.6 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 exceptiongroup==1.2.2 flake8==7.2.0 idna==3.10 iniconfig==2.1.0 mccabe==0.7.0 packaging==24.2 pluggy==1.5.0 psutil==4.1.0 pycodestyle==2.13.0 pyflakes==3.3.2 pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 tomli==2.2.1 urllib3==2.3.0
name: chroot_tasker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==6.6 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - exceptiongroup==1.2.2 - flake8==7.2.0 - idna==3.10 - iniconfig==2.1.0 - mccabe==0.7.0 - packaging==24.2 - pluggy==1.5.0 - psutil==4.1.0 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/chroot_tasker
[ "cli/tests/test_cli.py::TestCreate::test_create_task", "cli/tests/test_cli.py::TestCreate::test_send_signal_healthcheck", "tasker/tests/test_tasker.py::TestTask::test_create", "tasker/tests/test_tasker.py::TestTask::test_send_signal", "tasker/tests/test_tasker.py::TestTask::test_existing_task" ]
[]
[ "tasker/tests/test_tasker.py::TestCreateFilestystemDir::test_filesystem_dir_created", "tasker/tests/test_tasker.py::TestCreateFilestystemDir::test_multiple_filesystems", "tasker/tests/test_tasker.py::TestCreateFilestystemDir::test_image_removed", "tasker/tests/test_tasker.py::TestRunChrootProcess::test_run_chroot_process", "tasker/tests/test_tasker.py::TestRunChrootProcess::test_process_returned", "tasker/tests/test_tasker.py::TestRunChrootProcess::test_default_io" ]
[]
null
529
dask__dask-1150
71e3e413d6e00942de3ff32a3ba378408f2648e9
2016-05-10 15:29:30
71e3e413d6e00942de3ff32a3ba378408f2648e9
diff --git a/dask/array/random.py b/dask/array/random.py index 71050b304..9a1b0b364 100644 --- a/dask/array/random.py +++ b/dask/array/random.py @@ -44,8 +44,13 @@ class RandomState(object): self._numpy_state.seed(seed) def _wrap(self, func, *args, **kwargs): + """ Wrap numpy random function to produce dask.array random function + + extra_chunks should be a chunks tuple to append to the end of chunks + """ size = kwargs.pop('size') chunks = kwargs.pop('chunks') + extra_chunks = kwargs.pop('extra_chunks', ()) if not isinstance(size, (tuple, list)): size = (size,) @@ -62,12 +67,13 @@ class RandomState(object): seeds = different_seeds(len(sizes), self._numpy_state) token = tokenize(seeds, size, chunks, args, kwargs) name = 'da.random.{0}-{1}'.format(func.__name__, token) - keys = product([name], *[range(len(bd)) for bd in chunks]) + keys = product([name], *([range(len(bd)) for bd in chunks] + + [[0]] * len(extra_chunks))) vals = ((_apply_random, func.__name__, seed, size, args, kwargs) for seed, size in zip(seeds, sizes)) dsk = dict(zip(keys, vals)) - return Array(dsk, name, chunks, dtype=dtype) + return Array(dsk, name, chunks + extra_chunks, dtype=dtype) @doc_wraps(np.random.RandomState.beta) def beta(self, a, b, size=None, chunks=None): @@ -144,7 +150,11 @@ class RandomState(object): return self._wrap(np.random.RandomState.logseries, p, size=size, chunks=chunks) - # multinomial + @doc_wraps(np.random.RandomState.multinomial) + def multinomial(self, n, pvals, size=None, chunks=None): + return self._wrap(np.random.RandomState.multinomial, n, pvals, + size=size, chunks=chunks, + extra_chunks=((len(pvals),),)) @doc_wraps(np.random.RandomState.negative_binomial) def negative_binomial(self, n, p, size=None, chunks=None): @@ -295,6 +305,7 @@ laplace = _state.laplace logistic = _state.logistic lognormal = _state.lognormal logseries = _state.logseries +multinomial = _state.multinomial negative_binomial = _state.negative_binomial noncentral_chisquare = _state.noncentral_chisquare noncentral_f = _state.noncentral_f
Multinomial random generator `dask/array/random.py` is missing a multinomial random generator (there is aplaceholder `# multinomial`). Will dask have a multinomial random generator at some point? Does it require a significantly different approach than the other generators?
dask/dask
diff --git a/dask/array/tests/test_random.py b/dask/array/tests/test_random.py index 855b200fd..1112a13ae 100644 --- a/dask/array/tests/test_random.py +++ b/dask/array/tests/test_random.py @@ -134,6 +134,7 @@ def test_random_all(): da.random.logistic(size=5, chunks=3).compute() da.random.lognormal(size=5, chunks=3).compute() da.random.logseries(0.5, size=5, chunks=3).compute() + da.random.multinomial(20, [1/6.]*6, size=5, chunks=3).compute() da.random.negative_binomial(5, 0.5, size=5, chunks=3).compute() da.random.noncentral_chisquare(2, 2, size=5, chunks=3).compute() @@ -159,3 +160,11 @@ def test_random_all(): da.random.standard_gamma(2, size=5, chunks=3).compute() da.random.standard_normal(size=5, chunks=3).compute() da.random.standard_t(2, size=5, chunks=3).compute() + + +def test_multinomial(): + for size, chunks in [(5, 3), ((5, 4), (2, 3))]: + x = da.random.multinomial(20, [1/6.]*6, size=size, chunks=chunks) + y = np.random.multinomial(20, [1/6.]*6, size=size) + + assert x.shape == y.shape == x.compute().shape
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 pandas>=1.0.0 cloudpickle partd distributed s3fs toolz psutil pytables bokeh bcolz scipy h5py ipython", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz liblzma-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore @ file:///opt/conda/conda-bld/aiobotocore_1643638228694/work aiohttp @ file:///tmp/build/80754af9/aiohttp_1632748060317/work aioitertools @ file:///tmp/build/80754af9/aioitertools_1607109665762/work async-timeout==3.0.1 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work bcolz==1.2.1 bokeh @ file:///tmp/build/80754af9/bokeh_1620710048147/work boto3==1.23.10 botocore==1.26.10 brotlipy==0.7.0 certifi==2021.5.30 cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work chardet @ file:///tmp/build/80754af9/chardet_1607706739153/work click==8.0.3 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1632508026186/work contextvars==2.4 cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work cytoolz==0.11.0 -e git+https://github.com/dask/dask.git@71e3e413d6e00942de3ff32a3ba378408f2648e9#egg=dask decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work distributed==1.9.5 fsspec @ file:///opt/conda/conda-bld/fsspec_1642510437511/work h5py==2.10.0 HeapDict @ file:///Users/ktietz/demo/mc3/conda-bld/heapdict_1630598515714/work idna @ file:///tmp/build/80754af9/idna_1637925883363/work idna-ssl @ file:///tmp/build/80754af9/idna_ssl_1611752490495/work immutables @ file:///tmp/build/80754af9/immutables_1628888996840/work importlib-metadata==4.8.3 iniconfig==1.1.1 ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work jmespath @ file:///Users/ktietz/demo/mc3/conda-bld/jmespath_1630583964805/work locket==0.2.1 MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work mock @ file:///tmp/build/80754af9/mock_1607622725907/work msgpack @ file:///tmp/build/80754af9/msgpack-python_1612287171716/work msgpack-python==0.5.6 multidict @ file:///tmp/build/80754af9/multidict_1607367768400/work numexpr @ file:///tmp/build/80754af9/numexpr_1618853194344/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 parso==0.7.0 partd @ file:///opt/conda/conda-bld/partd_1647245470509/work pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work pluggy==1.0.0 prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work psutil @ file:///tmp/build/80754af9/psutil_1612297621795/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl py==1.11.0 pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work pytest==7.0.1 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work pytz==2021.3 PyYAML==5.4.1 s3fs==0.4.2 s3transfer==0.5.2 scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work six @ file:///tmp/build/80754af9/six_1644875935023/work sortedcontainers @ file:///tmp/build/80754af9/sortedcontainers_1623949099177/work tables==3.6.1 tblib @ file:///Users/ktietz/demo/mc3/conda-bld/tblib_1629402031467/work tomli==1.2.3 toolz @ file:///tmp/build/80754af9/toolz_1636545406491/work tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work wrapt==1.12.1 yarl @ file:///tmp/build/80754af9/yarl_1606939915466/work zict==2.0.0 zipp==3.6.0
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - aiobotocore=2.1.0=pyhd3eb1b0_0 - aiohttp=3.7.4.post0=py36h7f8727e_2 - aioitertools=0.7.1=pyhd3eb1b0_0 - async-timeout=3.0.1=py36h06a4308_0 - attrs=21.4.0=pyhd3eb1b0_0 - backcall=0.2.0=pyhd3eb1b0_0 - bcolz=1.2.1=py36h04863e7_0 - blas=1.0=openblas - blosc=1.21.3=h6a678d5_0 - bokeh=2.3.2=py36h06a4308_0 - brotlipy=0.7.0=py36h27cfd23_1003 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - cffi=1.14.6=py36h400218f_0 - chardet=4.0.0=py36h06a4308_1003 - click=8.0.3=pyhd3eb1b0_0 - cloudpickle=2.0.0=pyhd3eb1b0_0 - contextvars=2.4=py_0 - cryptography=35.0.0=py36hd23ed53_0 - cytoolz=0.11.0=py36h7b6447c_0 - decorator=5.1.1=pyhd3eb1b0_0 - freetype=2.12.1=h4a9f257_0 - fsspec=2022.1.0=pyhd3eb1b0_0 - giflib=5.2.2=h5eee18b_0 - h5py=2.10.0=py36h7918eee_0 - hdf5=1.10.4=hb1b8bf9_0 - heapdict=1.0.1=pyhd3eb1b0_0 - idna=3.3=pyhd3eb1b0_0 - idna_ssl=1.1.0=py36h06a4308_0 - immutables=0.16=py36h7f8727e_0 - ipython=7.16.1=py36h5ca1d4c_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.17.2=py36h06a4308_1 - jinja2=3.0.3=pyhd3eb1b0_0 - jmespath=0.10.0=pyhd3eb1b0_0 - jpeg=9e=h5eee18b_3 - lcms2=2.16=hb9589c4_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h6a678d5_0 - libdeflate=1.22=h5eee18b_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtiff=4.5.1=hffd6297_1 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - locket=0.2.1=py36h06a4308_1 - lz4-c=1.9.4=h6a678d5_1 - lzo=2.10=h7b6447c_2 - markupsafe=2.0.1=py36h27cfd23_0 - mock=4.0.3=pyhd3eb1b0_0 - multidict=5.1.0=py36h27cfd23_2 - ncurses=6.4=h6a678d5_0 - numexpr=2.7.3=py36h4be448d_1 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pandas=1.1.5=py36ha9443f7_0 - parso=0.7.0=py_0 - partd=1.2.0=pyhd3eb1b0_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pillow=8.3.1=py36h5aabda8_0 - pip=21.2.2=py36h06a4308_0 - prompt-toolkit=3.0.20=pyhd3eb1b0_0 - psutil=5.8.0=py36h27cfd23_1 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.11.2=pyhd3eb1b0_0 - pyopenssl=22.0.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pysocks=1.7.1=py36h06a4308_0 - pytables=3.6.1=py36h71ec239_0 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytz=2021.3=pyhd3eb1b0_0 - pyyaml=5.4.1=py36h27cfd23_1 - readline=8.2=h5eee18b_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sortedcontainers=2.4.0=pyhd3eb1b0_0 - sqlite=3.45.3=h5eee18b_0 - tblib=1.7.0=pyhd3eb1b0_0 - tk=8.6.14=h39e8969_0 - toolz=0.11.2=pyhd3eb1b0_0 - tornado=6.1=py36h27cfd23_0 - traitlets=4.3.3=py36h06a4308_0 - typing-extensions=4.1.1=hd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - urllib3=1.26.8=pyhd3eb1b0_0 - wcwidth=0.2.5=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - wrapt=1.12.1=py36h7b6447c_1 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - yarl=1.6.3=py36h27cfd23_0 - zict=2.0.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - zstd=1.5.6=hc292b87_0 - pip: - boto3==1.23.10 - botocore==1.26.10 - distributed==1.9.5 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - msgpack-python==0.5.6 - pluggy==1.0.0 - py==1.11.0 - pytest==7.0.1 - s3fs==0.4.2 - s3transfer==0.5.2 - tomli==1.2.3 - zipp==3.6.0 prefix: /opt/conda/envs/dask
[ "dask/array/tests/test_random.py::test_random_all", "dask/array/tests/test_random.py::test_multinomial" ]
[]
[ "dask/array/tests/test_random.py::test_RandomState", "dask/array/tests/test_random.py::test_concurrency", "dask/array/tests/test_random.py::test_doc_randomstate", "dask/array/tests/test_random.py::test_serializability", "dask/array/tests/test_random.py::test_determinisim_through_dask_values", "dask/array/tests/test_random.py::test_randomstate_consistent_names", "dask/array/tests/test_random.py::test_random", "dask/array/tests/test_random.py::test_parametrized_random_function", "dask/array/tests/test_random.py::test_kwargs", "dask/array/tests/test_random.py::test_unique_names", "dask/array/tests/test_random.py::test_docs", "dask/array/tests/test_random.py::test_can_make_really_big_random_array", "dask/array/tests/test_random.py::test_random_seed" ]
[]
BSD 3-Clause "New" or "Revised" License
530
joblib__joblib-350
6393c7ee293980963541384dc9573e09116f4734
2016-05-11 08:06:46
40341615cc2600675ce7457d9128fb030f6f89fa
aabadie: @lesteve, I addressed your previous comments and squashed the commits. lesteve: Thanks a lot, merging !
diff --git a/joblib/hashing.py b/joblib/hashing.py index a6e5337..ced817b 100644 --- a/joblib/hashing.py +++ b/joblib/hashing.py @@ -189,7 +189,11 @@ class NumpyHasher(Hasher): if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject: # Compute a hash of the object # The update function of the hash requires a c_contiguous buffer. - if obj.flags.c_contiguous: + if obj.shape == (): + # 0d arrays need to be flattened because viewing them as bytes + # raises a ValueError exception. + obj_c_contiguous = obj.flatten() + elif obj.flags.c_contiguous: obj_c_contiguous = obj elif obj.flags.f_contiguous: obj_c_contiguous = obj.T
Regression: joblib.hash fails on 0d array ```python import numpy as np import joblib arr = np.array(0) joblib.hash(arr) ``` Works with joblib 0.9.4 and fails on master with the following error: ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-4-c182cb63f185> in <module>() ----> 1 joblib.hash(arr) /home/le243287/dev/alt-scikit-learn/sklearn/externals/joblib/hashing.py in hash(obj, hash_name, coerce_mmap) 256 else: 257 hasher = Hasher(hash_name=hash_name) --> 258 return hasher.hash(obj) /home/le243287/dev/alt-scikit-learn/sklearn/externals/joblib/hashing.py in hash(self, obj, return_digest) 66 def hash(self, obj, return_digest=True): 67 try: ---> 68 self.dump(obj) 69 except pickle.PicklingError as e: 70 e.args += ('PicklingError while hashing %r: %r' % (obj, e),) /volatile/le243287/miniconda3/lib/python3.5/pickle.py in dump(self, obj) 406 if self.proto >= 4: 407 self.framer.start_framing() --> 408 self.save(obj) 409 self.write(STOP) 410 self.framer.end_framing() /home/le243287/dev/alt-scikit-learn/sklearn/externals/joblib/hashing.py in save(self, obj) 205 # taking the memoryview. 206 self._hash.update( --> 207 self._getbuffer(obj_c_contiguous.view(self.np.uint8))) 208 209 # We store the class, to be able to distinguish between ValueError: new type not compatible with array. ``` Full disclosure I discovered this when running the nilearn tests using joblib master.
joblib/joblib
diff --git a/joblib/test/test_hashing.py b/joblib/test/test_hashing.py index b197167..d36e4d8 100644 --- a/joblib/test/test_hashing.py +++ b/joblib/test/test_hashing.py @@ -402,6 +402,16 @@ def test_hashes_are_different_between_c_and_fortran_contiguous_arrays(): assert_not_equal(hash(arr_c), hash(arr_f)) +@with_numpy +def test_0d_array(): + hash(np.array(0)) + + +@with_numpy +def test_0d_and_1d_array_hashing_is_different(): + assert_not_equal(hash(np.array(0)), hash(np.array([0]))) + + @with_numpy def test_hashes_stay_the_same_with_numpy_objects(): # We want to make sure that hashes don't change with joblib
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "nose", "coverage", "numpy>=1.6.1", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/joblib/joblib.git@6393c7ee293980963541384dc9573e09116f4734#egg=joblib nose==1.3.7 numpy==1.19.5 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: joblib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - numpy==1.19.5 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/joblib
[ "joblib/test/test_hashing.py::test_0d_array", "joblib/test/test_hashing.py::test_0d_and_1d_array_hashing_is_different" ]
[]
[ "joblib/test/test_hashing.py::test_memory_setup_func", "joblib/test/test_hashing.py::test_memory_teardown_func", "joblib/test/test_hashing.py::test_hash_methods", "joblib/test/test_hashing.py::test_numpy_datetime_array", "joblib/test/test_hashing.py::test_hash_numpy_noncontiguous", "joblib/test/test_hashing.py::test_hash_numpy_performance", "joblib/test/test_hashing.py::test_bound_methods_hash", "joblib/test/test_hashing.py::test_bound_cached_methods_hash", "joblib/test/test_hashing.py::test_hash_object_dtype", "joblib/test/test_hashing.py::test_numpy_scalar", "joblib/test/test_hashing.py::test_dict_hash", "joblib/test/test_hashing.py::test_set_hash", "joblib/test/test_hashing.py::test_string", "joblib/test/test_hashing.py::test_dtype", "joblib/test/test_hashing.py::test_hashes_are_different_between_c_and_fortran_contiguous_arrays", "joblib/test/test_hashing.py::test_hashing_pickling_error" ]
[]
BSD 3-Clause "New" or "Revised" License
531
joblib__joblib-351
63efbf0263922f9603f9ad9f86a2cc344a627d20
2016-05-11 13:56:43
40341615cc2600675ce7457d9128fb030f6f89fa
aabadie: I think this is in a pretty good shape now, so changing the status to MRG. A few comments though: * the implementation is not perfect (e.g new `_COMPRESSOR_OBJS` list, etc) so I'd like to have someone else's opinion, * forcing the decompressor to a wrong one (exemple: use gzip compression with dump but try to uncompress with bz2) will raise an exception. Should we handle this case ? My answer on this is 'no' as the message is quite meaningful but maybe other people won't agree with this, * online documentation and CHANGES.rst still need to be updated but this can be done after a preliminary review. aabadie: @lesteve, I addressed what we discussed IRL. Feel free to have a look when you have time. aabadie: @lesteve, @ogrisel , any comment ? aabadie: Just for the record, here is the kind of things now possible with this PR: https://gist.github.com/aabadie/074587354d97d872aff6abb65510f618 lesteve: Looks like you need to rebase on master. lesteve: > Looks like you need to rebase on master. Other than this LGTM. aabadie: > Looks like you need to rebase on master. Rebased, waiting for AppVeyor. lesteve: Can you add an entry in CHANGES.rst? Maybe we want to update the docs and add a small section saying that we can use file objects. aabadie: > Can you add an entry in CHANGES.rst? Sure > Maybe we want to update the docs and add a small section saying that we can use file objects. Good point. Something I forgot to add. aabadie: @lesteve, I added some lines about persistence in file objects in the documentation and updated the CHANGES.rst file. Comments welcome :wink: lesteve: Can you rebase on master so we quickly double-check that flake8_diff.sh works fine on your PR? aabadie: > Can you rebase on master so we quickly double-check that flake8_diff.sh works fine on your PR? Travis is broken because of the new code in the doc. I'm on it. aabadie: I had issues with doctest and the usage of file object in a context manager. I skipped the lines in the doc but that may not be a solution. Any better idea ? Otherwise, I rebased on the lastest master (including the flake8_diff.sh recent changes) and it works just fine. lesteve: > I had issues with doctest and the usage of file object in a context manager. I skipped the lines in the doc but that may not be a solution. Any better idea ? What was the error? It would be great to understand where it comes from and fix it properly ... > Otherwise, I rebased on the lastest master (including the flake8_diff.sh recent changes) and it works just fine. Great, thanks a lot! aabadie: > What was the error? It would be great to understand where it comes from and fix it properly ... There were 2 things: * `with open() as fo` returns the file object ([<io.blabla>]) : I fixed it using an ellipsis flags and by adding `[<...>]` after the `with` block * in python 2.6, using gzip.GzipFile or bz2.BZ2File doesn't work if you don't use `contextlib.closing`. So I had to skip the file object compression example. lesteve: > with open() as fo returns the file object ([]) : I fixed it using an ellipsis flags and by adding [<...>] after the with block Hmmm I am not sure what we should do in this case: ```py with gzip.GzipFile('/tmp/test.gz', 'wb') as f: res = joblib.dump({'a': [1, 2, 3], 'b': 'asadf'}, f) ``` Should `res` be: * a single element list containing containing `f` * a single element list containing containing f.name to be more consistent with when dump is called with a filename * because this is a new feature, can we do what we want, in particular returning a list may not make sense, since the list was there for historical reasons (main pickle + companion files for each numpy array) > in python 2.6, using gzip.GzipFile or bz2.BZ2File doesn't work if you don't use contextlib.closing. So I had to skip the file object compression example. Pfff :sob: is there a way we can just skip doctests in Python 2.6? lesteve: > Pfff :sob: is there a way we can just skip doctests in Python 2.6? Seems like scikit-learn has some "*fixture*" files in doc to skip the doctests. You can probably have a look there. I believe there is something in setup.cfg as well to work with nose and doctest-fixtures. aabadie: > Should res be: > * a single element list containing containing f > * a single element list containing containing f.name to be more consistent with when dump is called > with a filename > * because this is a new feature, can we do what we want, in particular returning a list may not make > sense, since the list was there for historical reasons (main pickle + companion files for each numpy array) I think returning nothing in case a file object is given as input is reasonable because this means the user knows in advance the destination of the dump and the returned list is here, as you said, for historical reasons. aabadie: > Seems like scikit-learn has some *fixture* files in the doc folder to skip the doctests Nice, it works like a charm. The `setup.cfg` file in joblib was already correctly configured.
diff --git a/CHANGES.rst b/CHANGES.rst index 082f60c..eed5f3d 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,6 +4,11 @@ Latest changes Release 0.10.0 -------------- +Alexandre Abadie + + ENH: joblib.dump/load now accept file-like objects besides filenames. + https://github.com/joblib/joblib/pull/351 for more details. + Niels Zeilemaker and Olivier Grisel Refactored joblib.Parallel to enable the registration of custom diff --git a/benchmarks/bench_auto_batching.py b/benchmarks/bench_auto_batching.py index 6046099..d94bc95 100644 --- a/benchmarks/bench_auto_batching.py +++ b/benchmarks/bench_auto_batching.py @@ -53,11 +53,10 @@ def bench_short_tasks(task_times, n_jobs=2, batch_size="auto", p(delayed(sleep_noop)(max(t, 0), input_data, output_data_size) for t in task_times) duration = time.time() - t0 - effective_batch_size = getattr(p, '_effective_batch_size', + effective_batch_size = getattr(p._backend, '_effective_batch_size', p.batch_size) - - print('Completed %d tasks in %0.3fs, final batch_size=%d\n' - % (len(task_times), duration, effective_batch_size)) + print('Completed {} tasks in {:3f}s, final batch_size={}\n'.format( + len(task_times), duration, effective_batch_size)) return duration, effective_batch_size diff --git a/doc/persistence.rst b/doc/persistence.rst index d261795..f040428 100644 --- a/doc/persistence.rst +++ b/doc/persistence.rst @@ -46,6 +46,18 @@ We can then load the object from the file:: [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] +Persistence in file objects +=========================== + +Instead of filenames, `dump` and `load` functions also accept file objects: + + >>> with open(filename, 'wb') as fo: # doctest: +ELLIPSIS + ... joblib.dump(to_persist, fo) + >>> with open(filename, 'rb') as fo: # doctest: +ELLIPSIS + ... joblib.load(fo) + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] + + Compressed joblib pickles ========================= @@ -79,6 +91,15 @@ are 'gzip', 'bz2', 'lzma' and 'xz': Lzma and Xz compression methods are only available for python versions >= 3.3. +Compressor files provided by the python standard library can also be used to +compress pickle, e.g ``gzip.GzipFile``, ``bz2.BZ2File``, ``lzma.LZMAFile``: + >>> # Dumping in a gzip.GzipFile object using a compression level of 3. + >>> import gzip + >>> with gzip.GzipFile(filename + '.gz', 'wb', compresslevel=3) as fo: # doctest: +ELLIPSIS + ... joblib.dump(to_persist, fo) + >>> with gzip.GzipFile(filename + '.gz', 'rb') as fo: # doctest: +ELLIPSIS + ... joblib.load(fo) + [('a', [1, 2, 3]), ('b', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))] More details can be found in the :func:`joblib.dump` and :func:`joblib.load` documentation. diff --git a/doc/persistence_fixture.py b/doc/persistence_fixture.py new file mode 100644 index 0000000..503d0bc --- /dev/null +++ b/doc/persistence_fixture.py @@ -0,0 +1,13 @@ +"""Fixture module to skip the persistence doctest with python 2.6.""" + +from nose import SkipTest +from joblib import _compat + + +def setup_module(module): + """Setup module.""" + if _compat.PY26: + # gzip.GZipFile and bz2.BZ2File compressor classes cannot be used + # within a context manager (e.g in a `with` block) in python 2.6 so + # we skip doctesting of persistence documentation in this case. + raise SkipTest("Skipping persistence doctest in Python 2.6") diff --git a/joblib/numpy_pickle.py b/joblib/numpy_pickle.py index f029582..0cf88a2 100644 --- a/joblib/numpy_pickle.py +++ b/joblib/numpy_pickle.py @@ -397,6 +397,9 @@ def dump(value, filename, compress=0, protocol=None, cache_size=None): if Path is not None and isinstance(filename, Path): filename = str(filename) + is_filename = isinstance(filename, _basestring) + is_fileobj = hasattr(filename, "write") + compress_method = 'zlib' # zlib is the default compression method. if compress is True: # By default, if compress is enabled, we want to be using 3 by default @@ -424,14 +427,16 @@ def dump(value, filename, compress=0, protocol=None, cache_size=None): 'Non valid compression method given: "{0}". Possible values are ' '{1}.'.format(compress_method, _COMPRESSORS)) - if not isinstance(filename, _basestring): + if not is_filename and not is_fileobj: # People keep inverting arguments, and the resulting error is # incomprehensible raise ValueError( - 'Second argument should be a filename, %s (type %s) was given' + 'Second argument should be a filename or a file-like object, ' + '%s (type %s) was given.' % (filename, type(filename)) ) - elif not isinstance(compress, tuple): + + if is_filename and not isinstance(compress, tuple): # In case no explicit compression was requested using both compression # method and level in a tuple and the filename has an explicit # extension, we select the corresponding compressor. @@ -473,14 +478,54 @@ def dump(value, filename, compress=0, protocol=None, cache_size=None): with _write_fileobject(filename, compress=(compress_method, compress_level)) as f: NumpyPickler(f, protocol=protocol).dump(value) - - else: + elif is_filename: with open(filename, 'wb') as f: NumpyPickler(f, protocol=protocol).dump(value) + else: + NumpyPickler(filename, protocol=protocol).dump(value) + + # If the target container is a file object, nothing is returned. + if is_fileobj: + return + # For compatibility, the list of created filenames (e.g with one element + # after 0.10.0) is returned by default. return [filename] +def _unpickle(fobj, filename="", mmap_mode=None): + """Internal unpickling function.""" + # We are careful to open the file handle early and keep it open to + # avoid race-conditions on renames. + # That said, if data is stored in companion files, which can be + # the case with the old persistence format, moving the directory + # will create a race when joblib tries to access the companion + # files. + unpickler = NumpyUnpickler(filename, fobj, mmap_mode=mmap_mode) + obj = None + try: + obj = unpickler.load() + if unpickler.compat_mode: + warnings.warn("The file '%s' has been generated with a " + "joblib version less than 0.10. " + "Please regenerate this pickle file." + % filename, + DeprecationWarning, stacklevel=3) + except UnicodeDecodeError as exc: + # More user-friendly error message + if PY3_OR_LATER: + new_exc = ValueError( + 'You may be trying to read with ' + 'python 3 a joblib pickle generated with python 2. ' + 'This feature is not supported by joblib.') + new_exc.__cause__ = exc + raise new_exc + # Reraise exception with Python 2 + raise + + return obj + + def load(filename, mmap_mode=None): """Reconstruct a Python object from a file persisted with joblib.dump. @@ -514,37 +559,19 @@ def load(filename, mmap_mode=None): """ if Path is not None and isinstance(filename, Path): filename = str(filename) - with open(filename, 'rb') as f: - with _read_fileobject(f, filename, mmap_mode) as f: - if isinstance(f, _basestring): - # if the returned file object is a string, this means we try - # to load a pickle file generated with an version of Joblib - # so we load it with joblib compatibility function. - return load_compatibility(f) - - # We are careful to open the file handle early and keep it open to - # avoid race-conditions on renames. - # That said, if data is stored in companion files, which can be - # the case with the old persistence format, moving the directory - # will create a race when joblib tries to access the companion - # files. - unpickler = NumpyUnpickler(filename, f, mmap_mode=mmap_mode) - try: - obj = unpickler.load() - if unpickler.compat_mode: - warnings.warn("The file '%s' has been generated with a " - "joblib version less than 0.10. " - "Please regenerate this pickle file." - % filename, - DeprecationWarning, stacklevel=2) - except UnicodeDecodeError as exc: - # More user-friendly error message - if PY3_OR_LATER: - new_exc = ValueError( - 'You may be trying to read with ' - 'python 3 a joblib pickle generated with python 2. ' - 'This feature is not supported by joblib.') - new_exc.__cause__ = exc - raise new_exc + + if hasattr(filename, "read") and hasattr(filename, "seek"): + with _read_fileobject(filename, "", mmap_mode) as fobj: + obj = _unpickle(fobj) + else: + with open(filename, 'rb') as f: + with _read_fileobject(f, filename, mmap_mode) as fobj: + if isinstance(fobj, _basestring): + # if the returned file object is a string, this means we + # try to load a pickle file generated with an version of + # Joblib so we load it with joblib compatibility function. + return load_compatibility(fobj) + + obj = _unpickle(fobj, filename, mmap_mode) return obj diff --git a/joblib/numpy_pickle_utils.py b/joblib/numpy_pickle_utils.py index 1755b28..ee879a6 100644 --- a/joblib/numpy_pickle_utils.py +++ b/joblib/numpy_pickle_utils.py @@ -8,6 +8,7 @@ import pickle import sys import io import zlib +import gzip import bz2 import warnings import contextlib @@ -49,6 +50,9 @@ _LZMA_PREFIX = b'\x5d\x00' # Supported compressors _COMPRESSORS = ('zlib', 'bz2', 'lzma', 'xz', 'gzip') +_COMPRESSOR_CLASSES = [gzip.GzipFile, bz2.BZ2File] +if lzma is not None: + _COMPRESSOR_CLASSES.append(lzma.LZMAFile) # The max magic number length of supported compression file types. _MAX_PREFIX_LEN = max(len(prefix) @@ -147,20 +151,42 @@ def _read_fileobject(fileobj, filename, mmap_mode=None): """ # Detect if the fileobj contains compressed data. compressor = _detect_compressor(fileobj) + if isinstance(fileobj, tuple(_COMPRESSOR_CLASSES)): + compressor = fileobj.__class__.__name__ if compressor == 'compat': + # Compatibility with old pickle mode: simply return the input + # filename "as-is" and let the compatibility function be called by the + # caller. warnings.warn("The file '%s' has been generated with a joblib " "version less than 0.10. " "Please regenerate this pickle file." % filename, DeprecationWarning, stacklevel=2) yield filename else: - if compressor in _COMPRESSORS and mmap_mode is not None: + # Checking if incompatible load parameters with the type of file: + # mmap_mode cannot be used with compressed file or in memory buffers + # such as io.BytesIO. + if ((compressor in _COMPRESSORS or + isinstance(fileobj, tuple(_COMPRESSOR_CLASSES))) and + mmap_mode is not None): warnings.warn('File "%(filename)s" is compressed using ' '"%(compressor)s" which is not compatible with ' - 'mmap_mode "%(mmap_mode)s" flag passed.' - % locals(), DeprecationWarning, stacklevel=2) - - if compressor == 'zlib': + 'mmap_mode "%(mmap_mode)s" flag passed. mmap_mode ' + 'option will be ignored.' + % locals(), stacklevel=2) + if isinstance(fileobj, io.BytesIO) and mmap_mode is not None: + warnings.warn('In memory persistence is not compatible with ' + 'mmap_mode "%(mmap_mode)s" flag passed. mmap_mode ' + 'option will be ignored.' + % locals(), stacklevel=2) + + # if the passed fileobj is in the supported list of decompressor + # objects (GzipFile, BZ2File, LzmaFile), we simply return it. + if isinstance(fileobj, tuple(_COMPRESSOR_CLASSES)): + yield fileobj + # otherwise, based on the compressor detected in the file, we open the + # correct decompressor file object, wrapped in a buffer. + elif compressor == 'zlib': yield _buffered_read_file(BinaryZlibFile(fileobj, 'rb')) elif compressor == 'gzip': yield _buffered_read_file(BinaryGzipFile(fileobj, 'rb')) @@ -180,6 +206,7 @@ def _read_fileobject(fileobj, filename, mmap_mode=None): "python ({0}.{1})" .format(sys.version_info[0], sys.version_info[1])) + # No compression detected => returning the input file object (open) else: yield fileobj
In-memory caching Sometimes reloading custom objects from the cache can be expensive (but still much faster than recomputing the whole object from scratch), in which case a two-level cache can be useful: results could be first kept in memory, and, after some timeout (LRU/etc.), pushed to the hard drive for longer-time persistence. Is this something that joblib's architecture may easily allow?
joblib/joblib
diff --git a/joblib/test/test_numpy_pickle.py b/joblib/test/test_numpy_pickle.py index 19a5e95..f3708fb 100644 --- a/joblib/test/test_numpy_pickle.py +++ b/joblib/test/test_numpy_pickle.py @@ -13,6 +13,7 @@ import warnings import nose import gzip import zlib +import bz2 import pickle from contextlib import closing @@ -25,7 +26,7 @@ from joblib.testing import assert_raises_regex from joblib import numpy_pickle from joblib.test import data -from joblib._compat import PY3_OR_LATER +from joblib._compat import PY3_OR_LATER, PY26 from joblib.numpy_pickle_utils import _IO_BUFFER_SIZE, BinaryZlibFile from joblib.numpy_pickle_utils import _detect_compressor, _COMPRESSORS @@ -334,14 +335,15 @@ def test_compress_mmap_mode_warning(): numpy_pickle.load(this_filename, mmap_mode='r+') nose.tools.assert_equal(len(caught_warnings), 1) for warn in caught_warnings: - nose.tools.assert_equal(warn.category, DeprecationWarning) + nose.tools.assert_equal(warn.category, UserWarning) nose.tools.assert_equal(warn.message.args[0], 'File "%(filename)s" is compressed using ' '"%(compressor)s" which is not compatible ' 'with mmap_mode "%(mmap_mode)s" flag ' - 'passed.' % {'filename': this_filename, - 'mmap_mode': 'r+', - 'compressor': 'zlib'}) + 'passed. mmap_mode option will be ' + 'ignored.' % {'filename': this_filename, + 'mmap_mode': 'r+', + 'compressor': 'zlib'}) @with_numpy @@ -681,6 +683,120 @@ def test_compression_using_file_extension(): os.remove(dump_fname) +@with_numpy +def test_file_handle_persistence(): + objs = [np.random.random((10, 10)), + "some data", + np.matrix([0, 1, 2])] + fobjs = [open] + if not PY26: + fobjs += [bz2.BZ2File, gzip.GzipFile] + if PY3_OR_LATER: + import lzma + fobjs += [lzma.LZMAFile] + filename = env['filename'] + str(random.randint(0, 1000)) + + for obj in objs: + for fobj in fobjs: + with fobj(filename, 'wb') as f: + numpy_pickle.dump(obj, f) + + # using the same decompressor prevents from internally + # decompress again. + with fobj(filename, 'rb') as f: + obj_reloaded = numpy_pickle.load(f) + + # when needed, the correct decompressor should be used when + # passing a raw file handle. + with open(filename, 'rb') as f: + obj_reloaded_2 = numpy_pickle.load(f) + + if isinstance(obj, np.ndarray): + np.testing.assert_array_equal(obj_reloaded, obj) + np.testing.assert_array_equal(obj_reloaded_2, obj) + else: + nose.tools.assert_equal(obj_reloaded, obj) + nose.tools.assert_equal(obj_reloaded_2, obj) + + os.remove(filename) + + +@with_numpy +def test_in_memory_persistence(): + objs = [np.random.random((10, 10)), + "some data", + np.matrix([0, 1, 2])] + for obj in objs: + f = io.BytesIO() + numpy_pickle.dump(obj, f) + obj_reloaded = numpy_pickle.load(f) + if isinstance(obj, np.ndarray): + np.testing.assert_array_equal(obj_reloaded, obj) + else: + nose.tools.assert_equal(obj_reloaded, obj) + + +@with_numpy +def test_file_handle_persistence_mmap(): + obj = np.random.random((10, 10)) + filename = env['filename'] + str(random.randint(0, 1000)) + + with open(filename, 'wb') as f: + numpy_pickle.dump(obj, f) + + with open(filename, 'rb') as f: + obj_reloaded = numpy_pickle.load(f, mmap_mode='r+') + + np.testing.assert_array_equal(obj_reloaded, obj) + + +@with_numpy +def test_file_handle_persistence_compressed_mmap(): + obj = np.random.random((10, 10)) + filename = env['filename'] + str(random.randint(0, 1000)) + + with open(filename, 'wb') as f: + numpy_pickle.dump(obj, f, compress=('gzip', 3)) + + with closing(gzip.GzipFile(filename, 'rb')) as f: + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + numpy_pickle.load(f, mmap_mode='r+') + nose.tools.assert_equal(len(caught_warnings), 1) + for warn in caught_warnings: + nose.tools.assert_equal(warn.category, UserWarning) + nose.tools.assert_equal(warn.message.args[0], + 'File "%(filename)s" is compressed ' + 'using "%(compressor)s" which is not ' + 'compatible with mmap_mode ' + '"%(mmap_mode)s" flag ' + 'passed. mmap_mode option will be ' + 'ignored.' % + {'filename': "", + 'mmap_mode': 'r+', + 'compressor': 'GzipFile'}) + + +@with_numpy +def test_file_handle_persistence_in_memory_mmap(): + obj = np.random.random((10, 10)) + buf = io.BytesIO() + + numpy_pickle.dump(obj, buf) + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + numpy_pickle.load(buf, mmap_mode='r+') + nose.tools.assert_equal(len(caught_warnings), 1) + for warn in caught_warnings: + nose.tools.assert_equal(warn.category, UserWarning) + nose.tools.assert_equal(warn.message.args[0], + 'In memory persistence is not compatible ' + 'with mmap_mode "%(mmap_mode)s" ' + 'flag passed. mmap_mode option will be ' + 'ignored.' % {'mmap_mode': 'r+'}) + + def test_binary_zlibfile(): filename = env['filename'] + str(random.randint(0, 1000))
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 5 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "nose", "coverage", "numpy>=1.6.1", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/joblib/joblib.git@63efbf0263922f9603f9ad9f86a2cc344a627d20#egg=joblib nose==1.3.7 numpy==1.19.5 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: joblib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - numpy==1.19.5 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/joblib
[ "joblib/test/test_numpy_pickle.py::test_compress_mmap_mode_warning", "joblib/test/test_numpy_pickle.py::test_file_handle_persistence", "joblib/test/test_numpy_pickle.py::test_in_memory_persistence", "joblib/test/test_numpy_pickle.py::test_file_handle_persistence_mmap", "joblib/test/test_numpy_pickle.py::test_file_handle_persistence_compressed_mmap", "joblib/test/test_numpy_pickle.py::test_file_handle_persistence_in_memory_mmap" ]
[ "joblib/test/test_numpy_pickle.py::test_cache_size_warning", "joblib/test/test_numpy_pickle.py::test_joblib_pickle_across_python_versions" ]
[ "joblib/test/test_numpy_pickle.py::test_value_error", "joblib/test/test_numpy_pickle.py::test_compress_level_error", "joblib/test/test_numpy_pickle.py::test_numpy_persistence", "joblib/test/test_numpy_pickle.py::test_numpy_persistence_bufferred_array_compression", "joblib/test/test_numpy_pickle.py::test_memmap_persistence", "joblib/test/test_numpy_pickle.py::test_memmap_persistence_mixed_dtypes", "joblib/test/test_numpy_pickle.py::test_masked_array_persistence", "joblib/test/test_numpy_pickle.py::test_compressed_pickle_dump_and_load", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats", "joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile", "joblib/test/test_numpy_pickle.py::test_numpy_subclass", "joblib/test/test_numpy_pickle.py::test_pathlib", "joblib/test/test_numpy_pickle.py::test_non_contiguous_array_pickling", "joblib/test/test_numpy_pickle.py::test_pickle_highest_protocol" ]
[]
BSD 3-Clause "New" or "Revised" License
532
dask__dask-1152
472ce70b9c19a075764f7614e884b2afc14c44cb
2016-05-11 14:35:49
8f8435a08bd54f0763f75ce61ec55adea9a2c08b
diff --git a/dask/array/core.py b/dask/array/core.py index a82f73979..2cf8f9573 100644 --- a/dask/array/core.py +++ b/dask/array/core.py @@ -2062,7 +2062,7 @@ def asarray(array): """ if not isinstance(array, Array): name = 'asarray-' + tokenize(array) - if not hasattr(array, 'shape'): + if isinstance(getattr(array, 'shape', None), Iterable): array = np.asarray(array) array = from_array(array, chunks=array.shape, name=name) return array @@ -2103,7 +2103,7 @@ def is_scalar_for_elemwise(arg): True """ return (np.isscalar(arg) - or not hasattr(arg, 'shape') + or not isinstance(getattr(arg, 'shape', None), Iterable) or isinstance(arg, np.dtype) or (isinstance(arg, np.ndarray) and arg.ndim == 0)) @@ -2156,6 +2156,7 @@ def elemwise(op, *args, **kwargs): (op.__name__, str(sorted(set(kwargs) - set(['name', 'dtype']))))) shapes = [getattr(arg, 'shape', ()) for arg in args] + shapes = [s if isinstance(s, Iterable) else () for s in shapes] out_ndim = len(broadcast_shapes(*shapes)) # Raises ValueError if dimensions mismatch expr_inds = tuple(range(out_ndim))[::-1]
Array astype breaks when given a type instead of a dtype object The code below fails in dask 0.9.0, numpy 1.11.0, toolz 0.7.4, Python 2.7: ```py import numpy as np import dask.array as da a = np.arange(5).astype(np.int32) d = da.from_array(a, (1,)) print(d.dtype) e = d.astype(np.int16) print(e.dtype) print(e.compute()) ``` with the exception ``` Traceback (most recent call last): File "./dask-astype.py", line 8, in <module> e = d.astype(np.int16) File "/home/bmerry/work/sdp/env/local/lib/python2.7/site-packages/dask/array/core.py", line 1091, in astype return elemwise(_astype, self, dtype, name=name) File "/home/bmerry/work/sdp/env/local/lib/python2.7/site-packages/dask/array/core.py", line 2159, in elemwise out_ndim = len(broadcast_shapes(*shapes)) # Raises ValueError if dimensions mismatch File "/home/bmerry/work/sdp/env/local/lib/python2.7/site-packages/dask/array/core.py", line 2131, in broadcast_shapes for sizes in zip_longest(*map(reversed, shapes), fillvalue=1): TypeError: type object argument after * must be a sequence, not itertools.imap ``` If one passes `np.dtype(np.int16)` instead of just `np.int16`, then it works. The problem seems to be that the `np.int16.shape` attribute exists, but isn't a sequence. Possibly this can be fixed by adding `dtype = np.dtype(dtype) to the start of `Array.astype`.
dask/dask
diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py index 555ca3bfc..989a91ad9 100644 --- a/dask/array/tests/test_array_core.py +++ b/dask/array/tests/test_array_core.py @@ -2010,3 +2010,9 @@ def test_copy(): def test_npartitions(): assert da.ones(5, chunks=(2,)).npartitions == 3 assert da.ones((5, 5), chunks=(2, 3)).npartitions == 6 + + +def test_astype_gh1151(): + a = np.arange(5).astype(np.int32) + b = da.from_array(a, (1,)) + assert_eq(a.astype(np.int16), b.astype(np.int16))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 pandas>=1.0.0 cloudpickle partd distributed s3fs toolz psutil pytables bokeh bcolz scipy h5py ipython", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz liblzma-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore @ file:///opt/conda/conda-bld/aiobotocore_1643638228694/work aiohttp @ file:///tmp/build/80754af9/aiohttp_1632748060317/work aioitertools @ file:///tmp/build/80754af9/aioitertools_1607109665762/work async-timeout==3.0.1 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work bcolz==1.2.1 bokeh @ file:///tmp/build/80754af9/bokeh_1620710048147/work boto3==1.23.10 botocore==1.26.10 brotlipy==0.7.0 certifi==2021.5.30 cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work chardet @ file:///tmp/build/80754af9/chardet_1607706739153/work click==8.0.3 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1632508026186/work contextvars==2.4 cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work cytoolz==0.11.0 -e git+https://github.com/dask/dask.git@472ce70b9c19a075764f7614e884b2afc14c44cb#egg=dask decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work distributed==1.10.2 fsspec @ file:///opt/conda/conda-bld/fsspec_1642510437511/work h5py==2.10.0 HeapDict @ file:///Users/ktietz/demo/mc3/conda-bld/heapdict_1630598515714/work idna @ file:///tmp/build/80754af9/idna_1637925883363/work idna-ssl @ file:///tmp/build/80754af9/idna_ssl_1611752490495/work immutables @ file:///tmp/build/80754af9/immutables_1628888996840/work importlib-metadata==4.8.3 iniconfig==1.1.1 ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work jmespath @ file:///Users/ktietz/demo/mc3/conda-bld/jmespath_1630583964805/work locket==0.2.1 MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work mock @ file:///tmp/build/80754af9/mock_1607622725907/work msgpack @ file:///tmp/build/80754af9/msgpack-python_1612287171716/work msgpack-python==0.5.6 multidict @ file:///tmp/build/80754af9/multidict_1607367768400/work numexpr @ file:///tmp/build/80754af9/numexpr_1618853194344/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 parso==0.7.0 partd @ file:///opt/conda/conda-bld/partd_1647245470509/work pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work pluggy==1.0.0 prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work psutil @ file:///tmp/build/80754af9/psutil_1612297621795/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl py==1.11.0 pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work pytest==7.0.1 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work pytz==2021.3 PyYAML==5.4.1 s3fs==0.4.2 s3transfer==0.5.2 scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work six @ file:///tmp/build/80754af9/six_1644875935023/work sortedcontainers @ file:///tmp/build/80754af9/sortedcontainers_1623949099177/work tables==3.6.1 tblib @ file:///Users/ktietz/demo/mc3/conda-bld/tblib_1629402031467/work tomli==1.2.3 toolz @ file:///tmp/build/80754af9/toolz_1636545406491/work tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work wrapt==1.12.1 yarl @ file:///tmp/build/80754af9/yarl_1606939915466/work zict==2.0.0 zipp==3.6.0
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - aiobotocore=2.1.0=pyhd3eb1b0_0 - aiohttp=3.7.4.post0=py36h7f8727e_2 - aioitertools=0.7.1=pyhd3eb1b0_0 - async-timeout=3.0.1=py36h06a4308_0 - attrs=21.4.0=pyhd3eb1b0_0 - backcall=0.2.0=pyhd3eb1b0_0 - bcolz=1.2.1=py36h04863e7_0 - blas=1.0=openblas - blosc=1.21.3=h6a678d5_0 - bokeh=2.3.2=py36h06a4308_0 - brotlipy=0.7.0=py36h27cfd23_1003 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - cffi=1.14.6=py36h400218f_0 - chardet=4.0.0=py36h06a4308_1003 - click=8.0.3=pyhd3eb1b0_0 - cloudpickle=2.0.0=pyhd3eb1b0_0 - contextvars=2.4=py_0 - cryptography=35.0.0=py36hd23ed53_0 - cytoolz=0.11.0=py36h7b6447c_0 - decorator=5.1.1=pyhd3eb1b0_0 - freetype=2.12.1=h4a9f257_0 - fsspec=2022.1.0=pyhd3eb1b0_0 - giflib=5.2.2=h5eee18b_0 - h5py=2.10.0=py36h7918eee_0 - hdf5=1.10.4=hb1b8bf9_0 - heapdict=1.0.1=pyhd3eb1b0_0 - idna=3.3=pyhd3eb1b0_0 - idna_ssl=1.1.0=py36h06a4308_0 - immutables=0.16=py36h7f8727e_0 - ipython=7.16.1=py36h5ca1d4c_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.17.2=py36h06a4308_1 - jinja2=3.0.3=pyhd3eb1b0_0 - jmespath=0.10.0=pyhd3eb1b0_0 - jpeg=9e=h5eee18b_3 - lcms2=2.16=hb9589c4_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h6a678d5_0 - libdeflate=1.22=h5eee18b_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtiff=4.5.1=hffd6297_1 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - locket=0.2.1=py36h06a4308_1 - lz4-c=1.9.4=h6a678d5_1 - lzo=2.10=h7b6447c_2 - markupsafe=2.0.1=py36h27cfd23_0 - mock=4.0.3=pyhd3eb1b0_0 - multidict=5.1.0=py36h27cfd23_2 - ncurses=6.4=h6a678d5_0 - numexpr=2.7.3=py36h4be448d_1 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pandas=1.1.5=py36ha9443f7_0 - parso=0.7.0=py_0 - partd=1.2.0=pyhd3eb1b0_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pillow=8.3.1=py36h5aabda8_0 - pip=21.2.2=py36h06a4308_0 - prompt-toolkit=3.0.20=pyhd3eb1b0_0 - psutil=5.8.0=py36h27cfd23_1 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.11.2=pyhd3eb1b0_0 - pyopenssl=22.0.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pysocks=1.7.1=py36h06a4308_0 - pytables=3.6.1=py36h71ec239_0 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytz=2021.3=pyhd3eb1b0_0 - pyyaml=5.4.1=py36h27cfd23_1 - readline=8.2=h5eee18b_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sortedcontainers=2.4.0=pyhd3eb1b0_0 - sqlite=3.45.3=h5eee18b_0 - tblib=1.7.0=pyhd3eb1b0_0 - tk=8.6.14=h39e8969_0 - toolz=0.11.2=pyhd3eb1b0_0 - tornado=6.1=py36h27cfd23_0 - traitlets=4.3.3=py36h06a4308_0 - typing-extensions=4.1.1=hd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - urllib3=1.26.8=pyhd3eb1b0_0 - wcwidth=0.2.5=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - wrapt=1.12.1=py36h7b6447c_1 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - yarl=1.6.3=py36h27cfd23_0 - zict=2.0.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - zstd=1.5.6=hc292b87_0 - pip: - boto3==1.23.10 - botocore==1.26.10 - distributed==1.10.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - msgpack-python==0.5.6 - pluggy==1.0.0 - py==1.11.0 - pytest==7.0.1 - s3fs==0.4.2 - s3transfer==0.5.2 - tomli==1.2.3 - zipp==3.6.0 prefix: /opt/conda/envs/dask
[ "dask/array/tests/test_array_core.py::test_astype_gh1151" ]
[ "dask/array/tests/test_array_core.py::test_field_access", "dask/array/tests/test_array_core.py::test_coarsen", "dask/array/tests/test_array_core.py::test_coarsen_with_excess" ]
[ "dask/array/tests/test_array_core.py::test_getem", "dask/array/tests/test_array_core.py::test_top", "dask/array/tests/test_array_core.py::test_top_supports_broadcasting_rules", "dask/array/tests/test_array_core.py::test_concatenate3_on_scalars", "dask/array/tests/test_array_core.py::test_chunked_dot_product", "dask/array/tests/test_array_core.py::test_chunked_transpose_plus_one", "dask/array/tests/test_array_core.py::test_transpose", "dask/array/tests/test_array_core.py::test_broadcast_dimensions_works_with_singleton_dimensions", "dask/array/tests/test_array_core.py::test_broadcast_dimensions", "dask/array/tests/test_array_core.py::test_Array", "dask/array/tests/test_array_core.py::test_uneven_chunks", "dask/array/tests/test_array_core.py::test_numblocks_suppoorts_singleton_block_dims", "dask/array/tests/test_array_core.py::test_keys", "dask/array/tests/test_array_core.py::test_Array_computation", "dask/array/tests/test_array_core.py::test_stack", "dask/array/tests/test_array_core.py::test_short_stack", "dask/array/tests/test_array_core.py::test_stack_scalars", "dask/array/tests/test_array_core.py::test_concatenate", "dask/array/tests/test_array_core.py::test_concatenate_fixlen_strings", "dask/array/tests/test_array_core.py::test_vstack", "dask/array/tests/test_array_core.py::test_hstack", "dask/array/tests/test_array_core.py::test_dstack", "dask/array/tests/test_array_core.py::test_take", "dask/array/tests/test_array_core.py::test_compress", "dask/array/tests/test_array_core.py::test_binops", "dask/array/tests/test_array_core.py::test_isnull", "dask/array/tests/test_array_core.py::test_isclose", "dask/array/tests/test_array_core.py::test_broadcast_shapes", "dask/array/tests/test_array_core.py::test_elemwise_on_scalars", "dask/array/tests/test_array_core.py::test_partial_by_order", "dask/array/tests/test_array_core.py::test_elemwise_with_ndarrays", "dask/array/tests/test_array_core.py::test_elemwise_differently_chunked", "dask/array/tests/test_array_core.py::test_operators", "dask/array/tests/test_array_core.py::test_operator_dtype_promotion", "dask/array/tests/test_array_core.py::test_tensordot", "dask/array/tests/test_array_core.py::test_dot_method", "dask/array/tests/test_array_core.py::test_T", "dask/array/tests/test_array_core.py::test_norm", "dask/array/tests/test_array_core.py::test_choose", "dask/array/tests/test_array_core.py::test_where", "dask/array/tests/test_array_core.py::test_where_has_informative_error", "dask/array/tests/test_array_core.py::test_insert", "dask/array/tests/test_array_core.py::test_multi_insert", "dask/array/tests/test_array_core.py::test_broadcast_to", "dask/array/tests/test_array_core.py::test_ravel", "dask/array/tests/test_array_core.py::test_unravel", "dask/array/tests/test_array_core.py::test_reshape", "dask/array/tests/test_array_core.py::test_reshape_unknown_dimensions", "dask/array/tests/test_array_core.py::test_full", "dask/array/tests/test_array_core.py::test_map_blocks", "dask/array/tests/test_array_core.py::test_map_blocks2", "dask/array/tests/test_array_core.py::test_map_blocks_with_constants", "dask/array/tests/test_array_core.py::test_map_blocks_with_kwargs", "dask/array/tests/test_array_core.py::test_fromfunction", "dask/array/tests/test_array_core.py::test_from_function_requires_block_args", "dask/array/tests/test_array_core.py::test_repr", "dask/array/tests/test_array_core.py::test_slicing_with_ellipsis", "dask/array/tests/test_array_core.py::test_slicing_with_ndarray", "dask/array/tests/test_array_core.py::test_dtype", "dask/array/tests/test_array_core.py::test_blockdims_from_blockshape", "dask/array/tests/test_array_core.py::test_coerce", "dask/array/tests/test_array_core.py::test_store", "dask/array/tests/test_array_core.py::test_store_compute_false", "dask/array/tests/test_array_core.py::test_store_locks", "dask/array/tests/test_array_core.py::test_to_hdf5", "dask/array/tests/test_array_core.py::test_np_array_with_zero_dimensions", "dask/array/tests/test_array_core.py::test_unique", "dask/array/tests/test_array_core.py::test_dtype_complex", "dask/array/tests/test_array_core.py::test_astype", "dask/array/tests/test_array_core.py::test_arithmetic", "dask/array/tests/test_array_core.py::test_elemwise_consistent_names", "dask/array/tests/test_array_core.py::test_optimize", "dask/array/tests/test_array_core.py::test_slicing_with_non_ndarrays", "dask/array/tests/test_array_core.py::test_getarray", "dask/array/tests/test_array_core.py::test_squeeze", "dask/array/tests/test_array_core.py::test_size", "dask/array/tests/test_array_core.py::test_nbytes", "dask/array/tests/test_array_core.py::test_Array_normalizes_dtype", "dask/array/tests/test_array_core.py::test_args", "dask/array/tests/test_array_core.py::test_from_array_with_lock", "dask/array/tests/test_array_core.py::test_from_func", "dask/array/tests/test_array_core.py::test_topk", "dask/array/tests/test_array_core.py::test_topk_k_bigger_than_chunk", "dask/array/tests/test_array_core.py::test_bincount", "dask/array/tests/test_array_core.py::test_bincount_with_weights", "dask/array/tests/test_array_core.py::test_bincount_raises_informative_error_on_missing_minlength_kwarg", "dask/array/tests/test_array_core.py::test_histogram", "dask/array/tests/test_array_core.py::test_histogram_alternative_bins_range", "dask/array/tests/test_array_core.py::test_histogram_return_type", "dask/array/tests/test_array_core.py::test_histogram_extra_args_and_shapes", "dask/array/tests/test_array_core.py::test_concatenate3_2", "dask/array/tests/test_array_core.py::test_map_blocks3", "dask/array/tests/test_array_core.py::test_from_array_with_missing_chunks", "dask/array/tests/test_array_core.py::test_cache", "dask/array/tests/test_array_core.py::test_take_dask_from_numpy", "dask/array/tests/test_array_core.py::test_normalize_chunks", "dask/array/tests/test_array_core.py::test_raise_on_no_chunks", "dask/array/tests/test_array_core.py::test_chunks_is_immutable", "dask/array/tests/test_array_core.py::test_raise_on_bad_kwargs", "dask/array/tests/test_array_core.py::test_long_slice", "dask/array/tests/test_array_core.py::test_h5py_newaxis", "dask/array/tests/test_array_core.py::test_ellipsis_slicing", "dask/array/tests/test_array_core.py::test_point_slicing", "dask/array/tests/test_array_core.py::test_point_slicing_with_full_slice", "dask/array/tests/test_array_core.py::test_slice_with_floats", "dask/array/tests/test_array_core.py::test_vindex_errors", "dask/array/tests/test_array_core.py::test_vindex_merge", "dask/array/tests/test_array_core.py::test_empty_array", "dask/array/tests/test_array_core.py::test_array", "dask/array/tests/test_array_core.py::test_cov", "dask/array/tests/test_array_core.py::test_corrcoef", "dask/array/tests/test_array_core.py::test_memmap", "dask/array/tests/test_array_core.py::test_to_npy_stack", "dask/array/tests/test_array_core.py::test_view", "dask/array/tests/test_array_core.py::test_view_fortran", "dask/array/tests/test_array_core.py::test_h5py_tokenize", "dask/array/tests/test_array_core.py::test_map_blocks_with_changed_dimension", "dask/array/tests/test_array_core.py::test_broadcast_chunks", "dask/array/tests/test_array_core.py::test_chunks_error", "dask/array/tests/test_array_core.py::test_array_compute_forward_kwargs", "dask/array/tests/test_array_core.py::test_dont_fuse_outputs", "dask/array/tests/test_array_core.py::test_dont_dealias_outputs", "dask/array/tests/test_array_core.py::test_timedelta_op", "dask/array/tests/test_array_core.py::test_to_delayed", "dask/array/tests/test_array_core.py::test_cumulative", "dask/array/tests/test_array_core.py::test_eye", "dask/array/tests/test_array_core.py::test_diag", "dask/array/tests/test_array_core.py::test_tril_triu", "dask/array/tests/test_array_core.py::test_tril_triu_errors", "dask/array/tests/test_array_core.py::test_atop_names", "dask/array/tests/test_array_core.py::test_atop_kwargs", "dask/array/tests/test_array_core.py::test_from_delayed", "dask/array/tests/test_array_core.py::test_A_property", "dask/array/tests/test_array_core.py::test_copy", "dask/array/tests/test_array_core.py::test_npartitions" ]
[]
BSD 3-Clause "New" or "Revised" License
533
Axelrod-Python__Axelrod-587
03dd1a9600965800125eeb8942b6b0a3dfacf29c
2016-05-11 17:36:01
03dd1a9600965800125eeb8942b6b0a3dfacf29c
diff --git a/axelrod/strategies/cycler.py b/axelrod/strategies/cycler.py index 599e97a5..e3dd9c39 100644 --- a/axelrod/strategies/cycler.py +++ b/axelrod/strategies/cycler.py @@ -1,5 +1,6 @@ from axelrod import Actions, Player, init_args +import copy class AntiCycler(Player): """ @@ -74,18 +75,27 @@ class Cycler(Player): class CyclerCCD(Cycler): + classifier = copy.copy(Cycler.classifier) + classifier['memory_depth'] = 2 + @init_args def __init__(self, cycle="CCD"): Cycler.__init__(self, cycle=cycle) class CyclerCCCD(Cycler): + classifier = copy.copy(Cycler.classifier) + classifier['memory_depth'] = 3 + @init_args def __init__(self, cycle="CCCD"): Cycler.__init__(self, cycle=cycle) class CyclerCCCCCD(Cycler): + classifier = copy.copy(Cycler.classifier) + classifier['memory_depth'] = 5 + @init_args def __init__(self, cycle="CCCCCD"): Cycler.__init__(self, cycle=cycle) diff --git a/axelrod/strategies/gobymajority.py b/axelrod/strategies/gobymajority.py index fba5f73d..efc0d525 100644 --- a/axelrod/strategies/gobymajority.py +++ b/axelrod/strategies/gobymajority.py @@ -1,5 +1,7 @@ from axelrod import Actions, Player, init_args +import copy + C, D = Actions.C, Actions.D @@ -77,6 +79,8 @@ class GoByMajority40(GoByMajority): """ GoByMajority player with a memory of 40. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 40 @init_args def __init__(self, memory_depth=40, soft=True): @@ -88,6 +92,8 @@ class GoByMajority20(GoByMajority): """ GoByMajority player with a memory of 20. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 20 @init_args def __init__(self, memory_depth=20, soft=True): @@ -99,6 +105,8 @@ class GoByMajority10(GoByMajority): """ GoByMajority player with a memory of 10. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 10 @init_args def __init__(self, memory_depth=10, soft=True): @@ -110,6 +118,8 @@ class GoByMajority5(GoByMajority): """ GoByMajority player with a memory of 5. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 5 @init_args def __init__(self, memory_depth=5, soft=True): @@ -136,6 +146,8 @@ class HardGoByMajority40(HardGoByMajority): """ HardGoByMajority player with a memory of 40. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 40 @init_args def __init__(self, memory_depth=40, soft=False): @@ -147,6 +159,8 @@ class HardGoByMajority20(HardGoByMajority): """ HardGoByMajority player with a memory of 20. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 20 @init_args def __init__(self, memory_depth=20, soft=False): @@ -158,6 +172,8 @@ class HardGoByMajority10(HardGoByMajority): """ HardGoByMajority player with a memory of 10. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 10 @init_args def __init__(self, memory_depth=10, soft=False): @@ -169,6 +185,8 @@ class HardGoByMajority5(HardGoByMajority): """ HardGoByMajority player with a memory of 5. """ + classifier = copy.copy(GoByMajority.classifier) + classifier['memory_depth'] = 5 @init_args def __init__(self, memory_depth=5, soft=False): diff --git a/axelrod/strategies/meta.py b/axelrod/strategies/meta.py index 2f16d4b8..c2d5b60f 100644 --- a/axelrod/strategies/meta.py +++ b/axelrod/strategies/meta.py @@ -289,6 +289,14 @@ class MetaMixer(MetaPlayer): """ name = "Meta Mixer" + classifier = { + 'memory_depth': float('inf'), # Long memory + 'stochastic': True, + 'makes_use_of': set(), + 'inspects_source': False, + 'manipulates_source': False, + 'manipulates_state': False + } def __init__(self, team=None, distribution=None):
Test classification of strategy class as well as strategy player @mojones noticed a bug in the classification of Win Stay Lose Shift: see #506. I fixed it in #511, but really the test I added to #511 should be a test in the player class. I tried that but didn't get a failing test. Needs investigating :)
Axelrod-Python/Axelrod
diff --git a/axelrod/tests/unit/test_gambler.py b/axelrod/tests/unit/test_gambler.py index 1448103f..c59bb8d3 100755 --- a/axelrod/tests/unit/test_gambler.py +++ b/axelrod/tests/unit/test_gambler.py @@ -8,6 +8,8 @@ import random from .test_player import TestPlayer, TestHeadsUp from axelrod import random_choice, Actions +import copy + C, D = axelrod.Actions.C, axelrod.Actions.D @@ -25,6 +27,9 @@ class TestGambler(TestPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['memory_depth'] = float('inf') + def test_init(self): # Test empty table player = self.player(dict()) diff --git a/axelrod/tests/unit/test_gobymajority.py b/axelrod/tests/unit/test_gobymajority.py index 52883322..40d3b9e2 100644 --- a/axelrod/tests/unit/test_gobymajority.py +++ b/axelrod/tests/unit/test_gobymajority.py @@ -126,6 +126,15 @@ def factory_TestGoByRecentMajority(L, soft=True): name = "Hard Go By Majority: %i" % L player = getattr(axelrod, 'HardGoByMajority%i' % L) + expected_classifier = { + 'stochastic': False, + 'memory_depth': L, + 'makes_use_of': set(), + 'inspects_source': False, + 'manipulates_source': False, + 'manipulates_state': False + } + def test_initial_strategy(self): """Starts by defecting.""" self.first_play_test(D) diff --git a/axelrod/tests/unit/test_lookerup.py b/axelrod/tests/unit/test_lookerup.py index 49de2ce9..ce447ae1 100755 --- a/axelrod/tests/unit/test_lookerup.py +++ b/axelrod/tests/unit/test_lookerup.py @@ -4,6 +4,8 @@ import axelrod from .test_player import TestPlayer, TestHeadsUp from axelrod.strategies.lookerup import create_lookup_table_keys +import copy + C, D = axelrod.Actions.C, axelrod.Actions.D @@ -13,7 +15,7 @@ class TestLookerUp(TestPlayer): player = axelrod.LookerUp expected_classifier = { - 'memory_depth': 1, # Default TFT table + 'memory_depth': 1, # Default TfT 'stochastic': False, 'makes_use_of': set(), 'inspects_source': False, @@ -21,6 +23,9 @@ class TestLookerUp(TestPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['memory_depth'] = float('inf') + def test_init(self): # Test empty table player = self.player(dict()) @@ -113,6 +118,7 @@ class TestLookerUp(TestPlayer): self.responses_test([C, C, D], [D, D, C], [D]) + class TestEvolvedLookerUp(TestPlayer): name = "EvolvedLookerUp" diff --git a/axelrod/tests/unit/test_meta.py b/axelrod/tests/unit/test_meta.py index c8355d79..25810483 100644 --- a/axelrod/tests/unit/test_meta.py +++ b/axelrod/tests/unit/test_meta.py @@ -3,7 +3,7 @@ import random import axelrod -import unittest +import copy from .test_player import TestPlayer @@ -26,7 +26,7 @@ class TestMetaPlayer(TestPlayer): 'manipulates_state': False } - def classifier_test(self): + def classifier_test(self, expected_class_classifier=None): player = self.player() classifier = dict() for key in ['stochastic', @@ -47,6 +47,12 @@ class TestMetaPlayer(TestPlayer): msg="%s - Behaviour: %s != Expected Behaviour: %s" % (key, player.classifier[key], classifier[key])) + # Test that player has same classifier as it's class unless otherwise + # specified + if expected_class_classifier is None: + expected_class_classifier = player.classifier + self.assertEqual(expected_class_classifier, self.player.classifier) + def test_reset(self): p1 = self.player() p2 = axelrod.Cooperator() @@ -70,6 +76,10 @@ class TestMetaMajority(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + def test_strategy(self): P1 = axelrod.MetaMajority() @@ -96,6 +106,10 @@ class TestMetaMinority(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + def test_team(self): team = [axelrod.Cooperator] player = self.player(team=team) @@ -127,6 +141,10 @@ class TestMetaWinner(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + def test_strategy(self): P1 = axelrod.MetaWinner(team = [axelrod.Cooperator, axelrod.Defector]) @@ -206,6 +224,10 @@ class TestMetaMajorityMemoryOne(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + def test_strategy(self): self.first_play_test(C) @@ -222,6 +244,10 @@ class TestMetaWinnerMemoryOne(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + def test_strategy(self): self.first_play_test(C) @@ -237,6 +263,11 @@ class TestMetaMajorityFiniteMemory(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + + def test_strategy(self): self.first_play_test(C) @@ -252,6 +283,11 @@ class TestMetaWinnerFiniteMemory(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + + def test_strategy(self): self.first_play_test(C) @@ -267,6 +303,11 @@ class TestMetaMajorityLongMemory(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + + def test_strategy(self): self.first_play_test(C) @@ -282,6 +323,10 @@ class TestMetaWinnerLongMemory(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['stochastic'] = False + expected_class_classifier['makes_use_of'] = set([]) + def test_strategy(self): self.first_play_test(C) @@ -298,6 +343,9 @@ class TestMetaMixer(TestMetaPlayer): 'manipulates_state': False } + expected_class_classifier = copy.copy(expected_classifier) + expected_class_classifier['makes_use_of'] = set() + def test_strategy(self): team = [axelrod.TitForTat, axelrod.Cooperator, axelrod.Grudger] diff --git a/axelrod/tests/unit/test_player.py b/axelrod/tests/unit/test_player.py index 11a89e9a..601fd396 100644 --- a/axelrod/tests/unit/test_player.py +++ b/axelrod/tests/unit/test_player.py @@ -116,6 +116,7 @@ class TestOpponent(Player): class TestPlayer(unittest.TestCase): "A Test class from which other player test classes are inherited" player = TestOpponent + expected_class_classifier = None def test_initialisation(self): """Test that the player initiates correctly.""" @@ -126,7 +127,7 @@ class TestPlayer(unittest.TestCase): {'length': -1, 'game': DefaultGame, 'noise': 0}) self.assertEqual(player.cooperations, 0) self.assertEqual(player.defections, 0) - self.classifier_test() + self.classifier_test(self.expected_class_classifier) def test_repr(self): """Test that the representation is correct.""" @@ -237,12 +238,19 @@ class TestPlayer(unittest.TestCase): random_seed=random_seed, attrs=attrs) - def classifier_test(self): + def classifier_test(self, expected_class_classifier=None): """Test that the keys in the expected_classifier dictionary give the expected values in the player classifier dictionary. Also checks that two particular keys (memory_depth and stochastic) are in the dictionary.""" player = self.player() + + # Test that player has same classifier as it's class unless otherwise + # specified + if expected_class_classifier is None: + expected_class_classifier = player.classifier + self.assertEqual(expected_class_classifier, self.player.classifier) + self.assertTrue('memory_depth' in player.classifier, msg="memory_depth not in classifier") self.assertTrue('stochastic' in player.classifier,
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 3 }
0.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 -e git+https://github.com/Axelrod-Python/Axelrod.git@03dd1a9600965800125eeb8942b6b0a3dfacf29c#egg=Axelrod coverage==7.8.0 cycler==0.12.1 exceptiongroup==1.2.2 execnet==2.1.1 hypothesis==6.130.6 iniconfig==2.1.0 kiwisolver==1.4.7 matplotlib==3.3.4 numpy==2.0.2 packaging==24.2 pillow==11.1.0 pluggy==1.5.0 pyparsing==2.1.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 six==1.17.0 sortedcontainers==2.4.0 testfixtures==4.9.1 tomli==2.2.1 tqdm==3.4.0 typing_extensions==4.13.0
name: Axelrod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - coverage==7.8.0 - cycler==0.12.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - hypothesis==6.130.6 - iniconfig==2.1.0 - kiwisolver==1.4.7 - matplotlib==3.3.4 - numpy==2.0.2 - packaging==24.2 - pillow==11.1.0 - pluggy==1.5.0 - pyparsing==2.1.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - six==1.17.0 - sortedcontainers==2.4.0 - testfixtures==4.9.1 - tomli==2.2.1 - tqdm==3.4.0 - typing-extensions==4.13.0 prefix: /opt/conda/envs/Axelrod
[ "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority5::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority10::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority20::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority40::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority5::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority10::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority20::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority40::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaMixer::test_initialisation" ]
[]
[ "axelrod/tests/unit/test_gambler.py::TestPlayer::test_clone", "axelrod/tests/unit/test_gambler.py::TestPlayer::test_initialisation", "axelrod/tests/unit/test_gambler.py::TestPlayer::test_match_attributes", "axelrod/tests/unit/test_gambler.py::TestPlayer::test_repr", "axelrod/tests/unit/test_gambler.py::TestPlayer::test_reset", "axelrod/tests/unit/test_gambler.py::TestGambler::test_clone", "axelrod/tests/unit/test_gambler.py::TestGambler::test_defector_table", "axelrod/tests/unit/test_gambler.py::TestGambler::test_init", "axelrod/tests/unit/test_gambler.py::TestGambler::test_initialisation", "axelrod/tests/unit/test_gambler.py::TestGambler::test_match_attributes", "axelrod/tests/unit/test_gambler.py::TestGambler::test_repr", "axelrod/tests/unit/test_gambler.py::TestGambler::test_reset", "axelrod/tests/unit/test_gambler.py::TestGambler::test_strategy", "axelrod/tests/unit/test_gambler.py::TestPSOGambler::test_clone", "axelrod/tests/unit/test_gambler.py::TestPSOGambler::test_init", "axelrod/tests/unit/test_gambler.py::TestPSOGambler::test_initialisation", "axelrod/tests/unit/test_gambler.py::TestPSOGambler::test_match_attributes", "axelrod/tests/unit/test_gambler.py::TestPSOGambler::test_repr", "axelrod/tests/unit/test_gambler.py::TestPSOGambler::test_reset", "axelrod/tests/unit/test_gambler.py::TestPSOGambler::test_strategy", "axelrod/tests/unit/test_gambler.py::PSOGamblervsDefector::test_vs", "axelrod/tests/unit/test_gambler.py::PSOGamblervsCooperator::test_vs", "axelrod/tests/unit/test_gambler.py::PSOGamblervsTFT::test_vs", "axelrod/tests/unit/test_gambler.py::PSOGamblervsAlternator::test_vs", "axelrod/tests/unit/test_gobymajority.py::TestPlayer::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestPlayer::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestPlayer::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestPlayer::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestPlayer::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_default_soft", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_name", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_soft", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_default_soft", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_initialisation", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_name", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_soft", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority5::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority5::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority5::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority5::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority5::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority5::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority10::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority10::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority10::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority10::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority10::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority10::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority20::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority20::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority20::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority20::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority20::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority20::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority40::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority40::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority40::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority40::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority40::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestGoByMajority40::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority5::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority5::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority5::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority5::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority5::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority5::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority10::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority10::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority10::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority10::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority10::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority10::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority20::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority20::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority20::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority20::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority20::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority20::test_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority40::test_clone", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority40::test_initial_strategy", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority40::test_match_attributes", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority40::test_repr", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority40::test_reset", "axelrod/tests/unit/test_gobymajority.py::TestHardGoByMajority40::test_strategy", "axelrod/tests/unit/test_lookerup.py::TestPlayer::test_clone", "axelrod/tests/unit/test_lookerup.py::TestPlayer::test_initialisation", "axelrod/tests/unit/test_lookerup.py::TestPlayer::test_match_attributes", "axelrod/tests/unit/test_lookerup.py::TestPlayer::test_repr", "axelrod/tests/unit/test_lookerup.py::TestPlayer::test_reset", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_clone", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_defector_table", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_init", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_initialisation", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_match_attributes", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_repr", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_reset", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_starting_move", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_strategy", "axelrod/tests/unit/test_lookerup.py::TestLookerUp::test_zero_tables", "axelrod/tests/unit/test_lookerup.py::TestEvolvedLookerUp::test_clone", "axelrod/tests/unit/test_lookerup.py::TestEvolvedLookerUp::test_init", "axelrod/tests/unit/test_lookerup.py::TestEvolvedLookerUp::test_initialisation", "axelrod/tests/unit/test_lookerup.py::TestEvolvedLookerUp::test_match_attributes", "axelrod/tests/unit/test_lookerup.py::TestEvolvedLookerUp::test_repr", "axelrod/tests/unit/test_lookerup.py::TestEvolvedLookerUp::test_reset", "axelrod/tests/unit/test_lookerup.py::TestEvolvedLookerUp::test_strategy", "axelrod/tests/unit/test_lookerup.py::EvolvedLookerUpvsDefector::test_vs", "axelrod/tests/unit/test_lookerup.py::EvolvedLookerUpvsCooperator::test_vs", "axelrod/tests/unit/test_lookerup.py::EvolvedLookerUpvsTFT::test_vs", "axelrod/tests/unit/test_lookerup.py::EvolvedLookerUpvsAlternator::test_vs", "axelrod/tests/unit/test_meta.py::TestPlayer::test_clone", "axelrod/tests/unit/test_meta.py::TestPlayer::test_initialisation", "axelrod/tests/unit/test_meta.py::TestPlayer::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestPlayer::test_repr", "axelrod/tests/unit/test_meta.py::TestPlayer::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaPlayer::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaPlayer::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaPlayer::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaPlayer::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaPlayer::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaMajority::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaMajority::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaMajority::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaMajority::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaMajority::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaMajority::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaMinority::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaMinority::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaMinority::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaMinority::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaMinority::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaMinority::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaMinority::test_team", "axelrod/tests/unit/test_meta.py::TestMetaWinner::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaWinner::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaWinner::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaWinner::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaWinner::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaWinner::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaHunter::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaHunter::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaHunter::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaHunter::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaHunter::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaHunter::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaMajorityMemoryOne::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaMajorityMemoryOne::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaMajorityMemoryOne::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaMajorityMemoryOne::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaMajorityMemoryOne::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaMajorityMemoryOne::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaWinnerMemoryOne::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaWinnerMemoryOne::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaWinnerMemoryOne::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaWinnerMemoryOne::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaWinnerMemoryOne::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaWinnerMemoryOne::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaMajorityFiniteMemory::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaMajorityFiniteMemory::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaMajorityFiniteMemory::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaMajorityFiniteMemory::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaMajorityFiniteMemory::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaMajorityFiniteMemory::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaWinnerFiniteMemory::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaWinnerFiniteMemory::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaWinnerFiniteMemory::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaWinnerFiniteMemory::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaWinnerFiniteMemory::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaWinnerFiniteMemory::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaMajorityLongMemory::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaMajorityLongMemory::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaMajorityLongMemory::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaMajorityLongMemory::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaMajorityLongMemory::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaMajorityLongMemory::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaWinnerLongMemory::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaWinnerLongMemory::test_initialisation", "axelrod/tests/unit/test_meta.py::TestMetaWinnerLongMemory::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaWinnerLongMemory::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaWinnerLongMemory::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaWinnerLongMemory::test_strategy", "axelrod/tests/unit/test_meta.py::TestMetaMixer::test_clone", "axelrod/tests/unit/test_meta.py::TestMetaMixer::test_match_attributes", "axelrod/tests/unit/test_meta.py::TestMetaMixer::test_raise_error_in_distribution", "axelrod/tests/unit/test_meta.py::TestMetaMixer::test_repr", "axelrod/tests/unit/test_meta.py::TestMetaMixer::test_reset", "axelrod/tests/unit/test_meta.py::TestMetaMixer::test_strategy", "axelrod/tests/unit/test_player.py::TestPlayerClass::test_add_noise", "axelrod/tests/unit/test_player.py::TestPlayerClass::test_noisy_play", "axelrod/tests/unit/test_player.py::TestPlayerClass::test_play", "axelrod/tests/unit/test_player.py::TestPlayerClass::test_strategy", "axelrod/tests/unit/test_player.py::TestPlayer::test_clone", "axelrod/tests/unit/test_player.py::TestPlayer::test_initialisation", "axelrod/tests/unit/test_player.py::TestPlayer::test_match_attributes", "axelrod/tests/unit/test_player.py::TestPlayer::test_repr", "axelrod/tests/unit/test_player.py::TestPlayer::test_reset" ]
[]
MIT License
534
refnx__refnx-35
cd75b8c1b715bc9ae385e60e025baf1598a270a1
2016-05-13 02:48:29
568a56132fe0cd8418cff41ffedfc276bdb99af4
diff --git a/refnx/reduce/platypusnexus.py b/refnx/reduce/platypusnexus.py index ae28b951..f041c3ff 100644 --- a/refnx/reduce/platypusnexus.py +++ b/refnx/reduce/platypusnexus.py @@ -516,6 +516,9 @@ class PlatypusNexus(object): m_spec_tof_hist[:] = TOF - toffset flight_distance[:] = flight_distance[0] detpositions[:] = detpositions[0] + domega[:] = domega[0] + d_cx[:] = d_cx[0] + phase_angle[:] = phase_angle[0] break else: scanpoint += 1
Event mode reduction is not calculating the correct resolution for each timeslice
refnx/refnx
diff --git a/refnx/reduce/test/test_reduce.py b/refnx/reduce/test/test_reduce.py index 92f1f5f6..4b9f6990 100644 --- a/refnx/reduce/test/test_reduce.py +++ b/refnx/reduce/test/test_reduce.py @@ -3,7 +3,7 @@ import os.path import numpy as np from refnx.reduce import reduce_stitch, ReducePlatypus from numpy.testing import (assert_almost_equal, assert_, assert_equal, - assert_array_less) + assert_array_less, assert_allclose) import xml.etree.ElementTree as ET class TestReduce(unittest.TestCase): @@ -44,6 +44,11 @@ class TestReduce(unittest.TestCase): eventmode=[0, 900, 1800]) assert_equal(a.ydata.shape[0], 2) + # check that the resolutions are pretty much the same + assert_allclose(a.xdata_sd[0] / a.xdata[0], + a.xdata_sd[1] / a.xdata[1], + atol = 0.001) + # check that the right timestamps are written into the datafile tree = ET.parse(os.path.join(os.getcwd(), 'PLP0011641_1.xml')) t = tree.find('.//REFentry').attrib['time']
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 scipy>=1.0.0 emcee>=2.2.1 six>=1.11.0 uncertainties>=3.0.1 pandas>=0.23.4 pytest>=3.6.0 h5py>=2.8.0 xlrd>=1.1.0 ptemcee>=1.0.0", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asteval==0.9.26 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 emcee @ file:///home/conda/feedstock_root/build_artifacts/emcee_1713796893786/work future==0.18.2 h5py @ file:///tmp/build/80754af9/h5py_1593454121459/work importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work lmfit==1.0.3 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work ptemcee==1.0.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work pytz==2021.3 -e git+https://github.com/refnx/refnx.git@cd75b8c1b715bc9ae385e60e025baf1598a270a1#egg=refnx scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work six @ file:///tmp/build/80754af9/six_1644875935023/work toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work uncertainties @ file:///home/conda/feedstock_root/build_artifacts/uncertainties_1720452225073/work xlrd @ file:///croot/xlrd_1685030938141/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: refnx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - blas=1.0=openblas - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - emcee=3.1.6=pyhd8ed1ab_0 - future=0.18.2=py36_1 - h5py=2.10.0=py36hd6299e0_1 - hdf5=1.10.6=hb1b8bf9_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pandas=1.1.5=py36ha9443f7_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - ptemcee=1.0.0=py_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytz=2021.3=pyhd3eb1b0_0 - readline=8.2=h5eee18b_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - uncertainties=3.2.2=pyhd8ed1ab_1 - wheel=0.37.1=pyhd3eb1b0_0 - xlrd=2.0.1=pyhd3eb1b0_1 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - asteval==0.9.26 - lmfit==1.0.3 prefix: /opt/conda/envs/refnx
[ "refnx/reduce/test/test_reduce.py::TestReduce::test_event_reduction" ]
[]
[ "refnx/reduce/test/test_reduce.py::TestReduce::test_reduction_method", "refnx/reduce/test/test_reduce.py::TestReduce::test_smoke" ]
[]
BSD 3-Clause "New" or "Revised" License
535
adamtheturtle__todo-28
7666d2181cdea24c963f2d99f918fd368fefafef
2016-05-15 16:08:13
7666d2181cdea24c963f2d99f918fd368fefafef
diff --git a/authentication/authentication.py b/authentication/authentication.py index 7b64ff6..f9b7cee 100644 --- a/authentication/authentication.py +++ b/authentication/authentication.py @@ -288,6 +288,26 @@ def create_todo(): return jsonify(create.json()), create.status_code + [email protected]('/todos/<id>', methods=['GET']) +@consumes('application/json') +def read_todo(id): + """ + Get information about particular todo item. + + :reqheader Content-Type: application/json + :resheader Content-Type: application/json + :resjson string id: The id of the todo item. + :resjson boolean completed: Whether the item is completed. + :resjson number completion_time: The completion UNIX timestamp, or + ``null`` if there is none. + :status 200: The requested item's information is returned. + :status 404: There is no item with the given ``id``. + """ + url = urljoin(STORAGE_URL, 'todos/{id}').format(id=id) + response = requests.get(url, headers={'Content-Type': 'application/json'}) + return jsonify(response.json()), response.status_code + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally. diff --git a/storage/storage.py b/storage/storage.py index ae2db38..29189c9 100644 --- a/storage/storage.py +++ b/storage/storage.py @@ -218,6 +218,35 @@ def todos_post(): ), codes.CREATED [email protected]('/todos/<id>', methods=['GET']) +@consumes('application/json') +def specific_todo_get(id): + """ + Get information about particular todo item. + + :reqheader Content-Type: application/json + :resheader Content-Type: application/json + :resjson string id: The id of the todo item. + :resjson boolean completed: Whether the item is completed. + :resjson number completion_time: The completion UNIX timestamp, or + ``null`` if there is none. + :status 200: The requested item's information is returned. + :status 404: There is no item with the given ``id``. + """ + todo = Todo.query.filter_by(id=id).first() + + if todo is None: + return jsonify( + title='The requested todo does not exist.', + detail='No todo exists with the id "{id}"'.format(id=id), + ), codes.NOT_FOUND + + return jsonify( + content=todo.content, + completed=todo.completed, + completion_timestamp=todo.completion_timestamp, + ), codes.OK + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally.
Add ability to read a TODO item
adamtheturtle/todo
diff --git a/authentication/tests/test_authentication.py b/authentication/tests/test_authentication.py index c0da49d..25e8481 100644 --- a/authentication/tests/test_authentication.py +++ b/authentication/tests/test_authentication.py @@ -579,3 +579,123 @@ class CreateTodoTests(AuthenticationTests): """ response = self.app.post('/todos', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class ReadTodoTests(AuthenticationTests): + """ + Tests for getting a todo item at ``GET /todos/{id}.``. + """ + + @responses.activate + def test_success(self): + """ + A ``GET`` request for an existing todo an OK status code and the todo's + details. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + read = self.app.get( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(read.status_code, codes.OK) + expected = NOT_COMPLETED_TODO_DATA.copy() + expected['completion_timestamp'] = None + self.assertEqual(json.loads(read.data.decode('utf8')), expected) + + @responses.activate + @freeze_time(datetime.datetime.fromtimestamp(5, tz=pytz.utc)) + def test_completed(self): + """ + A ``GET`` request for an existing todo an OK status code and the todo's + details, included the completion timestamp. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + read = self.app.get( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(read.status_code, codes.OK) + expected = COMPLETED_TODO_DATA.copy() + expected['completion_timestamp'] = 5 + self.assertEqual(json.loads(read.data.decode('utf8')), expected) + + @responses.activate + def test_multiple_todos(self): + """ + A ``GET`` request gets the correct todo when there are multiple. + """ + self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + read = self.app.get( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(read.status_code, codes.OK) + expected = NOT_COMPLETED_TODO_DATA.copy() + expected['completion_timestamp'] = None + self.assertEqual(json.loads(read.data.decode('utf8')), expected) + + @responses.activate + def test_non_existant(self): + """ + A ``GET`` request for a todo which does not exist returns a NOT_FOUND + status code and error details. + """ + response = self.app.get('/todos/1', content_type='application/json') + + self.assertEqual(response.headers['Content-Type'], 'application/json') + self.assertEqual(response.status_code, codes.NOT_FOUND) + expected = { + 'title': 'The requested todo does not exist.', + 'detail': 'No todo exists with the id "1"', + } + self.assertEqual(json.loads(response.data.decode('utf8')), expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.app.get('/todos/1', content_type='text/html') + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) diff --git a/storage/tests/test_storage.py b/storage/tests/test_storage.py index 23feaba..e77676d 100644 --- a/storage/tests/test_storage.py +++ b/storage/tests/test_storage.py @@ -114,8 +114,8 @@ class GetUserTests(InMemoryStorageTests): def test_success(self): """ - A ``GET`` request for an existing user an OK status code and the user's - details. + A ``GET`` request for an existing user returns an OK status code and + the user's details. """ self.storage_app.post( '/users', @@ -304,3 +304,85 @@ class CreateTodoTests(InMemoryStorageTests): """ response = self.storage_app.post('/todos', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class GetTodoTests(InMemoryStorageTests): + """ + Tests for getting a todo item at ``GET /todos/{id}.``. + """ + + def test_success(self): + """ + A ``GET`` request for an existing todo an OK status code and the todo's + details. + """ + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + read = self.storage_app.get( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(read.status_code, codes.OK) + self.assertEqual(json.loads(read.data.decode('utf8')), TODO_DATA) + + def test_timestamp_null(self): + """ + If the timestamp is not given, the response includes a null timestamp. + """ + data = TODO_DATA.copy() + del data['completion_timestamp'] + + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(data), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + read = self.storage_app.get( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(read.status_code, codes.OK) + expected = TODO_DATA.copy() + expected['completion_timestamp'] = None + self.assertEqual(json.loads(read.data.decode('utf8')), expected) + + def test_non_existant(self): + """ + A ``GET`` request for a todo which does not exist returns a NOT_FOUND + status code and error details. + """ + response = self.storage_app.get( + '/todos/1', + content_type='application/json', + ) + + self.assertEqual(response.headers['Content-Type'], 'application/json') + self.assertEqual(response.status_code, codes.NOT_FOUND) + expected = { + 'title': 'The requested todo does not exist.', + 'detail': 'No todo exists with the id "1"', + } + self.assertEqual(json.loads(response.data.decode('utf8')), expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.storage_app.get('/todos/1', content_type='text/html') + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt", "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 bcrypt==4.0.1 certifi==2021.5.30 coverage==6.2 coveralls==3.3.1 dataclasses==0.8 doc8==0.11.2 docopt==0.6.2 docutils==0.17.1 execnet==1.9.0 flake8==5.0.4 Flask==0.10.1 Flask-Bcrypt==0.7.1 Flask-JsonSchema==0.1.1 Flask-Login==0.3.2 Flask-Negotiate==0.1.0 Flask-SQLAlchemy==2.1 freezegun==1.2.2 greenlet==2.0.2 imagesize==1.4.1 importlib-metadata==4.2.0 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==3.2.0 MarkupSafe==2.0.1 mccabe==0.7.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2016.4 -e git+https://github.com/adamtheturtle/todo.git@7666d2181cdea24c963f2d99f918fd368fefafef#egg=Qlutter_TODOer requests==2.10.0 responses==0.17.0 restructuredtext-lint==1.4.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==4.3.2 sphinx-rtd-theme==1.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-httpdomain==1.8.1 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 SQLAlchemy==1.4.54 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: todo channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - bcrypt==4.0.1 - coverage==6.2 - coveralls==3.3.1 - dataclasses==0.8 - doc8==0.11.2 - docopt==0.6.2 - docutils==0.17.1 - execnet==1.9.0 - flake8==5.0.4 - flask==0.10.1 - flask-bcrypt==0.7.1 - flask-jsonschema==0.1.1 - flask-login==0.3.2 - flask-negotiate==0.1.0 - flask-sqlalchemy==2.1 - freezegun==1.2.2 - greenlet==2.0.2 - imagesize==1.4.1 - importlib-metadata==4.2.0 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==3.2.0 - markupsafe==2.0.1 - mccabe==0.7.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2016.4 - requests==2.10.0 - responses==0.17.0 - restructuredtext-lint==1.4.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==4.3.2 - sphinx-rtd-theme==1.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-httpdomain==1.8.1 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlalchemy==1.4.54 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/todo
[ "authentication/tests/test_authentication.py::ReadTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetTodoTests::test_incorrect_content_type" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_existing_user", "authentication/tests/test_authentication.py::SignupTests::test_missing_email", "authentication/tests/test_authentication.py::SignupTests::test_missing_password", "authentication/tests/test_authentication.py::SignupTests::test_passwords_hashed", "authentication/tests/test_authentication.py::SignupTests::test_signup", "authentication/tests/test_authentication.py::LoginTests::test_login", "authentication/tests/test_authentication.py::LoginTests::test_missing_email", "authentication/tests/test_authentication.py::LoginTests::test_missing_password", "authentication/tests/test_authentication.py::LoginTests::test_non_existant_user", "authentication/tests/test_authentication.py::LoginTests::test_remember_me_cookie_set", "authentication/tests/test_authentication.py::LoginTests::test_wrong_password", "authentication/tests/test_authentication.py::LogoutTests::test_logout", "authentication/tests/test_authentication.py::LoadUserTests::test_user_does_not_exist", "authentication/tests/test_authentication.py::LoadUserTests::test_user_exists", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_fake_token", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_load_user_from_token", "authentication/tests/test_authentication.py::CreateTodoTests::test_current_completion_time", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_completed_flag", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_text", "authentication/tests/test_authentication.py::CreateTodoTests::test_success_response", "authentication/tests/test_authentication.py::ReadTodoTests::test_completed", "authentication/tests/test_authentication.py::ReadTodoTests::test_multiple_todos", "authentication/tests/test_authentication.py::ReadTodoTests::test_non_existant", "authentication/tests/test_authentication.py::ReadTodoTests::test_success", "storage/tests/test_storage.py::CreateUserTests::test_existing_user", "storage/tests/test_storage.py::CreateUserTests::test_missing_email", "storage/tests/test_storage.py::CreateUserTests::test_missing_password_hash", "storage/tests/test_storage.py::CreateUserTests::test_success_response", "storage/tests/test_storage.py::GetUserTests::test_non_existant_user", "storage/tests/test_storage.py::GetUserTests::test_success", "storage/tests/test_storage.py::GetUsersTests::test_with_users", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completed_flag", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completion_time", "storage/tests/test_storage.py::CreateTodoTests::test_missing_text", "storage/tests/test_storage.py::CreateTodoTests::test_success_response", "storage/tests/test_storage.py::GetTodoTests::test_non_existant", "storage/tests/test_storage.py::GetTodoTests::test_success", "storage/tests/test_storage.py::GetTodoTests::test_timestamp_null" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LoginTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_logout_twice", "authentication/tests/test_authentication.py::LogoutTests::test_not_logged_in", "authentication/tests/test_authentication.py::UserTests::test_different_password_different_token", "authentication/tests/test_authentication.py::UserTests::test_get_auth_token", "authentication/tests/test_authentication.py::UserTests::test_get_id", "authentication/tests/test_authentication.py::CreateTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::CreateUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_no_users", "storage/tests/test_storage.py::CreateTodoTests::test_incorrect_content_type" ]
[]
null
536
adamtheturtle__todo-35
418d1cc9a4fea4d7332715aa8b57eb13b65130c6
2016-05-15 19:03:18
418d1cc9a4fea4d7332715aa8b57eb13b65130c6
diff --git a/README.md b/README.md index 6906cef..71463e4 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ To start developing quickly, it is recommended that you create a `virtualenv` wi Tests are run on [Travis-CI](https://travis-ci.org/adamtheturtle/todo). +See `.travis.yml` for details of exactly what tests are run. ### Documentation diff --git a/authentication/authentication.py b/authentication/authentication.py index f9b7cee..4a66953 100644 --- a/authentication/authentication.py +++ b/authentication/authentication.py @@ -293,7 +293,7 @@ def create_todo(): @consumes('application/json') def read_todo(id): """ - Get information about particular todo item. + Get information about a particular todo item. :reqheader Content-Type: application/json :resheader Content-Type: application/json @@ -308,6 +308,23 @@ def read_todo(id): response = requests.get(url, headers={'Content-Type': 'application/json'}) return jsonify(response.json()), response.status_code + [email protected]('/todos/<id>', methods=['DELETE']) +@consumes('application/json') +def delete_todo(id): + """ + Delete a particular todo item. + + :reqheader Content-Type: application/json + :resheader Content-Type: application/json + :status 200: The requested item's information is returned. + :status 404: There is no item with the given ``id``. + """ + url = urljoin(STORAGE_URL, 'todos/{id}').format(id=id) + headers = {'Content-Type': 'application/json'} + response = requests.delete(url, headers=headers) + return jsonify(response.json()), response.status_code + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally. diff --git a/storage/storage.py b/storage/storage.py index 29189c9..c5b3224 100644 --- a/storage/storage.py +++ b/storage/storage.py @@ -242,11 +242,37 @@ def specific_todo_get(id): ), codes.NOT_FOUND return jsonify( + # TODO needs ID content=todo.content, completed=todo.completed, completion_timestamp=todo.completion_timestamp, ), codes.OK + [email protected]('/todos/<id>', methods=['DELETE']) +@consumes('application/json') +def delete_todo(id): + """ + Delete a particular todo item. + + :reqheader Content-Type: application/json + :resheader Content-Type: application/json + :status 200: The requested item's information is returned. + :status 404: There is no item with the given ``id``. + """ + todo = Todo.query.filter_by(id=id).first() + + if todo is None: + return jsonify( + title='The requested todo does not exist.', + detail='No todo exists with the id "{id}"'.format(id=id), + ), codes.NOT_FOUND + + db.session.delete(todo) + db.session.commit() + + return jsonify(), codes.OK + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally.
Add ability to delete a TODO item
adamtheturtle/todo
diff --git a/authentication/tests/test_authentication.py b/authentication/tests/test_authentication.py index 25e8481..85d152c 100644 --- a/authentication/tests/test_authentication.py +++ b/authentication/tests/test_authentication.py @@ -699,3 +699,80 @@ class ReadTodoTests(AuthenticationTests): """ response = self.app.get('/todos/1', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class DeleteTodoTests(AuthenticationTests): + """ + Tests for deleting a todo item at ``DELETE /todos/{id}.``. + """ + + @responses.activate + def test_success(self): + """ + It is possible to delete a todo item. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + delete = self.app.delete( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(delete.status_code, codes.OK) + + read = self.app.get( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(read.status_code, codes.NOT_FOUND) + + @responses.activate + def test_delete_twice(self): + """ + Deleting an item twice gives returns a 404 code and error message. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + self.app.delete( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + delete = self.app.delete( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(delete.status_code, codes.NOT_FOUND) + expected = { + 'title': 'The requested todo does not exist.', + 'detail': 'No todo exists with the id "1"', + } + self.assertEqual(json.loads(delete.data.decode('utf8')), expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.app.delete('/todos/1', content_type='text/html') + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) diff --git a/storage/tests/test_storage.py b/storage/tests/test_storage.py index e77676d..401fd2a 100644 --- a/storage/tests/test_storage.py +++ b/storage/tests/test_storage.py @@ -386,3 +386,81 @@ class GetTodoTests(InMemoryStorageTests): """ response = self.storage_app.get('/todos/1', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class DeleteTodoTests(InMemoryStorageTests): + """ + Tests for deleting a todo item at ``DELETE /todos/{id}.``. + """ + + def test_success(self): + """ + It is possible to delete a todo item. + """ + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + delete = self.storage_app.delete( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(delete.status_code, codes.OK) + + read = self.storage_app.get( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(read.status_code, codes.NOT_FOUND) + + def test_delete_twice(self): + """ + Deleting an item twice gives returns a 404 code and error message. + """ + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(TODO_DATA), + ) + + create_data = json.loads(create.data.decode('utf8')) + item_id = create_data['id'] + + self.storage_app.delete( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + delete = self.storage_app.delete( + '/todos/{id}'.format(id=item_id), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(delete.status_code, codes.NOT_FOUND) + expected = { + 'title': 'The requested todo does not exist.', + 'detail': 'No todo exists with the id "1"', + } + self.assertEqual(json.loads(delete.data.decode('utf8')), expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.storage_app.delete( + '/todos/1', + content_type='text/html', + ) + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt", "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 bcrypt==4.0.1 certifi==2021.5.30 coverage==6.2 coveralls==3.3.1 dataclasses==0.8 doc8==0.11.2 docopt==0.6.2 docutils==0.18.1 execnet==1.9.0 flake8==3.9.2 Flask==0.10.1 Flask-Bcrypt==0.7.1 Flask-JsonSchema==0.1.1 Flask-Login==0.3.2 Flask-Negotiate==0.1.0 Flask-SQLAlchemy==2.1 freezegun==1.2.2 greenlet==2.0.2 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==3.2.0 MarkupSafe==2.0.1 mccabe==0.6.1 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2016.4 -e git+https://github.com/adamtheturtle/todo.git@418d1cc9a4fea4d7332715aa8b57eb13b65130c6#egg=Qlutter_TODOer requests==2.10.0 responses==0.17.0 restructuredtext-lint==1.4.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-httpdomain==1.8.1 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 SQLAlchemy==1.4.54 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: todo channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - bcrypt==4.0.1 - coverage==6.2 - coveralls==3.3.1 - dataclasses==0.8 - doc8==0.11.2 - docopt==0.6.2 - docutils==0.18.1 - execnet==1.9.0 - flake8==3.9.2 - flask==0.10.1 - flask-bcrypt==0.7.1 - flask-jsonschema==0.1.1 - flask-login==0.3.2 - flask-negotiate==0.1.0 - flask-sqlalchemy==2.1 - freezegun==1.2.2 - greenlet==2.0.2 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==3.2.0 - markupsafe==2.0.1 - mccabe==0.6.1 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2016.4 - requests==2.10.0 - responses==0.17.0 - restructuredtext-lint==1.4.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-httpdomain==1.8.1 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlalchemy==1.4.54 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/todo
[ "authentication/tests/test_authentication.py::DeleteTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::DeleteTodoTests::test_incorrect_content_type" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_existing_user", "authentication/tests/test_authentication.py::SignupTests::test_missing_email", "authentication/tests/test_authentication.py::SignupTests::test_missing_password", "authentication/tests/test_authentication.py::SignupTests::test_passwords_hashed", "authentication/tests/test_authentication.py::SignupTests::test_signup", "authentication/tests/test_authentication.py::LoginTests::test_login", "authentication/tests/test_authentication.py::LoginTests::test_missing_email", "authentication/tests/test_authentication.py::LoginTests::test_missing_password", "authentication/tests/test_authentication.py::LoginTests::test_non_existant_user", "authentication/tests/test_authentication.py::LoginTests::test_remember_me_cookie_set", "authentication/tests/test_authentication.py::LoginTests::test_wrong_password", "authentication/tests/test_authentication.py::LogoutTests::test_logout", "authentication/tests/test_authentication.py::LoadUserTests::test_user_does_not_exist", "authentication/tests/test_authentication.py::LoadUserTests::test_user_exists", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_fake_token", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_load_user_from_token", "authentication/tests/test_authentication.py::CreateTodoTests::test_current_completion_time", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_completed_flag", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_text", "authentication/tests/test_authentication.py::CreateTodoTests::test_success_response", "authentication/tests/test_authentication.py::ReadTodoTests::test_completed", "authentication/tests/test_authentication.py::ReadTodoTests::test_multiple_todos", "authentication/tests/test_authentication.py::ReadTodoTests::test_non_existant", "authentication/tests/test_authentication.py::ReadTodoTests::test_success", "authentication/tests/test_authentication.py::DeleteTodoTests::test_delete_twice", "authentication/tests/test_authentication.py::DeleteTodoTests::test_success", "storage/tests/test_storage.py::CreateUserTests::test_existing_user", "storage/tests/test_storage.py::CreateUserTests::test_missing_email", "storage/tests/test_storage.py::CreateUserTests::test_missing_password_hash", "storage/tests/test_storage.py::CreateUserTests::test_success_response", "storage/tests/test_storage.py::GetUserTests::test_non_existant_user", "storage/tests/test_storage.py::GetUserTests::test_success", "storage/tests/test_storage.py::GetUsersTests::test_with_users", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completed_flag", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completion_time", "storage/tests/test_storage.py::CreateTodoTests::test_missing_text", "storage/tests/test_storage.py::CreateTodoTests::test_success_response", "storage/tests/test_storage.py::GetTodoTests::test_non_existant", "storage/tests/test_storage.py::GetTodoTests::test_success", "storage/tests/test_storage.py::GetTodoTests::test_timestamp_null", "storage/tests/test_storage.py::DeleteTodoTests::test_delete_twice", "storage/tests/test_storage.py::DeleteTodoTests::test_success" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LoginTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_logout_twice", "authentication/tests/test_authentication.py::LogoutTests::test_not_logged_in", "authentication/tests/test_authentication.py::UserTests::test_different_password_different_token", "authentication/tests/test_authentication.py::UserTests::test_get_auth_token", "authentication/tests/test_authentication.py::UserTests::test_get_id", "authentication/tests/test_authentication.py::CreateTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::ReadTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::CreateUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_no_users", "storage/tests/test_storage.py::CreateTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetTodoTests::test_incorrect_content_type" ]
[]
null
537
adamtheturtle__todo-39
e62c632ff6b104c40fd0f4580f4e2c8a2f084026
2016-05-15 22:33:10
e62c632ff6b104c40fd0f4580f4e2c8a2f084026
diff --git a/authentication/authentication.py b/authentication/authentication.py index bccc34e..ff1d8a1 100644 --- a/authentication/authentication.py +++ b/authentication/authentication.py @@ -154,10 +154,9 @@ def login(): """ Log in a given user. - :param email: An email address to log in as. - :type email: string - :param password: A password associated with the given ``email`` address. - :type password: string + :reqjson string email: An email address to log in as. + :reqjson string password: A password associated with the given ``email`` + address. :reqheader Content-Type: application/json :resheader Content-Type: application/json :resheader Set-Cookie: A ``remember_token``. @@ -212,10 +211,9 @@ def signup(): """ Sign up a new user. - :param email: The email address of the new user. - :type email: string - :param password: A password to associate with the given ``email`` address. - :type password: string + :reqjson string email: The email address of the new user. + :reqjson string password: A password to associate with the given ``email`` + address. :reqheader Content-Type: application/json :resheader Content-Type: application/json :resjson string email: The email address of the new user. @@ -256,13 +254,10 @@ def create_todo(): """ Create a new todo item. - :param content: The content of the new item. - :type content: string - :param completed: Whether the item is completed. - :type completed: boolean - :reqheader Content-Type: application/json :resheader Content-Type: application/json + :reqjson string content: The content of the new item. + :reqjson boolean completed: Whether the item is completed. :resjson string id: The id of the todo item. :resjson string content: The content of the new item. :resjson boolean completed: Whether the item is completed. @@ -298,9 +293,9 @@ def read_todo(id): :reqheader Content-Type: application/json :resheader Content-Type: application/json - :resjson string id: The id of the todo item. + :queryparameter number id: The id of the todo item. :resjson boolean completed: Whether the item is completed. - :resjson number completion_time: The completion UNIX timestamp, or + :resjson number completion_timestamp: The completion UNIX timestamp, or ``null`` if there is none. :status 200: The requested item's information is returned. :status 404: There is no item with the given ``id``. @@ -318,6 +313,7 @@ def delete_todo(id): :reqheader Content-Type: application/json :resheader Content-Type: application/json + :queryparameter number id: The id of the todo item. :status 200: The requested item's information is returned. :status 404: There is no item with the given ``id``. """ @@ -326,6 +322,26 @@ def delete_todo(id): response = requests.delete(url, headers=headers) return jsonify(response.json()), response.status_code + [email protected]('/todos', methods=['GET']) +@consumes('application/json') +def list_todos(): + """ + List todo items. + + :reqheader Content-Type: application/json + :resheader Content-Type: application/json + :resjsonarr boolean completed: Whether the item is completed. + :resjsonarr number completion_timestamp: The completion UNIX timestamp, or + ``null`` if there is none. + :status 200: The requested item's information is returned. + :status 404: There is no item with the given ``id``. + """ + url = urljoin(STORAGE_URL, 'todos') + headers = {'Content-Type': 'application/json'} + response = requests.get(url, headers=headers) + return jsonify(response.json()), response.status_code + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally. diff --git a/docs/source/index.rst b/docs/source/index.rst index 526acaa..c83eeab 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,14 +1,5 @@ -Welcome to ``todoer``'s documentation! -====================================== - -Authentication Service API Endpoints ------------------------------------- +``todoer`` API Documentation +============================ .. autoflask:: authentication.authentication:app :undoc-static: - -Storage Service API Endpoints ------------------------------ - -.. autoflask:: storage.storage:app - :undoc-static: diff --git a/storage/storage.py b/storage/storage.py index 19a4cc2..d79e4f7 100644 --- a/storage/storage.py +++ b/storage/storage.py @@ -33,6 +33,17 @@ class Todo(db.Model): completed = db.Column(db.Boolean) completion_timestamp = db.Column(db.Integer) + def as_dict(self): + """ + Return a representation of a todo item suitable for JSON responses. + """ + return dict( + id=self.id, + content=self.content, + completed=self.completed, + completion_timestamp=self.completion_timestamp, + ) + def create_app(database_uri): """ @@ -211,12 +222,7 @@ def todos_post(): db.session.add(todo) db.session.commit() - return jsonify( - id=todo.id, - content=todo.content, - completed=todo.completed, - completion_timestamp=todo.completion_timestamp, - ), codes.CREATED + return jsonify(todo.as_dict()), codes.CREATED @app.route('/todos/<id>', methods=['GET']) @@ -242,12 +248,7 @@ def specific_todo_get(id): detail='No todo exists with the id "{id}"'.format(id=id), ), codes.NOT_FOUND - return jsonify( - id=todo.id, - content=todo.content, - completed=todo.completed, - completion_timestamp=todo.completion_timestamp, - ), codes.OK + return jsonify(todo.as_dict()), codes.OK @app.route('/todos/<id>', methods=['DELETE']) @@ -274,6 +275,24 @@ def delete_todo(id): return jsonify(), codes.OK + [email protected]('/todos', methods=['GET']) +@consumes('application/json') +def list_todos(): + """ + List todo items. + + :reqheader Content-Type: application/json + :resheader Content-Type: application/json + :resjsonarr boolean completed: Whether the item is completed. + :resjsonarr number completion_timestamp: The completion UNIX timestamp, or + ``null`` if there is none. + :status 200: The requested item's information is returned. + :status 404: There is no item with the given ``id``. + """ + todos = [todo.as_dict() for todo in Todo.query.all()] + return jsonify(todos=todos), codes.OK + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally.
Add ability to list all TODOs
adamtheturtle/todo
diff --git a/authentication/tests/test_authentication.py b/authentication/tests/test_authentication.py index 124aa3b..f6bf0e5 100644 --- a/authentication/tests/test_authentication.py +++ b/authentication/tests/test_authentication.py @@ -583,7 +583,7 @@ class CreateTodoTests(AuthenticationTests): class ReadTodoTests(AuthenticationTests): """ - Tests for getting a todo item at ``GET /todos/{id}.``. + Tests for getting a todo item at ``GET /todos/{id}``. """ @responses.activate @@ -604,7 +604,6 @@ class ReadTodoTests(AuthenticationTests): read = self.app.get( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(read.status_code, codes.OK) @@ -632,7 +631,6 @@ class ReadTodoTests(AuthenticationTests): read = self.app.get( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(read.status_code, codes.OK) @@ -670,7 +668,6 @@ class ReadTodoTests(AuthenticationTests): read = self.app.get( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(read.status_code, codes.OK) @@ -726,7 +723,6 @@ class DeleteTodoTests(AuthenticationTests): delete = self.app.delete( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(delete.status_code, codes.OK) @@ -734,7 +730,6 @@ class DeleteTodoTests(AuthenticationTests): read = self.app.get( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(read.status_code, codes.NOT_FOUND) @@ -756,13 +751,11 @@ class DeleteTodoTests(AuthenticationTests): self.app.delete( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) delete = self.app.delete( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(delete.status_code, codes.NOT_FOUND) @@ -779,3 +772,63 @@ class DeleteTodoTests(AuthenticationTests): """ response = self.app.delete('/todos/1', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class ListTodosTests(AuthenticationTests): + """ + Tests for listing todo items at ``GET /todos``. + """ + + @responses.activate + def test_no_todos(self): + """ + When there are no todos, an empty array is returned. + """ + list_todos = self.app.get( + '/todos', + content_type='application/json', + ) + + list_todos_data = json.loads(list_todos.data.decode('utf8')) + + self.assertEqual(list_todos.status_code, codes.OK) + self.assertEqual(list_todos_data['todos'], []) + + @responses.activate + def test_list(self): + """ + All todos are listed. + """ + other_todo = NOT_COMPLETED_TODO_DATA.copy() + other_todo['content'] = 'Get a haircut' + + todos = [NOT_COMPLETED_TODO_DATA, other_todo] + expected = [] + for index, data in enumerate(todos): + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(data), + ) + create_data = json.loads(create.data.decode('utf8')) + expected_data = data.copy() + expected_data['id'] = create_data['id'] + expected_data['completion_timestamp'] = None + expected.append(expected_data) + + list_todos = self.app.get( + '/todos', + content_type='application/json', + ) + + self.assertEqual(list_todos.status_code, codes.OK) + list_todos_data = json.loads(list_todos.data.decode('utf8')) + self.assertEqual(list_todos_data['todos'], expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.app.get('/todos', content_type='text/html') + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) diff --git a/storage/tests/test_storage.py b/storage/tests/test_storage.py index 98cfa5f..8bb35a4 100644 --- a/storage/tests/test_storage.py +++ b/storage/tests/test_storage.py @@ -328,7 +328,6 @@ class GetTodoTests(InMemoryStorageTests): read = self.storage_app.get( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(read.status_code, codes.OK) @@ -355,7 +354,6 @@ class GetTodoTests(InMemoryStorageTests): read = self.storage_app.get( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(read.status_code, codes.OK) @@ -412,7 +410,6 @@ class DeleteTodoTests(InMemoryStorageTests): delete = self.storage_app.delete( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(delete.status_code, codes.OK) @@ -420,7 +417,6 @@ class DeleteTodoTests(InMemoryStorageTests): read = self.storage_app.get( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(read.status_code, codes.NOT_FOUND) @@ -441,13 +437,11 @@ class DeleteTodoTests(InMemoryStorageTests): self.storage_app.delete( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) delete = self.storage_app.delete( '/todos/{id}'.format(id=item_id), content_type='application/json', - data=json.dumps({}), ) self.assertEqual(delete.status_code, codes.NOT_FOUND) @@ -467,3 +461,60 @@ class DeleteTodoTests(InMemoryStorageTests): content_type='text/html', ) self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class ListTodosTests(InMemoryStorageTests): + """ + Tests for listing todo items at ``GET /todos``. + """ + + def test_no_todos(self): + """ + When there are no todos, an empty array is returned. + """ + list_todos = self.storage_app.get( + '/todos', + content_type='application/json', + ) + + list_todos_data = json.loads(list_todos.data.decode('utf8')) + + self.assertEqual(list_todos.status_code, codes.OK) + self.assertEqual(list_todos_data['todos'], []) + + def test_list(self): + """ + All todos are listed. + """ + other_todo = TODO_DATA.copy() + other_todo['content'] = 'Get a haircut' + + todos = [TODO_DATA, other_todo] + expected = [] + for index, data in enumerate(todos): + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(data), + ) + create_data = json.loads(create.data.decode('utf8')) + expected_data = data.copy() + expected_data['id'] = create_data['id'] + expected.append(expected_data) + + list_todos = self.storage_app.get( + '/todos', + content_type='application/json', + ) + + self.assertEqual(list_todos.status_code, codes.OK) + list_todos_data = json.loads(list_todos.data.decode('utf8')) + self.assertEqual(list_todos_data['todos'], expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.storage_app.get('/todos', content_type='text/html') + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt", "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 bcrypt==4.0.1 certifi==2021.5.30 coverage==6.2 coveralls==3.3.1 dataclasses==0.8 doc8==0.11.2 docopt==0.6.2 docutils==0.18.1 execnet==1.9.0 flake8==3.9.2 Flask==0.10.1 Flask-Bcrypt==0.7.1 Flask-JsonSchema==0.1.1 Flask-Login==0.3.2 Flask-Negotiate==0.1.0 Flask-SQLAlchemy==2.1 freezegun==1.2.2 greenlet==2.0.2 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==3.2.0 MarkupSafe==2.0.1 mccabe==0.6.1 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2016.4 -e git+https://github.com/adamtheturtle/todo.git@e62c632ff6b104c40fd0f4580f4e2c8a2f084026#egg=Qlutter_TODOer requests==2.10.0 responses==0.17.0 restructuredtext-lint==1.4.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-httpdomain==1.8.1 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 SQLAlchemy==1.4.54 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: todo channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - bcrypt==4.0.1 - coverage==6.2 - coveralls==3.3.1 - dataclasses==0.8 - doc8==0.11.2 - docopt==0.6.2 - docutils==0.18.1 - execnet==1.9.0 - flake8==3.9.2 - flask==0.10.1 - flask-bcrypt==0.7.1 - flask-jsonschema==0.1.1 - flask-login==0.3.2 - flask-negotiate==0.1.0 - flask-sqlalchemy==2.1 - freezegun==1.2.2 - greenlet==2.0.2 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==3.2.0 - markupsafe==2.0.1 - mccabe==0.6.1 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2016.4 - requests==2.10.0 - responses==0.17.0 - restructuredtext-lint==1.4.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-httpdomain==1.8.1 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlalchemy==1.4.54 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/todo
[ "authentication/tests/test_authentication.py::ListTodosTests::test_incorrect_content_type", "storage/tests/test_storage.py::ListTodosTests::test_incorrect_content_type" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_existing_user", "authentication/tests/test_authentication.py::SignupTests::test_missing_email", "authentication/tests/test_authentication.py::SignupTests::test_missing_password", "authentication/tests/test_authentication.py::SignupTests::test_passwords_hashed", "authentication/tests/test_authentication.py::SignupTests::test_signup", "authentication/tests/test_authentication.py::LoginTests::test_login", "authentication/tests/test_authentication.py::LoginTests::test_missing_email", "authentication/tests/test_authentication.py::LoginTests::test_missing_password", "authentication/tests/test_authentication.py::LoginTests::test_non_existant_user", "authentication/tests/test_authentication.py::LoginTests::test_remember_me_cookie_set", "authentication/tests/test_authentication.py::LoginTests::test_wrong_password", "authentication/tests/test_authentication.py::LogoutTests::test_logout", "authentication/tests/test_authentication.py::LoadUserTests::test_user_does_not_exist", "authentication/tests/test_authentication.py::LoadUserTests::test_user_exists", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_fake_token", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_load_user_from_token", "authentication/tests/test_authentication.py::CreateTodoTests::test_current_completion_time", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_completed_flag", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_text", "authentication/tests/test_authentication.py::CreateTodoTests::test_success_response", "authentication/tests/test_authentication.py::ReadTodoTests::test_completed", "authentication/tests/test_authentication.py::ReadTodoTests::test_multiple_todos", "authentication/tests/test_authentication.py::ReadTodoTests::test_non_existant", "authentication/tests/test_authentication.py::ReadTodoTests::test_success", "authentication/tests/test_authentication.py::DeleteTodoTests::test_delete_twice", "authentication/tests/test_authentication.py::DeleteTodoTests::test_success", "authentication/tests/test_authentication.py::ListTodosTests::test_list", "authentication/tests/test_authentication.py::ListTodosTests::test_no_todos", "storage/tests/test_storage.py::CreateUserTests::test_existing_user", "storage/tests/test_storage.py::CreateUserTests::test_missing_email", "storage/tests/test_storage.py::CreateUserTests::test_missing_password_hash", "storage/tests/test_storage.py::CreateUserTests::test_success_response", "storage/tests/test_storage.py::GetUserTests::test_non_existant_user", "storage/tests/test_storage.py::GetUserTests::test_success", "storage/tests/test_storage.py::GetUsersTests::test_with_users", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completed_flag", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completion_time", "storage/tests/test_storage.py::CreateTodoTests::test_missing_text", "storage/tests/test_storage.py::CreateTodoTests::test_success_response", "storage/tests/test_storage.py::GetTodoTests::test_non_existant", "storage/tests/test_storage.py::GetTodoTests::test_success", "storage/tests/test_storage.py::GetTodoTests::test_timestamp_null", "storage/tests/test_storage.py::DeleteTodoTests::test_delete_twice", "storage/tests/test_storage.py::DeleteTodoTests::test_success", "storage/tests/test_storage.py::ListTodosTests::test_list", "storage/tests/test_storage.py::ListTodosTests::test_no_todos" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LoginTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_logout_twice", "authentication/tests/test_authentication.py::LogoutTests::test_not_logged_in", "authentication/tests/test_authentication.py::UserTests::test_different_password_different_token", "authentication/tests/test_authentication.py::UserTests::test_get_auth_token", "authentication/tests/test_authentication.py::UserTests::test_get_id", "authentication/tests/test_authentication.py::CreateTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::ReadTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::DeleteTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::CreateUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_no_users", "storage/tests/test_storage.py::CreateTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::DeleteTodoTests::test_incorrect_content_type" ]
[]
null
538
adamtheturtle__todo-46
736849d28dacdf6112fe2bef70aec1b6ceced636
2016-05-16 20:47:11
736849d28dacdf6112fe2bef70aec1b6ceced636
diff --git a/authentication/authentication.py b/authentication/authentication.py index c123d4f..445bcc7 100644 --- a/authentication/authentication.py +++ b/authentication/authentication.py @@ -327,7 +327,7 @@ def delete_todo(id): @consumes('application/json') def list_todos(): """ - List todo items. + List todo items, with optional filters. :reqheader Content-Type: application/json :resheader Content-Type: application/json @@ -346,6 +346,52 @@ def list_todos(): ) return jsonify(response.json()), response.status_code + [email protected]('/todos/<id>', methods=['PATCH']) +@consumes('application/json') +def update_todo(id): + """ + Update a todo item. If an item is changed from not-completed to completed, + the ``completion_timestamp`` is set as now. + + :reqheader Content-Type: application/json + + :queryparameter number id: The id of the todo item. + + :reqjson string content: The new of the item (optional). + :reqjson boolean completed: Whether the item is completed (optional). + + :resheader Content-Type: application/json + + :resjson string id: The id of the item. + :resjson string content: The content item. + :resjson boolean completed: Whether the item is completed. + :resjson number completion_timestamp: The completion UNIX timestamp (now), + or ``null`` if the item is not completed. + + :status 200: An item with the given details has been created. + :status 404: There is no item with the given ``id``. + """ + get_response, get_status_code = read_todo(id) + + if not get_status_code == codes.OK: + return jsonify(get_response.json), get_status_code + + already_completed = get_response.json['completed'] + data = json.loads(request.data) + if data.get('completed') and not already_completed: + now = datetime.datetime.now(tz=pytz.utc) + data['completion_timestamp'] = now.timestamp() + elif data.get('completed') is False: + data['completion_timestamp'] = None + + response = requests.patch( + urljoin(STORAGE_URL, 'todos/{id}').format(id=id), + headers={'Content-Type': 'application/json'}, + data=json.dumps(data), + ) + return jsonify(response.json()), response.status_code + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally. diff --git a/storage/storage.py b/storage/storage.py index e596f8d..4027848 100644 --- a/storage/storage.py +++ b/storage/storage.py @@ -298,6 +298,53 @@ def list_todos(): todos = Todo.query.filter_by(**todo_filter).all() return jsonify(todos=[todo.as_dict() for todo in todos]), codes.OK + [email protected]('/todos/<id>', methods=['PATCH']) +@consumes('application/json') +def update_todo(id): + """ + Update a todo item. + + :reqheader Content-Type: application/json + + :queryparameter number id: The id of the todo item. + + :reqjson string content: The new of the item. + :reqjson boolean completed: Whether the item is completed. + :reqjson number completion_timestamp: The completion UNIX timestamp, or + ``null``. + + :resheader Content-Type: application/json + + :resjson string id: The id of the item. + :resjson string content: The content item. + :resjson boolean completed: Whether the item is completed. + :resjson number completion_timestamp: The completion UNIX timestamp (now), + or ``null`` if the item is not completed. + + :status 200: An item with the given details has been created. + :status 404: There is no item with the given ``id``. + """ + todo = Todo.query.filter_by(id=id).first() + + if todo is None: + return jsonify( + title='The requested todo does not exist.', + detail='No todo exists with the id "{id}"'.format(id=id), + ), codes.NOT_FOUND + + if 'content' in request.json: + todo.content = request.json['content'] + + if 'completed' in request.json: + todo.completed = request.json['completed'] + + if 'completion_timestamp' in request.json: + todo.completion_timestamp = request.json['completion_timestamp'] + + db.session.commit() + return jsonify(todo.as_dict()), codes.OK + if __name__ == '__main__': # pragma: no cover # Specifying 0.0.0.0 as the host tells the operating system to listen on # all public IPs. This makes the server visible externally.
Add ability to update a TODO item (PATCH)
adamtheturtle/todo
diff --git a/authentication/tests/test_authentication.py b/authentication/tests/test_authentication.py index 2a76131..6f7108a 100644 --- a/authentication/tests/test_authentication.py +++ b/authentication/tests/test_authentication.py @@ -884,3 +884,220 @@ class ListTodosTests(AuthenticationTests): """ response = self.app.get('/todos', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class UpdateTodoTests(AuthenticationTests): + """ + Tests for updating a todo item at ``PATCH /todos/{id}.``. + """ + + @responses.activate + def test_change_content(self): + """ + It is possible to change the content of a todo item. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + new_content = 'Book vacation' + + patch = self.app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'content': new_content}), + ) + + expected = create.json + expected['content'] = new_content + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + @responses.activate + @freeze_time(datetime.datetime.fromtimestamp(5.0, tz=pytz.utc)) + def test_flag_completed(self): + """ + It is possible to flag a todo item as completed. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + patch = self.app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'completed': True}), + ) + + expected = create.json + expected['completed'] = True + # Timestamp set to now, the time it is first marked completed. + expected['completion_timestamp'] = 5.0 + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + @responses.activate + def test_flag_not_completed(self): + """ + It is possible to flag a todo item as not completed. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + patch = self.app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'completed': False}), + ) + + expected = create.json + expected['completed'] = False + # Marking an item as not completed removes the completion timestamp. + expected['completion_timestamp'] = None + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + @responses.activate + def test_change_content_and_flag(self): + """ + It is possible to change the content of a todo item, as well as marking + the item as completed. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + new_content = 'Book vacation' + + patch = self.app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'content': new_content, 'completed': False}), + ) + + expected = create.json + expected['content'] = new_content + expected['completed'] = False + expected['completion_timestamp'] = None + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + @responses.activate + def test_flag_completed_already_completed(self): + """ + Flagging an already completed item as completed does not change the + completion timestamp. + """ + create_time = datetime.datetime.fromtimestamp(5.0, tz=pytz.utc) + with freeze_time(create_time): + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + patch_time = datetime.datetime.fromtimestamp(6.0, tz=pytz.utc) + with freeze_time(patch_time): + patch = self.app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'completed': True}), + ) + + expected = create.json + # Timestamp set to the time it is first marked completed. + expected['completion_timestamp'] = 5.0 + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + @responses.activate + def test_remain_same(self): + """ + Not requesting any changes keeps the item the same. + """ + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + patch = self.app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({}), + ) + + self.assertEqual(create.json, patch.json) + + @responses.activate + def test_non_existant(self): + """ + If the todo item to be updated does not exist, a ``NOT_FOUND`` error is + returned. + """ + response = self.app.patch('/todos/1', content_type='application/json') + + self.assertEqual(response.headers['Content-Type'], 'application/json') + self.assertEqual(response.status_code, codes.NOT_FOUND) + expected = { + 'title': 'The requested todo does not exist.', + 'detail': 'No todo exists with the id "1"', + } + self.assertEqual(response.json, expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.app.patch('/todos/1', content_type='text/html') + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) diff --git a/storage/tests/test_storage.py b/storage/tests/test_storage.py index aef8af7..f8c2c90 100644 --- a/storage/tests/test_storage.py +++ b/storage/tests/test_storage.py @@ -574,3 +574,166 @@ class ListTodosTests(InMemoryStorageTests): """ response = self.storage_app.get('/todos', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + + +class UpdateTodoTests(InMemoryStorageTests): + """ + Tests for updating a todo item at ``PATCH /todos/{id}.``. + """ + + def test_change_content(self): + """ + It is possible to change the content of a todo item. + """ + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + new_content = 'Book vacation' + + patch = self.storage_app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'content': new_content}), + ) + + expected = NOT_COMPLETED_TODO_DATA.copy() + expected['content'] = new_content + expected['completion_timestamp'] = None + expected['id'] = create.json['id'] + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.storage_app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + def test_flag_completed(self): + """ + It is possible to flag a todo item as completed. + """ + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + patch = self.storage_app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'completed': True, 'completion_timestamp': 2.0}), + ) + + expected = NOT_COMPLETED_TODO_DATA.copy() + expected['completed'] = True + expected['completion_timestamp'] = 2 + expected['id'] = create.json['id'] + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.storage_app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + def test_flag_not_completed(self): + """ + It is possible to flag a todo item as not completed. + """ + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + patch = self.storage_app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps( + {'completed': False, 'completion_timestamp': None}), + ) + + expected = COMPLETED_TODO_DATA.copy() + expected['completed'] = False + expected['completion_timestamp'] = None + expected['id'] = create.json['id'] + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.storage_app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + def test_change_content_and_flag(self): + """ + It is possible to change the content of a todo item, as well as marking + the item as completed. + """ + create = self.storage_app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + new_content = 'Book vacation' + + patch = self.storage_app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'content': new_content, 'completed': False}), + ) + + expected = NOT_COMPLETED_TODO_DATA.copy() + expected['content'] = new_content + expected['completed'] = False + expected['completion_timestamp'] = None + expected['id'] = create.json['id'] + + self.assertEqual(patch.status_code, codes.OK) + self.assertEqual(patch.json, expected) + + read = self.storage_app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.json, expected) + + def test_non_existant(self): + """ + If the todo item to be updated does not exist, a ``NOT_FOUND`` error is + returned. + """ + response = self.storage_app.patch( + '/todos/1', + content_type='application/json', + ) + + self.assertEqual(response.headers['Content-Type'], 'application/json') + self.assertEqual(response.status_code, codes.NOT_FOUND) + expected = { + 'title': 'The requested todo does not exist.', + 'detail': 'No todo exists with the id "1"', + } + self.assertEqual(response.json, expected) + + def test_incorrect_content_type(self): + """ + If a Content-Type header other than 'application/json' is given, an + UNSUPPORTED_MEDIA_TYPE status code is given. + """ + response = self.storage_app.patch('/todos/1', content_type='text/html') + self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt", "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 bcrypt==4.0.1 certifi==2021.5.30 coverage==6.2 coveralls==3.3.1 dataclasses==0.8 doc8==0.11.2 docopt==0.6.2 docutils==0.18.1 execnet==1.9.0 flake8==3.9.2 Flask==0.10.1 Flask-Bcrypt==0.7.1 Flask-JsonSchema==0.1.1 Flask-Login==0.3.2 Flask-Negotiate==0.1.0 Flask-SQLAlchemy==2.1 Flask-Testing==0.8.1 freezegun==1.2.2 greenlet==2.0.2 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==3.2.0 MarkupSafe==2.0.1 mccabe==0.6.1 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2016.4 -e git+https://github.com/adamtheturtle/todo.git@736849d28dacdf6112fe2bef70aec1b6ceced636#egg=Qlutter_TODOer requests==2.10.0 responses==0.17.0 restructuredtext-lint==1.4.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-httpdomain==1.8.1 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 SQLAlchemy==1.4.54 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: todo channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - bcrypt==4.0.1 - coverage==6.2 - coveralls==3.3.1 - dataclasses==0.8 - doc8==0.11.2 - docopt==0.6.2 - docutils==0.18.1 - execnet==1.9.0 - flake8==3.9.2 - flask==0.10.1 - flask-bcrypt==0.7.1 - flask-jsonschema==0.1.1 - flask-login==0.3.2 - flask-negotiate==0.1.0 - flask-sqlalchemy==2.1 - flask-testing==0.8.1 - freezegun==1.2.2 - greenlet==2.0.2 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==3.2.0 - markupsafe==2.0.1 - mccabe==0.6.1 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2016.4 - requests==2.10.0 - responses==0.17.0 - restructuredtext-lint==1.4.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-httpdomain==1.8.1 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlalchemy==1.4.54 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/todo
[ "authentication/tests/test_authentication.py::UpdateTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::UpdateTodoTests::test_incorrect_content_type" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_existing_user", "authentication/tests/test_authentication.py::SignupTests::test_missing_email", "authentication/tests/test_authentication.py::SignupTests::test_missing_password", "authentication/tests/test_authentication.py::SignupTests::test_passwords_hashed", "authentication/tests/test_authentication.py::SignupTests::test_signup", "authentication/tests/test_authentication.py::LoginTests::test_login", "authentication/tests/test_authentication.py::LoginTests::test_missing_email", "authentication/tests/test_authentication.py::LoginTests::test_missing_password", "authentication/tests/test_authentication.py::LoginTests::test_non_existant_user", "authentication/tests/test_authentication.py::LoginTests::test_remember_me_cookie_set", "authentication/tests/test_authentication.py::LoginTests::test_wrong_password", "authentication/tests/test_authentication.py::LogoutTests::test_logout", "authentication/tests/test_authentication.py::LogoutTests::test_logout_twice", "authentication/tests/test_authentication.py::LoadUserTests::test_user_does_not_exist", "authentication/tests/test_authentication.py::LoadUserTests::test_user_exists", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_fake_token", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_load_user_from_token", "authentication/tests/test_authentication.py::CreateTodoTests::test_current_completion_time", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_completed_flag", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_text", "authentication/tests/test_authentication.py::CreateTodoTests::test_success_response", "authentication/tests/test_authentication.py::ReadTodoTests::test_completed", "authentication/tests/test_authentication.py::ReadTodoTests::test_multiple_todos", "authentication/tests/test_authentication.py::ReadTodoTests::test_non_existant", "authentication/tests/test_authentication.py::ReadTodoTests::test_success", "authentication/tests/test_authentication.py::DeleteTodoTests::test_delete_twice", "authentication/tests/test_authentication.py::DeleteTodoTests::test_success", "authentication/tests/test_authentication.py::ListTodosTests::test_filter_completed", "authentication/tests/test_authentication.py::ListTodosTests::test_filter_not_completed", "authentication/tests/test_authentication.py::ListTodosTests::test_list", "authentication/tests/test_authentication.py::ListTodosTests::test_no_todos", "authentication/tests/test_authentication.py::UpdateTodoTests::test_change_content", "authentication/tests/test_authentication.py::UpdateTodoTests::test_change_content_and_flag", "authentication/tests/test_authentication.py::UpdateTodoTests::test_flag_completed", "authentication/tests/test_authentication.py::UpdateTodoTests::test_flag_completed_already_completed", "authentication/tests/test_authentication.py::UpdateTodoTests::test_flag_not_completed", "authentication/tests/test_authentication.py::UpdateTodoTests::test_non_existant", "authentication/tests/test_authentication.py::UpdateTodoTests::test_remain_same", "storage/tests/test_storage.py::CreateUserTests::test_existing_user", "storage/tests/test_storage.py::CreateUserTests::test_missing_email", "storage/tests/test_storage.py::CreateUserTests::test_missing_password_hash", "storage/tests/test_storage.py::CreateUserTests::test_success_response", "storage/tests/test_storage.py::GetUserTests::test_non_existant_user", "storage/tests/test_storage.py::GetUserTests::test_success", "storage/tests/test_storage.py::GetUsersTests::test_with_users", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completed_flag", "storage/tests/test_storage.py::CreateTodoTests::test_missing_completion_time", "storage/tests/test_storage.py::CreateTodoTests::test_missing_text", "storage/tests/test_storage.py::CreateTodoTests::test_success_response", "storage/tests/test_storage.py::GetTodoTests::test_non_existant", "storage/tests/test_storage.py::GetTodoTests::test_success", "storage/tests/test_storage.py::GetTodoTests::test_timestamp_null", "storage/tests/test_storage.py::DeleteTodoTests::test_delete_twice", "storage/tests/test_storage.py::DeleteTodoTests::test_success", "storage/tests/test_storage.py::ListTodosTests::test_filter_completed", "storage/tests/test_storage.py::ListTodosTests::test_filter_not_completed", "storage/tests/test_storage.py::ListTodosTests::test_list", "storage/tests/test_storage.py::ListTodosTests::test_no_todos", "storage/tests/test_storage.py::UpdateTodoTests::test_change_content", "storage/tests/test_storage.py::UpdateTodoTests::test_change_content_and_flag", "storage/tests/test_storage.py::UpdateTodoTests::test_flag_completed", "storage/tests/test_storage.py::UpdateTodoTests::test_flag_not_completed", "storage/tests/test_storage.py::UpdateTodoTests::test_non_existant" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LoginTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_not_logged_in", "authentication/tests/test_authentication.py::UserTests::test_different_password_different_token", "authentication/tests/test_authentication.py::UserTests::test_get_auth_token", "authentication/tests/test_authentication.py::UserTests::test_get_id", "authentication/tests/test_authentication.py::CreateTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::ReadTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::DeleteTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::ListTodosTests::test_incorrect_content_type", "storage/tests/test_storage.py::CreateUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUserTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetUsersTests::test_no_users", "storage/tests/test_storage.py::CreateTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::GetTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::DeleteTodoTests::test_incorrect_content_type", "storage/tests/test_storage.py::ListTodosTests::test_incorrect_content_type" ]
[]
null
539
adamtheturtle__todo-47
f81fa85e3c06d931963f76f2d0772ce0b9db67b9
2016-05-16 22:04:31
f81fa85e3c06d931963f76f2d0772ce0b9db67b9
diff --git a/authentication/authentication.py b/authentication/authentication.py index 445bcc7..6937a58 100644 --- a/authentication/authentication.py +++ b/authentication/authentication.py @@ -250,9 +250,10 @@ def signup(): @app.route('/todos', methods=['POST']) @consumes('application/json') @jsonschema.validate('todos', 'create') +@login_required def create_todo(): """ - Create a new todo item. + Create a new todo item. Requires log in. :reqheader Content-Type: application/json :resheader Content-Type: application/json @@ -287,9 +288,10 @@ def create_todo(): @app.route('/todos/<id>', methods=['GET']) @consumes('application/json') +@login_required def read_todo(id): """ - Get information about a particular todo item. + Get information about a particular todo item. Requires log in. :reqheader Content-Type: application/json :resheader Content-Type: application/json @@ -307,9 +309,10 @@ def read_todo(id): @app.route('/todos/<id>', methods=['DELETE']) @consumes('application/json') +@login_required def delete_todo(id): """ - Delete a particular todo item. + Delete a particular todo item. Requires log in. :reqheader Content-Type: application/json :resheader Content-Type: application/json @@ -325,9 +328,10 @@ def delete_todo(id): @app.route('/todos', methods=['GET']) @consumes('application/json') +@login_required def list_todos(): """ - List todo items, with optional filters. + List todo items, with optional filters. Requires log in. :reqheader Content-Type: application/json :resheader Content-Type: application/json @@ -349,10 +353,11 @@ def list_todos(): @app.route('/todos/<id>', methods=['PATCH']) @consumes('application/json') +@login_required def update_todo(id): """ Update a todo item. If an item is changed from not-completed to completed, - the ``completion_timestamp`` is set as now. + the ``completion_timestamp`` is set as now. Requires log in. :reqheader Content-Type: application/json
Protect the TODO CRUD APIs
adamtheturtle/todo
diff --git a/authentication/tests/test_authentication.py b/authentication/tests/test_authentication.py index 6f7108a..29fb21c 100644 --- a/authentication/tests/test_authentication.py +++ b/authentication/tests/test_authentication.py @@ -30,6 +30,7 @@ from storage.tests.testtools import InMemoryStorageTests USER_DATA = {'email': '[email protected]', 'password': 'secret'} COMPLETED_TODO_DATA = {'content': 'Buy milk', 'completed': True} NOT_COMPLETED_TODO_DATA = {'content': 'Get haircut', 'completed': False} +TIMESTAMP = 1463437744.335567 class AuthenticationTests(InMemoryStorageTests): @@ -93,6 +94,19 @@ class AuthenticationTests(InMemoryStorageTests): {key: value for (key, value) in response.headers}, response.data) + def log_in_as_new_user(self): + """ + Create a user and log in as that user. + """ + self.app.post( + '/signup', + content_type='application/json', + data=json.dumps(USER_DATA)) + self.app.post( + '/login', + content_type='application/json', + data=json.dumps(USER_DATA)) + class SignupTests(AuthenticationTests): """ @@ -503,6 +517,7 @@ class CreateTodoTests(AuthenticationTests): returns a JSON response with the given data and a ``null`` ``completion_timestamp``. """ + self.log_in_as_new_user() response = self.app.post( '/todos', content_type='application/json', @@ -516,12 +531,13 @@ class CreateTodoTests(AuthenticationTests): self.assertEqual(response.json, expected) @responses.activate - @freeze_time(datetime.datetime.fromtimestamp(5.01, tz=pytz.utc)) + @freeze_time(datetime.datetime.fromtimestamp(TIMESTAMP, tz=pytz.utc)) def test_current_completion_time(self): """ If the completed flag is set to ``true`` then the completed time is the number of seconds since the epoch. """ + self.log_in_as_new_user() response = self.app.post( '/todos', content_type='application/json', @@ -534,7 +550,7 @@ class CreateTodoTests(AuthenticationTests): # some accuracy). self.assertAlmostEqual( response.json['completion_timestamp'], - 5.01, + TIMESTAMP, places=3, ) @@ -580,14 +596,29 @@ class CreateTodoTests(AuthenticationTests): } self.assertEqual(response.json, expected) + @responses.activate def test_incorrect_content_type(self): """ If a Content-Type header other than 'application/json' is given, an UNSUPPORTED_MEDIA_TYPE status code is given. """ + self.log_in_as_new_user() response = self.app.post('/todos', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + @responses.activate + def test_not_logged_in(self): + """ + When no user is logged in, an UNAUTHORIZED status code is returned. + """ + response = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + self.assertEqual(response.status_code, codes.UNAUTHORIZED) + class ReadTodoTests(AuthenticationTests): """ @@ -600,6 +631,7 @@ class ReadTodoTests(AuthenticationTests): A ``GET`` request for an existing todo an OK status code and the todo's details. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -618,12 +650,13 @@ class ReadTodoTests(AuthenticationTests): self.assertEqual(read.json, expected) @responses.activate - @freeze_time(datetime.datetime.fromtimestamp(5, tz=pytz.utc)) + @freeze_time(datetime.datetime.fromtimestamp(TIMESTAMP, tz=pytz.utc)) def test_completed(self): """ A ``GET`` request for an existing todo an OK status code and the todo's details, included the completion timestamp. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -637,8 +670,12 @@ class ReadTodoTests(AuthenticationTests): self.assertEqual(read.status_code, codes.OK) expected = COMPLETED_TODO_DATA.copy() - expected['completion_timestamp'] = 5 expected['id'] = create.json['id'] + self.assertAlmostEqual( + read.json.pop('completion_timestamp'), + TIMESTAMP, + places=3 + ) self.assertEqual(read.json, expected) @responses.activate @@ -646,6 +683,7 @@ class ReadTodoTests(AuthenticationTests): """ A ``GET`` request gets the correct todo when there are multiple. """ + self.log_in_as_new_user() self.app.post( '/todos', content_type='application/json', @@ -681,6 +719,7 @@ class ReadTodoTests(AuthenticationTests): A ``GET`` request for a todo which does not exist returns a NOT_FOUND status code and error details. """ + self.log_in_as_new_user() response = self.app.get('/todos/1', content_type='application/json') self.assertEqual(response.headers['Content-Type'], 'application/json') @@ -699,6 +738,27 @@ class ReadTodoTests(AuthenticationTests): response = self.app.get('/todos/1', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + @responses.activate + def test_not_logged_in(self): + """ + When no user is logged in, an UNAUTHORIZED status code is returned. + """ + self.log_in_as_new_user() + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + self.app.post('/logout', content_type='application/json') + + read = self.app.get( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(read.status_code, codes.UNAUTHORIZED) + class DeleteTodoTests(AuthenticationTests): """ @@ -710,6 +770,7 @@ class DeleteTodoTests(AuthenticationTests): """ It is possible to delete a todo item. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -735,6 +796,7 @@ class DeleteTodoTests(AuthenticationTests): """ Deleting an item twice gives returns a 404 code and error message. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -758,14 +820,38 @@ class DeleteTodoTests(AuthenticationTests): } self.assertEqual(delete.json, expected) + @responses.activate def test_incorrect_content_type(self): """ If a Content-Type header other than 'application/json' is given, an UNSUPPORTED_MEDIA_TYPE status code is given. """ + self.log_in_as_new_user() response = self.app.delete('/todos/1', content_type='text/html') self.assertEqual(response.status_code, codes.UNSUPPORTED_MEDIA_TYPE) + @responses.activate + def test_not_logged_in(self): + """ + When no user is logged in, an UNAUTHORIZED status code is returned. + """ + self.log_in_as_new_user() + + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(COMPLETED_TODO_DATA), + ) + + self.app.post('/logout', content_type='application/json') + + delete = self.app.delete( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + ) + + self.assertEqual(delete.status_code, codes.UNAUTHORIZED) + class ListTodosTests(AuthenticationTests): """ @@ -777,6 +863,7 @@ class ListTodosTests(AuthenticationTests): """ When there are no todos, an empty array is returned. """ + self.log_in_as_new_user() list_todos = self.app.get( '/todos', content_type='application/json', @@ -785,11 +872,24 @@ class ListTodosTests(AuthenticationTests): self.assertEqual(list_todos.status_code, codes.OK) self.assertEqual(list_todos.json['todos'], []) + @responses.activate + def test_not_logged_in(self): + """ + When no user is logged in, an UNAUTHORIZED status code is returned. + """ + list_todos = self.app.get( + '/todos', + content_type='application/json', + ) + + self.assertEqual(list_todos.status_code, codes.UNAUTHORIZED) + @responses.activate def test_list(self): """ All todos are listed. """ + self.log_in_as_new_user() other_todo = NOT_COMPLETED_TODO_DATA.copy() other_todo['content'] = 'Get a haircut' @@ -815,11 +915,12 @@ class ListTodosTests(AuthenticationTests): self.assertEqual(list_todos.json['todos'], expected) @responses.activate - @freeze_time(datetime.datetime.fromtimestamp(5, tz=pytz.utc)) + @freeze_time(datetime.datetime.fromtimestamp(TIMESTAMP, tz=pytz.utc)) def test_filter_completed(self): """ It is possible to filter by only completed items. """ + self.log_in_as_new_user() self.app.post( '/todos', content_type='application/json', @@ -842,15 +943,21 @@ class ListTodosTests(AuthenticationTests): self.assertEqual(list_todos.status_code, codes.OK) expected = COMPLETED_TODO_DATA.copy() - expected['completion_timestamp'] = 5.0 expected['id'] = 2 - self.assertEqual(list_todos_data['todos'], [expected]) + [todo] = list_todos_data['todos'] + self.assertAlmostEqual( + todo.pop('completion_timestamp'), + TIMESTAMP, + places=3, + ) + self.assertEqual(todo, expected) @responses.activate def test_filter_not_completed(self): """ It is possible to filter by only items which are not completed. """ + self.log_in_as_new_user() self.app.post( '/todos', content_type='application/json', @@ -877,6 +984,7 @@ class ListTodosTests(AuthenticationTests): expected['id'] = 1 self.assertEqual(list_todos_data['todos'], [expected]) + @responses.activate def test_incorrect_content_type(self): """ If a Content-Type header other than 'application/json' is given, an @@ -896,6 +1004,7 @@ class UpdateTodoTests(AuthenticationTests): """ It is possible to change the content of a todo item. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -924,11 +1033,34 @@ class UpdateTodoTests(AuthenticationTests): self.assertEqual(read.json, expected) @responses.activate - @freeze_time(datetime.datetime.fromtimestamp(5.0, tz=pytz.utc)) + def test_not_logged_in(self): + """ + When no user is logged in, an UNAUTHORIZED status code is returned. + """ + self.log_in_as_new_user() + create = self.app.post( + '/todos', + content_type='application/json', + data=json.dumps(NOT_COMPLETED_TODO_DATA), + ) + + self.app.post('/logout', content_type='application/json') + + patch = self.app.patch( + '/todos/{id}'.format(id=create.json['id']), + content_type='application/json', + data=json.dumps({'content': 'Book vacation'}), + ) + + self.assertEqual(patch.status_code, codes.UNAUTHORIZED) + + @responses.activate + @freeze_time(datetime.datetime.fromtimestamp(TIMESTAMP, tz=pytz.utc)) def test_flag_completed(self): """ It is possible to flag a todo item as completed. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -943,10 +1075,14 @@ class UpdateTodoTests(AuthenticationTests): expected = create.json expected['completed'] = True - # Timestamp set to now, the time it is first marked completed. - expected['completion_timestamp'] = 5.0 + expected['completion_timestamp'] = TIMESTAMP self.assertEqual(patch.status_code, codes.OK) + self.assertAlmostEqual( + patch.json.pop('completion_timestamp'), + expected.pop('completion_timestamp'), + places=3, + ) self.assertEqual(patch.json, expected) read = self.app.get( @@ -954,6 +1090,11 @@ class UpdateTodoTests(AuthenticationTests): content_type='application/json', ) + self.assertAlmostEqual( + read.json.pop('completion_timestamp'), + TIMESTAMP, + places=3, + ) self.assertEqual(read.json, expected) @responses.activate @@ -961,6 +1102,7 @@ class UpdateTodoTests(AuthenticationTests): """ It is possible to flag a todo item as not completed. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -994,6 +1136,7 @@ class UpdateTodoTests(AuthenticationTests): It is possible to change the content of a todo item, as well as marking the item as completed. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -1029,7 +1172,8 @@ class UpdateTodoTests(AuthenticationTests): Flagging an already completed item as completed does not change the completion timestamp. """ - create_time = datetime.datetime.fromtimestamp(5.0, tz=pytz.utc) + self.log_in_as_new_user() + create_time = datetime.datetime.fromtimestamp(TIMESTAMP, tz=pytz.utc) with freeze_time(create_time): create = self.app.post( '/todos', @@ -1037,7 +1181,8 @@ class UpdateTodoTests(AuthenticationTests): data=json.dumps(COMPLETED_TODO_DATA), ) - patch_time = datetime.datetime.fromtimestamp(6.0, tz=pytz.utc) + patch_time = datetime.datetime.fromtimestamp( + TIMESTAMP + 1, tz=pytz.utc) with freeze_time(patch_time): patch = self.app.patch( '/todos/{id}'.format(id=create.json['id']), @@ -1045,25 +1190,34 @@ class UpdateTodoTests(AuthenticationTests): data=json.dumps({'completed': True}), ) - expected = create.json - # Timestamp set to the time it is first marked completed. - expected['completion_timestamp'] = 5.0 - + self.assertAlmostEqual( + patch.json.pop('completion_timestamp'), + # Timestamp set to the time it is first marked completed. + create.json.pop('completion_timestamp'), + places=3, + ) self.assertEqual(patch.status_code, codes.OK) - self.assertEqual(patch.json, expected) + self.assertEqual(patch.json, create.json) read = self.app.get( '/todos/{id}'.format(id=create.json['id']), content_type='application/json', ) - self.assertEqual(read.json, expected) + self.assertAlmostEqual( + read.json.pop('completion_timestamp'), + # Timestamp set to the time it is first marked completed. + TIMESTAMP, + places=3, + ) + self.assertEqual(read.json, create.json) @responses.activate def test_remain_same(self): """ Not requesting any changes keeps the item the same. """ + self.log_in_as_new_user() create = self.app.post( '/todos', content_type='application/json', @@ -1084,6 +1238,7 @@ class UpdateTodoTests(AuthenticationTests): If the todo item to be updated does not exist, a ``NOT_FOUND`` error is returned. """ + self.log_in_as_new_user() response = self.app.patch('/todos/1', content_type='application/json') self.assertEqual(response.headers['Content-Type'], 'application/json')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt", "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 bcrypt==4.0.1 certifi==2021.5.30 coverage==6.2 coveralls==3.3.1 dataclasses==0.8 doc8==0.11.2 docopt==0.6.2 docutils==0.18.1 execnet==1.9.0 flake8==3.9.2 Flask==0.10.1 Flask-Bcrypt==0.7.1 Flask-JsonSchema==0.1.1 Flask-Login==0.3.2 Flask-Negotiate==0.1.0 Flask-SQLAlchemy==2.1 Flask-Testing==0.8.1 freezegun==1.2.2 greenlet==2.0.2 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==3.2.0 MarkupSafe==2.0.1 mccabe==0.6.1 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2016.4 -e git+https://github.com/adamtheturtle/todo.git@f81fa85e3c06d931963f76f2d0772ce0b9db67b9#egg=Qlutter_TODOer requests==2.10.0 responses==0.17.0 restructuredtext-lint==1.4.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-httpdomain==1.8.1 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 SQLAlchemy==1.4.54 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: todo channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - bcrypt==4.0.1 - coverage==6.2 - coveralls==3.3.1 - dataclasses==0.8 - doc8==0.11.2 - docopt==0.6.2 - docutils==0.18.1 - execnet==1.9.0 - flake8==3.9.2 - flask==0.10.1 - flask-bcrypt==0.7.1 - flask-jsonschema==0.1.1 - flask-login==0.3.2 - flask-negotiate==0.1.0 - flask-sqlalchemy==2.1 - flask-testing==0.8.1 - freezegun==1.2.2 - greenlet==2.0.2 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==3.2.0 - markupsafe==2.0.1 - mccabe==0.6.1 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2016.4 - requests==2.10.0 - responses==0.17.0 - restructuredtext-lint==1.4.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-httpdomain==1.8.1 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlalchemy==1.4.54 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/todo
[ "authentication/tests/test_authentication.py::ListTodosTests::test_not_logged_in" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_existing_user", "authentication/tests/test_authentication.py::SignupTests::test_missing_email", "authentication/tests/test_authentication.py::SignupTests::test_missing_password", "authentication/tests/test_authentication.py::SignupTests::test_passwords_hashed", "authentication/tests/test_authentication.py::SignupTests::test_signup", "authentication/tests/test_authentication.py::LoginTests::test_login", "authentication/tests/test_authentication.py::LoginTests::test_missing_email", "authentication/tests/test_authentication.py::LoginTests::test_missing_password", "authentication/tests/test_authentication.py::LoginTests::test_non_existant_user", "authentication/tests/test_authentication.py::LoginTests::test_remember_me_cookie_set", "authentication/tests/test_authentication.py::LoginTests::test_wrong_password", "authentication/tests/test_authentication.py::LogoutTests::test_logout", "authentication/tests/test_authentication.py::LogoutTests::test_logout_twice", "authentication/tests/test_authentication.py::LoadUserTests::test_user_does_not_exist", "authentication/tests/test_authentication.py::LoadUserTests::test_user_exists", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_fake_token", "authentication/tests/test_authentication.py::LoadUserFromTokenTests::test_load_user_from_token", "authentication/tests/test_authentication.py::CreateTodoTests::test_current_completion_time", "authentication/tests/test_authentication.py::CreateTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_completed_flag", "authentication/tests/test_authentication.py::CreateTodoTests::test_missing_text", "authentication/tests/test_authentication.py::CreateTodoTests::test_not_logged_in", "authentication/tests/test_authentication.py::CreateTodoTests::test_success_response", "authentication/tests/test_authentication.py::ReadTodoTests::test_completed", "authentication/tests/test_authentication.py::ReadTodoTests::test_multiple_todos", "authentication/tests/test_authentication.py::ReadTodoTests::test_non_existant", "authentication/tests/test_authentication.py::ReadTodoTests::test_not_logged_in", "authentication/tests/test_authentication.py::ReadTodoTests::test_success", "authentication/tests/test_authentication.py::DeleteTodoTests::test_delete_twice", "authentication/tests/test_authentication.py::DeleteTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::DeleteTodoTests::test_not_logged_in", "authentication/tests/test_authentication.py::DeleteTodoTests::test_success", "authentication/tests/test_authentication.py::ListTodosTests::test_filter_completed", "authentication/tests/test_authentication.py::ListTodosTests::test_filter_not_completed", "authentication/tests/test_authentication.py::ListTodosTests::test_list", "authentication/tests/test_authentication.py::ListTodosTests::test_no_todos", "authentication/tests/test_authentication.py::UpdateTodoTests::test_change_content", "authentication/tests/test_authentication.py::UpdateTodoTests::test_change_content_and_flag", "authentication/tests/test_authentication.py::UpdateTodoTests::test_flag_completed", "authentication/tests/test_authentication.py::UpdateTodoTests::test_flag_completed_already_completed", "authentication/tests/test_authentication.py::UpdateTodoTests::test_flag_not_completed", "authentication/tests/test_authentication.py::UpdateTodoTests::test_non_existant", "authentication/tests/test_authentication.py::UpdateTodoTests::test_not_logged_in", "authentication/tests/test_authentication.py::UpdateTodoTests::test_remain_same" ]
[ "authentication/tests/test_authentication.py::SignupTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LoginTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::LogoutTests::test_not_logged_in", "authentication/tests/test_authentication.py::UserTests::test_different_password_different_token", "authentication/tests/test_authentication.py::UserTests::test_get_auth_token", "authentication/tests/test_authentication.py::UserTests::test_get_id", "authentication/tests/test_authentication.py::ReadTodoTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::ListTodosTests::test_incorrect_content_type", "authentication/tests/test_authentication.py::UpdateTodoTests::test_incorrect_content_type" ]
[]
null
540
requests__requests-kerberos-73
b86ced24d162e8e283080a85ca06719de16e2376
2016-05-17 06:45:27
b86ced24d162e8e283080a85ca06719de16e2376
diff --git a/README.rst b/README.rst index 70e60eb..ee8fa9e 100644 --- a/README.rst +++ b/README.rst @@ -131,6 +131,10 @@ builds). An explicit principal can be specified with the ``principal`` arg: >>> kerberos_auth = HTTPKerberosAuth(principal="user@REALM") >>> r = requests.get("http://example.org", auth=kerberos_auth) ... + +**Windows users:** Explicit Principal is currently not supported when using +``kerberos-sspi``. Providing a value for ``principal`` in this scenario will raise +``NotImplementedError``. Logging ------- diff --git a/requests_kerberos/kerberos_.py b/requests_kerberos/kerberos_.py index f3c5d39..87d8f96 100644 --- a/requests_kerberos/kerberos_.py +++ b/requests_kerberos/kerberos_.py @@ -1,7 +1,9 @@ try: import kerberos + using_kerberos_sspi = False except ImportError: import kerberos_sspi as kerberos + using_kerberos_sspi = True import re import logging @@ -95,6 +97,7 @@ class HTTPKerberosAuth(AuthBase): self.principal = principal self.hostname_override = hostname_override self.sanitize_mutual_error_response = sanitize_mutual_error_response + self._using_kerberos_sspi = using_kerberos_sspi def generate_request_header(self, response, host, is_preemptive=False): """ @@ -118,9 +121,16 @@ class HTTPKerberosAuth(AuthBase): # w/ name-based HTTP hosting) kerb_host = self.hostname_override if self.hostname_override is not None else host kerb_spn = "{0}@{1}".format(self.service, kerb_host) + + kwargs = {} + # kerberos-sspi: Never pass principal. Raise if user tries to specify one. + if not self._using_kerberos_sspi: + kwargs['principal'] = self.principal + elif self.principal: + raise NotImplementedError("Can't use 'principal' argument with kerberos-sspi.") result, self.context[host] = kerberos.authGSSClientInit(kerb_spn, - gssflags=gssflags, principal=self.principal) + gssflags=gssflags, **kwargs) if result < 1: raise EnvironmentError(result, kerb_stage)
TypeError: authGSSClientInit() got an unexpected keyword argument 'principal' Looks like now that kerberos-sspi (https://github.com/may-day/kerberos-sspi/blob/master/kerberos_sspi.py#L170) doesn't support 'principal' that was added in commit https://github.com/requests/requests-kerberos/commit/c464cc0035a5552ab28b9e8c3eee7a5904f33996.
requests/requests-kerberos
diff --git a/test_requests_kerberos.py b/test_requests_kerberos.py index 0077223..9f3edc5 100644 --- a/test_requests_kerberos.py +++ b/test_requests_kerberos.py @@ -54,6 +54,12 @@ class KerberosTestCase(unittest.TestCase): clientStep_error.reset_mock() clientStep_exception.reset_mock() clientResponse.reset_mock() + + # When using kerberos-sspi, we never pass principal to authGSSClientInit(). + # This affects our repeated use of assert_called_with(). + self.clientInit_default_principal = {'principal': None} + if kerberos_module_name == 'kerberos_sspi': + self.clientInit_default_principal = {} def tearDown(self): """Teardown.""" @@ -120,7 +126,7 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) clientStep_continue.assert_called_with("CTX", "token") clientResponse.assert_called_with("CTX") @@ -142,7 +148,7 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) self.assertFalse(clientStep_continue.called) self.assertFalse(clientResponse.called) @@ -164,7 +170,7 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) clientStep_error.assert_called_with("CTX", "token") self.assertFalse(clientResponse.called) @@ -209,7 +215,7 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) clientStep_continue.assert_called_with("CTX", "token") clientResponse.assert_called_with("CTX") @@ -254,7 +260,7 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) clientStep_continue.assert_called_with("CTX", "token") clientResponse.assert_called_with("CTX") @@ -495,7 +501,7 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) clientStep_continue.assert_called_with("CTX", "token") clientResponse.assert_called_with("CTX") @@ -545,7 +551,7 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) clientStep_continue.assert_called_with("CTX", "token") clientResponse.assert_called_with("CTX") @@ -565,10 +571,10 @@ class KerberosTestCase(unittest.TestCase): gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) def test_delegation(self): - with patch.multiple('kerberos', + with patch.multiple(kerberos_module_name, authGSSClientInit=clientInit_complete, authGSSClientResponse=clientResponse, authGSSClientStep=clientStep_continue): @@ -609,7 +615,7 @@ class KerberosTestCase(unittest.TestCase): kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG | kerberos.GSS_C_DELEG_FLAG), - principal=None + **self.clientInit_default_principal ) clientStep_continue.assert_called_with("CTX", "token") clientResponse.assert_called_with("CTX") @@ -624,13 +630,18 @@ class KerberosTestCase(unittest.TestCase): response.headers = {'www-authenticate': 'negotiate token'} host = urlparse(response.url).hostname auth = requests_kerberos.HTTPKerberosAuth(principal="user@REALM") - auth.generate_request_header(response, host), - clientInit_complete.assert_called_with( - "[email protected]", - gssflags=( - kerberos.GSS_C_MUTUAL_FLAG | - kerberos.GSS_C_SEQUENCE_FLAG), - principal="user@REALM") + try: + auth.generate_request_header(response, host) + clientInit_complete.assert_called_with( + "[email protected]", + gssflags=( + kerberos.GSS_C_MUTUAL_FLAG | + kerberos.GSS_C_SEQUENCE_FLAG), + principal="user@REALM") + except NotImplementedError: + # principal is not supported with kerberos-sspi. + if not auth._using_kerberos_sspi: + raise def test_realm_override(self): with patch.multiple(kerberos_module_name, @@ -642,13 +653,35 @@ class KerberosTestCase(unittest.TestCase): response.headers = {'www-authenticate': 'negotiate token'} host = urlparse(response.url).hostname auth = requests_kerberos.HTTPKerberosAuth(hostname_override="otherhost.otherdomain.org") - auth.generate_request_header(response, host), + auth.generate_request_header(response, host) clientInit_complete.assert_called_with( "[email protected]", gssflags=( kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG), - principal=None) + **self.clientInit_default_principal) + + def test_kerberos_sspi_reject_principal(self): + with patch.multiple(kerberos_module_name, + authGSSClientInit=clientInit_complete, + authGSSClientResponse=clientResponse, + authGSSClientStep=clientStep_continue): + response = requests.Response() + response.url = "http://www.example.org/" + host = urlparse(response.url).hostname + + auth = requests_kerberos.HTTPKerberosAuth(principal="user@REALM") + auth._using_kerberos_sspi = True + self.assertRaises(NotImplementedError, auth.generate_request_header, response, host) + + auth = requests_kerberos.HTTPKerberosAuth(principal=None) + auth._using_kerberos_sspi = True + auth.generate_request_header(response, host) + clientInit_complete.assert_called_with( + "[email protected]", + gssflags=( + kerberos.GSS_C_MUTUAL_FLAG | + kerberos.GSS_C_SEQUENCE_FLAG)) if __name__ == '__main__':
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pykerberos==1.2.4 pytest==8.3.5 requests==2.32.3 -e git+https://github.com/requests/requests-kerberos.git@b86ced24d162e8e283080a85ca06719de16e2376#egg=requests_kerberos tomli==2.2.1 urllib3==2.3.0
name: requests-kerberos channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pykerberos==1.2.4 - pytest==8.3.5 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/requests-kerberos
[ "test_requests_kerberos.py::KerberosTestCase::test_kerberos_sspi_reject_principal" ]
[]
[ "test_requests_kerberos.py::KerberosTestCase::test_authenticate_server", "test_requests_kerberos.py::KerberosTestCase::test_authenticate_user", "test_requests_kerberos.py::KerberosTestCase::test_delegation", "test_requests_kerberos.py::KerberosTestCase::test_force_preemptive", "test_requests_kerberos.py::KerberosTestCase::test_generate_request_header", "test_requests_kerberos.py::KerberosTestCase::test_generate_request_header_custom_service", "test_requests_kerberos.py::KerberosTestCase::test_generate_request_header_init_error", "test_requests_kerberos.py::KerberosTestCase::test_generate_request_header_step_error", "test_requests_kerberos.py::KerberosTestCase::test_handle_401", "test_requests_kerberos.py::KerberosTestCase::test_handle_other", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_200", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_200_mutual_auth_optional_hard_failure", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_200_mutual_auth_optional_soft_failure", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_200_mutual_auth_required_failure", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_200_mutual_auth_required_failure_2", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_401", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_401_rejected", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_500_mutual_auth_optional_failure", "test_requests_kerberos.py::KerberosTestCase::test_handle_response_500_mutual_auth_required_failure", "test_requests_kerberos.py::KerberosTestCase::test_negotate_value_extraction", "test_requests_kerberos.py::KerberosTestCase::test_negotate_value_extraction_none", "test_requests_kerberos.py::KerberosTestCase::test_no_force_preemptive", "test_requests_kerberos.py::KerberosTestCase::test_principal_override", "test_requests_kerberos.py::KerberosTestCase::test_realm_override" ]
[]
ISC License
541
kapouille__mongoquery-4
759677a81968ec264caa65020777cdae11d8a5e2
2016-05-17 11:51:11
759677a81968ec264caa65020777cdae11d8a5e2
foolswood: The Travis failure is python 3.2 only (and resolved by https://www.python.org/dev/peps/pep-0414/). There are a couple of options I can see to sort this out: - Remove (or find another way to create) the unicode literal in the tests. - Stop supporting python 3.2. rajcze: > The Travis failure is python 3.2 only (and resolved by https://www.python.org/dev/peps/pep-0414/). > There are a couple of options I can see to sort this out... My bad for only testing on 2.7 and 3.5... It's not really my call, but I'd rather remove the unicode literal from the test suite. Even though we could go with `unicode()`, and something like: ```lang=python try: unicode() except NameError: unicode = lambda x: str(x) ``` It seems too nasty to just facilitate for what IMHO is quite a corner-case issue. foolswood: I don't know many things using python3.2 (I don't have it locally either) so I don't blame you at all. I was leaning towards the literal removal too. Thought I'd put some options out, see if there was something I was missing.
diff --git a/mongoquery/__init__.py b/mongoquery/__init__.py index 9fa9482..83dc2ff 100644 --- a/mongoquery/__init__.py +++ b/mongoquery/__init__.py @@ -15,6 +15,10 @@ class _Undefined(object): pass +def is_non_string_sequence(entry): + return isinstance(entry, Sequence) and not isinstance(entry, string_type) + + class Query(object): def __init__(self, definition): self._definition = definition @@ -29,7 +33,7 @@ class Query(object): for sub_operator, sub_condition in condition.items() ) else: - if isinstance(entry, Sequence): + if is_non_string_sequence(entry): return condition in entry else: return condition == entry @@ -39,7 +43,7 @@ class Query(object): return entry if entry is None: return entry - if isinstance(entry, Sequence) and not isinstance(entry, string_type): + if is_non_string_sequence(entry): try: index = int(path[0]) return self._extract(entry[index], path[1:]) @@ -277,7 +281,7 @@ class Query(object): ) ) - if isinstance(entry, Sequence) and not isinstance(entry, string_type): + if is_non_string_sequence(entry): return len(entry) == condition return False
Checks against strings don't work properly See the following case: ``` >>> import mongoquery >>> a = {"a": "5", "b": 6} >>> query = mongoquery.Query({"a": 2}) >>> query.match(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/mongoquery/__init__.py", line 23, in match return self._match(self._definition, entry) File "/usr/local/lib/python2.7/site-packages/mongoquery/__init__.py", line 29, in _match for sub_operator, sub_condition in condition.items() File "/usr/local/lib/python2.7/site-packages/mongoquery/__init__.py", line 29, in <genexpr> for sub_operator, sub_condition in condition.items() File "/usr/local/lib/python2.7/site-packages/mongoquery/__init__.py", line 72, in _process_condition return self._match(condition, extracted_data) File "/usr/local/lib/python2.7/site-packages/mongoquery/__init__.py", line 33, in _match return condition in entry TypeError: 'in <string>' requires string as left operand, not int ``` This happens because we have: ``` def _match(self, condition, entry): if isinstance(condition, Mapping): return all( self._process_condition(sub_operator, sub_condition, entry) for sub_operator, sub_condition in condition.items() ) else: if isinstance(entry, Sequence): <----- HERE return condition in entry else: return condition == entry ``` `str` is actually a subtype of `collections.Sequence`, and thus we try and do an "in" comparison, when we really want equality. This seems like a bug even if you had two strings, because this can happen: ``` >>> b = {"a": "567", "b": 6} >>> query2 = mongoquery.Query({"a": "6"}) >>> query2.match(b) True ``` Same reason - we're doing an `in` when you want to do a strict equality check. There are a couple of possible fixes: 1. Check against explicit types instead of `Sequence` 2. Ensure that it is not a string-like type (e.g. bytes, unicode, str, etc)
kapouille/mongoquery
diff --git a/tests/test_query.py b/tests/test_query.py index 27d44e9..22ef7c8 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -103,6 +103,11 @@ class TestQuery(TestCase): self._query({"qty": {"$type": 'number'}}) ) + self.assertEqual( + _ALL, + self._query({"item": {"$type": 'string'}}) + ) + self.assertEqual( [], self._query({"qty": {"$type": 'string'}}) @@ -385,3 +390,8 @@ class TestQuery(TestCase): collection = [{"turtles": "swim"}] self.assertEqual( [], self._query({"turtles": {"value": "swim"}}, collection)) + + def test_query_string(self): + collection = [{"a": "5"}, {"a": "567"}] + self.assertEqual([], self._query({"a": 5}, collection)) + self.assertEqual([{"a": "5"}], self._query({"a": "5"}, collection))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
list
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "nose", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/kapouille/mongoquery.git@759677a81968ec264caa65020777cdae11d8a5e2#egg=mongoquery nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1
name: mongoquery channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/mongoquery
[ "tests/test_query.py::TestQuery::test_query_string" ]
[]
[ "tests/test_query.py::TestQuery::test_array", "tests/test_query.py::TestQuery::test_bad_query_doesnt_infinitely_recurse", "tests/test_query.py::TestQuery::test_comparison", "tests/test_query.py::TestQuery::test_element", "tests/test_query.py::TestQuery::test_evaluation", "tests/test_query.py::TestQuery::test_integer_mapping_key_exists", "tests/test_query.py::TestQuery::test_query_integer_keyed", "tests/test_query.py::TestQuery::test_query_subfield_not_found", "tests/test_query.py::TestQuery::test_simple_lookup" ]
[]
The Unlicense
542
adamtheturtle__todo-49
1d4c12ba785e521b5b0b8b40d54613280cf0bb34
2016-05-17 12:16:24
1d4c12ba785e521b5b0b8b40d54613280cf0bb34
diff --git a/.travis.yml b/.travis.yml index 087594a..dbd7728 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,7 @@ script: # Build documentation HTML. - sphinx-build -W -b html -d build/doctrees docs/source build/html # Run all discoverable tests, but set the source directories so that the coverage tool knows not to include coverage for all dependencies. - - "coverage run --branch --source=authentication,storage -m unittest discover" + - "coverage run --branch --source=todoer,storage -m unittest discover" after_success: # Sends the coverage report to coveralls.io which can report to Pull Requests # and track test coverage over time. diff --git a/docker-compose.yml b/docker-compose.yml index 16eb9a5..3524129 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -authenticate: +todoer: build: . ports: # HOST:CONTAINER @@ -9,7 +9,7 @@ authenticate: environment: # Set the environment variable SECRET_KEY else the secret will be insecure. - SECRET_KEY - command: python authentication/authentication.py + command: python todoer/todoer.py links: - storage storage: @@ -22,7 +22,7 @@ storage: # See http://flask.pocoo.org/docs/0.10/api/#flask.Flask.run - "5001:5001" volumes: - - /tmp/authentication:/data + - /tmp/todoer:/data environment: - - SQLALCHEMY_DATABASE_URI=sqlite:////data/authentication.db + - SQLALCHEMY_DATABASE_URI=sqlite:////data/todoer.db command: python storage/storage.py diff --git a/docs/source/index.rst b/docs/source/index.rst index c83eeab..d1ea106 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,5 +1,5 @@ ``todoer`` API Documentation ============================ -.. autoflask:: authentication.authentication:app +.. autoflask:: todoer.todoer:app :undoc-static: diff --git a/authentication/authentication.py b/todoer/todoer.py similarity index 99% rename from authentication/authentication.py rename to todoer/todoer.py index 6937a58..5fb937c 100644 --- a/authentication/authentication.py +++ b/todoer/todoer.py @@ -1,5 +1,5 @@ """ -An authentication service. +An authentication service with todo capabilities. """ import datetime
Rename authentication service
adamtheturtle/todo
diff --git a/authentication/__init__.py b/todoer/__init__.py similarity index 100% rename from authentication/__init__.py rename to todoer/__init__.py diff --git a/authentication/schemas/todos.json b/todoer/schemas/todos.json similarity index 100% rename from authentication/schemas/todos.json rename to todoer/schemas/todos.json diff --git a/authentication/schemas/user.json b/todoer/schemas/user.json similarity index 100% rename from authentication/schemas/user.json rename to todoer/schemas/user.json diff --git a/authentication/tests/__init__.py b/todoer/tests/__init__.py similarity index 100% rename from authentication/tests/__init__.py rename to todoer/tests/__init__.py diff --git a/authentication/tests/test_authentication.py b/todoer/tests/test_todoer.py similarity index 99% rename from authentication/tests/test_authentication.py rename to todoer/tests/test_todoer.py index 29fb21c..2c9b504 100644 --- a/authentication/tests/test_authentication.py +++ b/todoer/tests/test_todoer.py @@ -1,5 +1,5 @@ """ -Tests for authentication.authentication. +Tests for todoer.todoer. """ import datetime @@ -16,7 +16,7 @@ from requests import codes from urllib.parse import urljoin from werkzeug.http import parse_cookie -from authentication.authentication import ( +from todoer.todoer import ( app, bcrypt, load_user_from_id, @@ -674,7 +674,7 @@ class ReadTodoTests(AuthenticationTests): self.assertAlmostEqual( read.json.pop('completion_timestamp'), TIMESTAMP, - places=3 + places=3, ) self.assertEqual(read.json, expected)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 4 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt", "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 bcrypt==4.0.1 certifi==2021.5.30 coverage==6.2 coveralls==3.3.1 dataclasses==0.8 doc8==0.11.2 docopt==0.6.2 docutils==0.18.1 execnet==1.9.0 flake8==3.9.2 Flask==0.10.1 Flask-Bcrypt==0.7.1 Flask-JsonSchema==0.1.1 Flask-Login==0.3.2 Flask-Negotiate==0.1.0 Flask-SQLAlchemy==2.1 Flask-Testing==0.8.1 freezegun==1.2.2 greenlet==2.0.2 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 jsonschema==3.2.0 MarkupSafe==2.0.1 mccabe==0.6.1 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2016.4 -e git+https://github.com/adamtheturtle/todo.git@1d4c12ba785e521b5b0b8b40d54613280cf0bb34#egg=Qlutter_TODOer requests==2.10.0 responses==0.17.0 restructuredtext-lint==1.4.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-httpdomain==1.8.1 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 SQLAlchemy==1.4.54 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: todo channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - bcrypt==4.0.1 - coverage==6.2 - coveralls==3.3.1 - dataclasses==0.8 - doc8==0.11.2 - docopt==0.6.2 - docutils==0.18.1 - execnet==1.9.0 - flake8==3.9.2 - flask==0.10.1 - flask-bcrypt==0.7.1 - flask-jsonschema==0.1.1 - flask-login==0.3.2 - flask-negotiate==0.1.0 - flask-sqlalchemy==2.1 - flask-testing==0.8.1 - freezegun==1.2.2 - greenlet==2.0.2 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - jsonschema==3.2.0 - markupsafe==2.0.1 - mccabe==0.6.1 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2016.4 - requests==2.10.0 - responses==0.17.0 - restructuredtext-lint==1.4.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-httpdomain==1.8.1 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sqlalchemy==1.4.54 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/todo
[ "todoer/tests/test_todoer.py::SignupTests::test_incorrect_content_type", "todoer/tests/test_todoer.py::LoginTests::test_incorrect_content_type", "todoer/tests/test_todoer.py::LogoutTests::test_incorrect_content_type", "todoer/tests/test_todoer.py::LogoutTests::test_not_logged_in", "todoer/tests/test_todoer.py::UserTests::test_different_password_different_token", "todoer/tests/test_todoer.py::UserTests::test_get_auth_token", "todoer/tests/test_todoer.py::UserTests::test_get_id", "todoer/tests/test_todoer.py::ReadTodoTests::test_incorrect_content_type", "todoer/tests/test_todoer.py::ListTodosTests::test_incorrect_content_type", "todoer/tests/test_todoer.py::ListTodosTests::test_not_logged_in", "todoer/tests/test_todoer.py::UpdateTodoTests::test_incorrect_content_type" ]
[ "todoer/tests/test_todoer.py::SignupTests::test_existing_user", "todoer/tests/test_todoer.py::SignupTests::test_missing_email", "todoer/tests/test_todoer.py::SignupTests::test_missing_password", "todoer/tests/test_todoer.py::SignupTests::test_passwords_hashed", "todoer/tests/test_todoer.py::SignupTests::test_signup", "todoer/tests/test_todoer.py::LoginTests::test_login", "todoer/tests/test_todoer.py::LoginTests::test_missing_email", "todoer/tests/test_todoer.py::LoginTests::test_missing_password", "todoer/tests/test_todoer.py::LoginTests::test_non_existant_user", "todoer/tests/test_todoer.py::LoginTests::test_remember_me_cookie_set", "todoer/tests/test_todoer.py::LoginTests::test_wrong_password", "todoer/tests/test_todoer.py::LogoutTests::test_logout", "todoer/tests/test_todoer.py::LogoutTests::test_logout_twice", "todoer/tests/test_todoer.py::LoadUserTests::test_user_does_not_exist", "todoer/tests/test_todoer.py::LoadUserTests::test_user_exists", "todoer/tests/test_todoer.py::LoadUserFromTokenTests::test_fake_token", "todoer/tests/test_todoer.py::LoadUserFromTokenTests::test_load_user_from_token", "todoer/tests/test_todoer.py::CreateTodoTests::test_current_completion_time", "todoer/tests/test_todoer.py::CreateTodoTests::test_incorrect_content_type", "todoer/tests/test_todoer.py::CreateTodoTests::test_missing_completed_flag", "todoer/tests/test_todoer.py::CreateTodoTests::test_missing_text", "todoer/tests/test_todoer.py::CreateTodoTests::test_not_logged_in", "todoer/tests/test_todoer.py::CreateTodoTests::test_success_response", "todoer/tests/test_todoer.py::ReadTodoTests::test_completed", "todoer/tests/test_todoer.py::ReadTodoTests::test_multiple_todos", "todoer/tests/test_todoer.py::ReadTodoTests::test_non_existant", "todoer/tests/test_todoer.py::ReadTodoTests::test_not_logged_in", "todoer/tests/test_todoer.py::ReadTodoTests::test_success", "todoer/tests/test_todoer.py::DeleteTodoTests::test_delete_twice", "todoer/tests/test_todoer.py::DeleteTodoTests::test_incorrect_content_type", "todoer/tests/test_todoer.py::DeleteTodoTests::test_not_logged_in", "todoer/tests/test_todoer.py::DeleteTodoTests::test_success", "todoer/tests/test_todoer.py::ListTodosTests::test_filter_completed", "todoer/tests/test_todoer.py::ListTodosTests::test_filter_not_completed", "todoer/tests/test_todoer.py::ListTodosTests::test_list", "todoer/tests/test_todoer.py::ListTodosTests::test_no_todos", "todoer/tests/test_todoer.py::UpdateTodoTests::test_change_content", "todoer/tests/test_todoer.py::UpdateTodoTests::test_change_content_and_flag", "todoer/tests/test_todoer.py::UpdateTodoTests::test_flag_completed", "todoer/tests/test_todoer.py::UpdateTodoTests::test_flag_completed_already_completed", "todoer/tests/test_todoer.py::UpdateTodoTests::test_flag_not_completed", "todoer/tests/test_todoer.py::UpdateTodoTests::test_non_existant", "todoer/tests/test_todoer.py::UpdateTodoTests::test_not_logged_in", "todoer/tests/test_todoer.py::UpdateTodoTests::test_remain_same" ]
[]
[]
null
543
peterbe__hashin-22
ce536a0cffac911124b9af4d14ec0ab79e32816a
2016-05-17 12:43:56
ce536a0cffac911124b9af4d14ec0ab79e32816a
diff --git a/hashin.py b/hashin.py index 510e9bf..d2d1fe6 100755 --- a/hashin.py +++ b/hashin.py @@ -120,7 +120,6 @@ def run(spec, file, algorithm, python_versions=None, verbose=False): def amend_requirements_content(requirements, package, new_lines): - # if the package wasn't already there, add it to the bottom if '%s==' % package not in requirements: # easy peasy @@ -132,7 +131,7 @@ def amend_requirements_content(requirements, package, new_lines): lines = [] padding = ' ' * 4 for line in requirements.splitlines(): - if '{0}=='.format(package) in line: + if line.startswith('{0}=='.format(package)): lines.append(line) elif lines and line.startswith(padding): lines.append(line)
Wrong package replaced when target name is found in existing package For example, an attempt to add hashes for the `selenium` package replaces the `pytest-selenium` package. Another example would be `pytest-django` and `django`. Before: ```ini pytest-selenium==1.2.1 \ --hash=sha256:e82f0a265b0e238ac42ac275d79313d0a7e0bef1a450633aeb3d6549cc14f517 \ --hash=sha256:bd2121022ff3255ce82faec0ef3602462ec6bce9ca627b53462986cfc9b391e9 selenium==2.52.0 \ --hash=sha256:820550a740ca1f746c399a0101986c0e6f94fbfe3c6f976e3f694db452cbe124 ``` Command: ```bash $ hashin selenium==2.53.1 requirements.txt ``` After: ```ini selenium==2.53.1 \ --hash=sha256:b1af142650ed7025f906349ae0d7ed1f1a1e635e6ce7ac67e2b2f854f9f8fdc1 \ --hash=sha256:53929418a41295b526fbb68e43bc32fe93c3ef99c030b9e705caf1de486440de ```
peterbe/hashin
diff --git a/tests/test_cli.py b/tests/test_cli.py index 839c27a..40c9d50 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -188,6 +188,29 @@ autocompeter==1.2.3 \\ ) self.assertEqual(result, previous + new_lines) + def test_amend_requirements_content_new_similar_name(self): + """This test came from https://github.com/peterbe/hashin/issues/15""" + previous_1 = """ +pytest-selenium==1.2.1 \ + --hash=sha256:e82f0a265b0e238ac42ac275d79313d0a7e0bef1a450633aeb3d6549cc14f517 \ + --hash=sha256:bd2121022ff3255ce82faec0ef3602462ec6bce9ca627b53462986cfc9b391e9 + """.strip() + '\n' + previous_2 = """ +selenium==2.52.0 \ + --hash=sha256:820550a740ca1f746c399a0101986c0e6f94fbfe3c6f976e3f694db452cbe124 + """.strip() + '\n' + new_lines = """ +selenium==2.53.1 \ + --hash=sha256:b1af142650ed7025f906349ae0d7ed1f1a1e635e6ce7ac67e2b2f854f9f8fdc1 \ + --hash=sha256:53929418a41295b526fbb68e43bc32fe93c3ef99c030b9e705caf1de486440de + """.strip() + result = hashin.amend_requirements_content( + previous_1 + previous_2, 'selenium', new_lines + ) + self.assertTrue(previous_1 in result) + self.assertTrue(previous_2 not in result) + self.assertTrue(new_lines in result) + @cleanup_tmpdir('hashin*') @mock.patch('hashin.urlopen') def test_run(self, murlopen):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock", "flake8", "black", "therapist", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio", "pytest-bdd", "pytest-benchmark", "pytest-randomly", "responses", "hypothesis", "freezegun", "trustme", "requests-mock", "requests", "tomlkit" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "test-requirements.txt", "lint-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 black==25.1.0 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 click==8.1.8 colorama==0.4.6 coverage==7.8.0 cryptography==44.0.2 exceptiongroup==1.2.2 execnet==2.1.1 flake8==7.2.0 freezegun==1.5.1 gherkin-official==29.0.0 -e git+https://github.com/peterbe/hashin.git@ce536a0cffac911124b9af4d14ec0ab79e32816a#egg=hashin hypothesis==6.130.5 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 Mako==1.3.9 MarkupSafe==3.0.2 mccabe==0.7.0 mock==5.2.0 mypy-extensions==1.0.0 packaging==24.2 parse==1.20.2 parse_type==0.6.4 pathspec==0.12.1 platformdirs==4.3.7 pluggy==1.5.0 py-cpuinfo==9.0.0 pycodestyle==2.13.0 pycparser==2.22 pyflakes==3.3.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-bdd==8.1.0 pytest-benchmark==5.1.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-randomly==3.16.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 requests-mock==1.12.1 responses==0.25.7 six==1.17.0 sortedcontainers==2.4.0 therapist==2.2.0 tomli==2.2.1 tomlkit==0.13.2 trustme==1.2.1 typing_extensions==4.13.0 urllib3==2.3.0 zipp==3.21.0
name: hashin channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - black==25.1.0 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - click==8.1.8 - colorama==0.4.6 - coverage==7.8.0 - cryptography==44.0.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - flake8==7.2.0 - freezegun==1.5.1 - gherkin-official==29.0.0 - hypothesis==6.130.5 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - mako==1.3.9 - markupsafe==3.0.2 - mccabe==0.7.0 - mock==5.2.0 - mypy-extensions==1.0.0 - packaging==24.2 - parse==1.20.2 - parse-type==0.6.4 - pathspec==0.12.1 - platformdirs==4.3.7 - pluggy==1.5.0 - py-cpuinfo==9.0.0 - pycodestyle==2.13.0 - pycparser==2.22 - pyflakes==3.3.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-bdd==8.1.0 - pytest-benchmark==5.1.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-randomly==3.16.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - requests-mock==1.12.1 - responses==0.25.7 - six==1.17.0 - sortedcontainers==2.4.0 - therapist==2.2.0 - tomli==2.2.1 - tomlkit==0.13.2 - trustme==1.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 - zipp==3.21.0 prefix: /opt/conda/envs/hashin
[ "tests/test_cli.py::Tests::test_amend_requirements_content_new_similar_name" ]
[ "tests/test_cli.py::Tests::test_run" ]
[ "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_2", "tests/test_cli.py::Tests::test_get_latest_version_simple", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_amonst_others_2", "tests/test_cli.py::Tests::test_expand_python_version", "tests/test_cli.py::Tests::test_filter_releases", "tests/test_cli.py::Tests::test_get_hashes_error", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_amonst_others", "tests/test_cli.py::Tests::test_amend_requirements_content_new", "tests/test_cli.py::Tests::test_release_url_metadata_python", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement", "tests/test_cli.py::Tests::test_amend_requirements_content_replacement_single_to_multi" ]
[]
MIT License
544
sigmavirus24__github3.py-613
f6948ac9097f61dd44d8666ac1de42edbea666d5
2016-05-17 16:50:13
05ed0c6a02cffc6ddd0e82ce840c464e1c5fd8c4
diff --git a/github3/pulls.py b/github3/pulls.py index 10457b7d..497e01f0 100644 --- a/github3/pulls.py +++ b/github3/pulls.py @@ -8,7 +8,6 @@ This module contains all the classes relating to pull requests. """ from __future__ import unicode_literals -from re import match from json import dumps from . import models @@ -178,10 +177,8 @@ class PullRequest(models.GitHubCore): #: GitHub.com url for review comments (not a template) self.review_comments_url = pull.get('review_comments_url') - m = match('https?://[\w\d\-\.\:]+/(\S+)/(\S+)/(?:issues|pull)?/\d+', - self.issue_url) #: Returns ('owner', 'repository') this issue was filed on. - self.repository = m.groups() + self.repository = self.base.repo #: The state of the pull self.state = pull.get('state') #: The title of the request
PullRequest.respository return on GitHub Enterprise instance [`github3.pulls.PullRequest.respository`](https://github.com/sigmavirus24/github3.py/blob/0.9.3/github3/pulls.py#L188-L189) returns `(u'api/v3/repos/user', u'repo')` on GitHub Enterprise instances. I believe the expected return shouls be ``(u'user', u'repo')` . <bountysource-plugin> --- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/7415115-pullrequest-respository-return-on-github-enterprise-instance?utm_campaign=plugin&utm_content=tracker%2F183477&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F183477&utm_medium=issues&utm_source=github). </bountysource-plugin>
sigmavirus24/github3.py
diff --git a/tests/cassettes/PullRequest_single.json b/tests/cassettes/PullRequest_single.json new file mode 100644 index 00000000..47a27b6a --- /dev/null +++ b/tests/cassettes/PullRequest_single.json @@ -0,0 +1,1 @@ +{"http_interactions": [{"request": {"body": {"string": "", "encoding": "utf-8"}, "headers": {"Accept-Charset": "utf-8", "Content-Type": "application/json", "Accept-Encoding": "gzip, deflate", "Accept": "application/vnd.github.v3.full+json", "User-Agent": "github3.py/1.0.0"}, "method": "GET", "uri": "https://api.github.com/repos/sigmavirus24/github3.py"}, "response": {"body": {"string": "", "base64_string": "H4sIAAAAAAAAA62YTY+jOBCG/0rEddNxgKTzcZmd0+ze5jB72UtkwASrASPbJEqj/u/7GgOBrDZJt1dqRQntevy6XGWq3Hg88fbhxl9ufH/ulbRg3t47cp3VUbioLt7cS+s8P3T/UPxY0BOXtQpWZDJKnEsmvX3j5eLISzDGQ0Ex0wSr5TZczj16oprKQy1zjMu0rtSeEPtQLSy1VkzGotSs1ItYFKQm1vgbUEfZAQzTi/3VNly/JttdugvW7HUX+JttxJif7EIapxsY3ExU8W4SS8ZMityozXSR3+izulqTm8GpyHNxBuV2RY8mIoOlcXNL4eXxixRYNkTojMGxWNKHcRRX+vOiWqsGu6v0gSeGo7BbkiWfFtbZQZYJjo+GSFaJFlhHKpa80lyUnxc4sQZNyCMt+Tv9Gg3WChAj7fNSWitYsxMC9fPm1qwhleQnGl+MaySLGT/B2V9E3tiDqC+Vyem/EBTG9VyzA00Kk6MpzRX7mHvt9BqD2gdzpOSz0T89AxI27Com/HnRmShnOY8klZdZKuSMI6FlSmPE6uyMM2aGcJ394PqPOpp9//nnKYRAjHsblNzN3Nb5k2ScyjGkB3tyF4H0BACS3tjFiWPsG4LPLp9ipDqNhKRaPDo07gucgBoy/mliSTNaOAlvAQBlQrh5sgUAxJWq2VOhfX/hLUeRPn/KuojskfdM1txHWwK0UoVzvmTMyYMDpCH9qYx0KOPMDdszGmK/tbtNj05SjT0wUS4iJw5elKSFNERl1L6H9MFVnaEaxgQqWeos1TAGqJaO+93KNJABiZegxtY76ewZpOk8mtPyWNOjG3WAYNfNq/pI3x8WMfdz50oB0pRvkke1+yF35RiltnZAvru59Iq5QtuC5H6Z88ABo8KmdUFR8Ed1wX1ih5iE/f+ANXF6iza/H5cxj+UaRkOuZ7I99Du6i3e7U7/XSZrrHF2v4BQSPYM0v1VUZ+bkwlQVlcxFdIcgTURRbC0WiyZjtC2rCyYdM9gSgKIyzlA1uuhsegaqnoLqtlpPjcwE1XsuaOLk2wECoN1GF62WMI6xCk2qk8AWMCYWPGdKi9LtjL1SxuxSaJ7y+JmO5X66TUDNN8XLmM1pns8RtZrHHHGMWtvsIgpO5uYhS8AycEdgO5WcIaSdvC6ZZTTEdpqxZGhEkgPVaCCCpR+8LMMXP/zl7/br7X4d/o2V1FUyGbN6WW5egnbMao0/M6aqVTbC2CHbX8tgv16BZIbgBOxCEN9w/4BP3Hn8q78ftRTm1gCGSmVXw9+vZvv/uBzpzOIcsXQT9M/Pebp9LT02hdRMFKxCmdBdswyrDKvLAp5O0H4lIlYL9MDErIy/Y+g2CMJJQRCLusR++Ds8PlON2hWv3vHDvpAYmj4zNVUHm6beXsvadJV4cj0GRg/P/I0PHZ9t2jr66wanJJdSdJdFJZIU/X7Fyo49yMBA263tjc1oBHTjQS+7W0XCUlrn+mCLZ8hOUPXnooLukukz2r4ebGjjiqNf9vbjH8Cshcw6EwAA", "encoding": "utf-8"}, "headers": {"vary": "Accept, Accept-Encoding", "x-served-by": "03d91026ad8428f4d9966d7434f9d82e", "x-xss-protection": "1; mode=block", "x-content-type-options": "nosniff", "etag": "\"103c261a609253cc5113039f6ab21f0e\"", "access-control-allow-credentials": "true", "status": "200 OK", "x-ratelimit-remaining": "54", "x-github-media-type": "github.v3; param=full; format=json", "access-control-expose-headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "transfer-encoding": "chunked", "x-github-request-id": "48A0C4D3:7DF9:2EE6AA1:53D5BBD8", "cache-control": "public, max-age=60, s-maxage=60", "last-modified": "Wed, 23 Jul 2014 19:45:45 GMT", "date": "Mon, 28 Jul 2014 02:56:25 GMT", "access-control-allow-origin": "*", "content-security-policy": "default-src 'none'", "content-encoding": "gzip", "strict-transport-security": "max-age=31536000; includeSubdomains", "server": "GitHub.com", "x-ratelimit-limit": "60", "x-frame-options": "deny", "content-type": "application/json; charset=utf-8", "x-ratelimit-reset": "1406517556"}, "status": {"message": "OK", "code": 200}, "url": "https://api.github.com/repos/sigmavirus24/github3.py"}, "recorded_at": "2014-07-28T02:56:25"}, {"request": {"body": {"string": "", "encoding": "utf-8"}, "headers": {"Accept-Charset": "utf-8", "Content-Type": "application/json", "Accept-Encoding": "gzip, deflate", "Accept": "application/vnd.github.v3.full+json", "User-Agent": "github3.py/1.0.0"}, "method": "GET", "uri": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/235"}, "response": {"body": {"string": "", "base64_string": "H4sIAAAAAAAAA+1aW2/ruBH+K4KfWtSxLMkX2Tg42/PUC4p20WZfFgs4lETZRGRJlShnc4T8935DSral+NixafQpgBPYEufjcIYz5FzqQVUkg+VgI2VeLm2b5WK0FnJTBaMw29oFz7PSLsV6y3aiqEp3Yuu33ih/tfMqSUrb9aaD4UBEg6Uznbjj6WQxBNw2WXWRj1DP4TVwkYjj2wFGRA6mcibDjQGMoqfFlWXFezhXSUoBtKJKq23Ai8ESghsOSskkhwLCJCt5hLmkkAk9+BZF1r95wlnJR6wsuSwtJmUhggrjh4OqJIh6kGRrkWJ4sBYJUGWjCm/mePPJcMB2TLKiz7p6WDaKJqQwSyVPpdJ5ZWvinwC1LhoAUu9gNnZmk2juLgIWMz/0He7NvTh0o/GYx8EiJLbO7SaaqbSPOD2/TY4GxlmSZC+g7q+ku127E9h7KjCmv4t0fQMCqGo7kxsOQWIJbyQYUcrrmFEUNcynlCsREQZUXxQ8uoqhhgbsvKTgpFYWqsCqoAwLkUuRpdcx1qEEUlasWSq+s+uRQFkCQDmNq1alKEDJd9iE15FqktrOC7Fj4SuJouAhFzsI9ga4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VE17bwdpYxIE1oNJ9/fLPneKk8KG4LWrT3tiaZ+sYB6L5tGnPbBiuyPjt0qfU5xf96TrgL0fR1aMD+LJL1D60RG+7NI8lkkoTZYs3ZN43rp4YqEOum7Cw2uxjRAXQtcxONRJFQzLC6cPhVG0L6pf6ITIkQzJTUIxtS2h+Fv/wNzD6LGUi8AAA==", "encoding": "utf-8"}, "headers": {"vary": "Accept, Accept-Encoding", "x-served-by": "3061975e1f37121b3751604ad153c687", "x-xss-protection": "1; mode=block", "x-content-type-options": "nosniff", "etag": "\"42d9e03172ef97d5dbb406c4702c5c0e\"", "access-control-allow-credentials": "true", "status": "200 OK", "x-ratelimit-remaining": "53", "x-github-media-type": "github.v3; param=full; format=json", "access-control-expose-headers": "ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval", "transfer-encoding": "chunked", "x-github-request-id": "48A0C4D3:7DF9:2EE6AAD:53D5BBD9", "cache-control": "public, max-age=60, s-maxage=60", "last-modified": "Mon, 28 Jul 2014 01:14:14 GMT", "date": "Mon, 28 Jul 2014 02:56:25 GMT", "access-control-allow-origin": "*", "content-security-policy": "default-src 'none'", "content-encoding": "gzip", "strict-transport-security": "max-age=31536000; includeSubdomains", "server": "GitHub.com", "x-ratelimit-limit": "60", "x-frame-options": "deny", "content-type": "application/json; charset=utf-8", "x-ratelimit-reset": "1406517556"}, "status": {"message": "OK", "code": 200}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/pulls/235"}, "recorded_at": "2014-07-28T02:56:25"}], "recorded_with": "betamax/0.3.2"} diff --git a/tests/integration/test_pulls.py b/tests/integration/test_pulls.py index b32ef019..70c00b16 100644 --- a/tests/integration/test_pulls.py +++ b/tests/integration/test_pulls.py @@ -130,6 +130,14 @@ class TestPullRequest(IntegrationHelper): p = self.get_pull_request(num=241) assert p.update(p.title) is True + def test_repository(self): + """Show that the pull request has the owner repository.""" + self.basic_login() + cassette_name = self.cassette_name('single') + with self.recorder.use_cassette(cassette_name): + p = self.get_pull_request() + assert p.repository == ('sigmavirus24', 'github3.py') + class TestReviewComment(IntegrationHelper):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=2.3.5", "betamax>=0.5.0", "betamax_matchers>=0.2.0", "mock==1.0.1" ], "pre_install": null, "python": "3.4", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 betamax==0.8.1 betamax-matchers==0.4.0 certifi==2021.5.30 charset-normalizer==2.0.12 distlib==0.3.9 filelock==3.4.1 -e git+https://github.com/sigmavirus24/github3.py.git@f6948ac9097f61dd44d8666ac1de42edbea666d5#egg=github3.py idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 mock==1.0.1 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 requests-toolbelt==1.0.0 six==1.17.0 swebench-matterhorn @ file:///swebench_matterhorn toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 uritemplate==4.1.1 uritemplate.py==3.0.2 urllib3==1.26.20 virtualenv==20.17.1 zipp==3.6.0
name: github3.py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - betamax==0.8.1 - betamax-matchers==0.4.0 - charset-normalizer==2.0.12 - distlib==0.3.9 - filelock==3.4.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - mock==1.0.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - requests-toolbelt==1.0.0 - six==1.17.0 - swebench-matterhorn==0.0.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - uritemplate==4.1.1 - uritemplate-py==3.0.2 - urllib3==1.26.20 - virtualenv==20.17.1 - wheel==0.21.0 - zipp==3.6.0 prefix: /opt/conda/envs/github3.py
[ "tests/integration/test_pulls.py::TestPullRequest::test_repository" ]
[]
[ "tests/integration/test_pulls.py::TestPullRequest::test_close", "tests/integration/test_pulls.py::TestPullRequest::test_commits", "tests/integration/test_pulls.py::TestPullRequest::test_create_comment", "tests/integration/test_pulls.py::TestPullRequest::test_create_review_comment", "tests/integration/test_pulls.py::TestPullRequest::test_diff", "tests/integration/test_pulls.py::TestPullRequest::test_files", "tests/integration/test_pulls.py::TestPullRequest::test_is_merged", "tests/integration/test_pulls.py::TestPullRequest::test_issue", "tests/integration/test_pulls.py::TestPullRequest::test_issue_comments", "tests/integration/test_pulls.py::TestPullRequest::test_patch", "tests/integration/test_pulls.py::TestPullRequest::test_reopen", "tests/integration/test_pulls.py::TestPullRequest::test_review_comments", "tests/integration/test_pulls.py::TestPullRequest::test_update", "tests/integration/test_pulls.py::TestReviewComment::test_reply", "tests/integration/test_pulls.py::TestPullFile::test_contents" ]
[]
BSD 3-Clause "New" or "Revised" License
545
box__box-python-sdk-134
3ba6cf1fe50f2f9b3c273d96375dfdc98ea87d3c
2016-05-18 01:31:58
ded623f4b6de0530d8f983d3c3d2cafe646c126b
diff --git a/HISTORY.rst b/HISTORY.rst index ec26cb8..e7ca71f 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -6,6 +6,11 @@ Release History Upcoming ++++++++ +1.5.2 +++++++++++++++++++ + +- Bugfix so that ``OAuth2`` always has the correct tokens after a call to ``refresh()``. + 1.5.1 (2016-03-23) ++++++++++++++++++ diff --git a/boxsdk/auth/oauth2.py b/boxsdk/auth/oauth2.py index a810e79..6b0e9d5 100644 --- a/boxsdk/auth/oauth2.py +++ b/boxsdk/auth/oauth2.py @@ -167,10 +167,17 @@ def _get_tokens(self): """ Get the current access and refresh tokens. + This is a protected method that can be overridden to look up tokens + from an external source (the inverse of the `store_tokens` callback). + + This method does not need to update this object's private token + attributes. Its caller in :class:`OAuth2` is responsible for that. + :return: Tuple containing the current access token and refresh token. + One or both of them may be `None`, if they aren't set. :rtype: - `tuple` of (`unicode`, `unicode`) + `tuple` of ((`unicode` or `None`), (`unicode` or `None`)) """ return self._access_token, self._refresh_token @@ -181,16 +188,24 @@ def refresh(self, access_token_to_refresh): :param access_token_to_refresh: The expired access token, which needs to be refreshed. + Pass `None` if you don't have the access token. :type access_token_to_refresh: - `unicode` + `unicode` or `None` + :return: + Tuple containing the new access token and refresh token. + The refresh token may be `None`, if the authentication scheme + doesn't use one, or keeps it hidden from this client. + :rtype: + `tuple` of (`unicode`, (`unicode` or `None`)) """ with self._refresh_lock: - access_token, refresh_token = self._get_tokens() + access_token, refresh_token = self._get_and_update_current_tokens() # The lock here is for handling that case that multiple requests fail, due to access token expired, at the # same time to avoid multiple session renewals. - if access_token_to_refresh == access_token: - # If the active access token is the same as the token needs to be refreshed, we make the request to - # refresh the token. + if (access_token is None) or (access_token_to_refresh == access_token): + # If the active access token is the same as the token needs to + # be refreshed, or if we don't currently have any active access + # token, we make the request to refresh the token. return self._refresh(access_token_to_refresh) else: # If the active access token (self._access_token) is not the same as the token needs to be refreshed, @@ -213,11 +228,37 @@ def _get_state_csrf_token(): return 'box_csrf_token_' + ''.join(ascii_alphabet[int(system_random.random() * ascii_len)] for _ in range(16)) def _store_tokens(self, access_token, refresh_token): - self._access_token = access_token - self._refresh_token = refresh_token + self._update_current_tokens(access_token, refresh_token) if self._store_tokens_callback is not None: self._store_tokens_callback(access_token, refresh_token) + def _get_and_update_current_tokens(self): + """Get the current access and refresh tokens, while also storing them in this object's private attributes. + + :return: + Same as for :meth:`_get_tokens()`. + """ + tokens = self._get_tokens() + self._update_current_tokens(*tokens) + return tokens + + def _update_current_tokens(self, access_token, refresh_token): + """Store the latest tokens in this object's private attributes. + + :param access_token: + The latest access token. + May be `None`, if it hasn't been provided. + :type access_token: + `unicode` or `None` + :param refresh_token: + The latest refresh token. + May be `None`, if the authentication scheme doesn't use one, or if + it hasn't been provided. + :type refresh_token: + `unicode` or `None` + """ + self._access_token, self._refresh_token = access_token, refresh_token + def send_token_request(self, data, access_token, expect_refresh_token=True): """ Send the request to acquire or refresh an access token. @@ -262,7 +303,7 @@ def revoke(self): Revoke the authorization for the current access/refresh token pair. """ with self._refresh_lock: - access_token, refresh_token = self._get_tokens() + access_token, refresh_token = self._get_and_update_current_tokens() token_to_revoke = access_token or refresh_token if token_to_revoke is None: return diff --git a/boxsdk/auth/redis_managed_oauth2.py b/boxsdk/auth/redis_managed_oauth2.py index f333849..a8d85ac 100644 --- a/boxsdk/auth/redis_managed_oauth2.py +++ b/boxsdk/auth/redis_managed_oauth2.py @@ -30,13 +30,7 @@ def __init__(self, unique_id=uuid4(), redis_server=None, *args, **kwargs): refresh_lock = Lock(redis=self._redis_server, name='{0}_lock'.format(self._unique_id)) super(RedisManagedOAuth2Mixin, self).__init__(*args, refresh_lock=refresh_lock, **kwargs) if self._access_token is None: - self._update_current_tokens() - - def _update_current_tokens(self): - """ - Get the latest tokens from redis and store them. - """ - self._access_token, self._refresh_token = self._redis_server.hvals(self._unique_id) or (None, None) + self._get_and_update_current_tokens() @property def unique_id(self): @@ -51,8 +45,7 @@ def _get_tokens(self): Base class override. Gets the latest tokens from redis before returning them. """ - self._update_current_tokens() - return super(RedisManagedOAuth2Mixin, self)._get_tokens() + return self._redis_server.hvals(self._unique_id) or (None, None) def _store_tokens(self, access_token, refresh_token): """ diff --git a/boxsdk/version.py b/boxsdk/version.py index c64a173..9f6ca5f 100644 --- a/boxsdk/version.py +++ b/boxsdk/version.py @@ -3,4 +3,4 @@ from __future__ import unicode_literals, absolute_import -__version__ = '1.5.1' +__version__ = '1.5.2' diff --git a/requirements-dev.txt b/requirements-dev.txt index f962a37..66fa4cd 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,17 +1,10 @@ -r requirements.txt bottle jsonpatch -mock<=1.0.1 +mock>=2.0.0 pep8 pylint - -# Temporary version exclusion of the 2.8 release line. -# <https://github.com/pytest-dev/pytest/issues/1085> breaks pytest on Python 2, only in 2.8.1. Fixed in upcoming 2.8.2. -# <https://github.com/pytest-dev/pytest/issues/1035> breaks pytest on Python 2.6, on all currently existing 2.8.* -# releases. Has not yet been fixed in the master branch, so there isn't a guarantee that it will work in the upcoming -# 2.8.2 release. -pytest<2.8 - +pytest>=2.8.3 pytest-cov pytest-xdist sphinx
BoxSession._renew_session does not set previously refreshed tokens I am using `CooperativelyManagedOAuth2` so that I can use the same oauth tokens for multiple clients but it seems like refreshed tokens do not get updated in the session if the tokens were refreshed by another client. I have two instances of the oauth class using the same tokens and two clients using one of the instances. For example, say there are two clients initialized with the same tokens but different `CooperativelyManagedOAuth2` instances. The first client makes a request, sees the access token is expired and refreshes the tokens. The tokens in the first client's oauth instance are updated with the new tokens. The second client then makes a request, sees it's access token is expired and tries to refresh the token. The token is already refreshed so it does not try to refresh them again but then does not replace the old tokens so when client two retries the request it will raise a `BoxAPIException`.
box/box-python-sdk
diff --git a/test/conftest.py b/test/conftest.py index c5e61dd..a5958da 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -102,6 +102,12 @@ def access_token(): return 'T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl' [email protected](scope='session') +def new_access_token(): + # Must be distinct from access_token. + return 'ZFoWjFHvNbvVqHjlT9cE5asGnuyYCCqI' + + @pytest.fixture(scope='session') def refresh_token(): return 'J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgRb' diff --git a/test/unit/auth/test_jwt_auth.py b/test/unit/auth/test_jwt_auth.py index c4d5f11..a117850 100644 --- a/test/unit/auth/test_jwt_auth.py +++ b/test/unit/auth/test_jwt_auth.py @@ -73,8 +73,8 @@ def jwt_auth_init_mocks( } mock_network_layer.request.return_value = successful_token_response - key_file = mock_open() - with patch('boxsdk.auth.jwt_auth.open', key_file, create=True) as jwt_auth_open: + key_file_read_data = 'key_file_read_data' + with patch('boxsdk.auth.jwt_auth.open', mock_open(read_data=key_file_read_data), create=True) as jwt_auth_open: with patch('cryptography.hazmat.primitives.serialization.load_pem_private_key') as load_pem_private_key: oauth = JWTAuth( client_id=fake_client_id, @@ -89,9 +89,9 @@ def jwt_auth_init_mocks( ) jwt_auth_open.assert_called_once_with(sentinel.rsa_path) - key_file.return_value.read.assert_called_once_with() # pylint:disable=no-member + jwt_auth_open.return_value.read.assert_called_once_with() # pylint:disable=no-member load_pem_private_key.assert_called_once_with( - key_file.return_value.read.return_value, # pylint:disable=no-member + key_file_read_data, password=rsa_passphrase, backend=default_backend(), ) diff --git a/test/unit/auth/test_oauth2.py b/test/unit/auth/test_oauth2.py index af4d6ed..8fdf7b2 100644 --- a/test/unit/auth/test_oauth2.py +++ b/test/unit/auth/test_oauth2.py @@ -5,9 +5,11 @@ from functools import partial import re from threading import Thread +import uuid from mock import Mock import pytest +from six.moves import range # pylint:disable=redefined-builtin from six.moves.urllib import parse as urlparse # pylint:disable=import-error,no-name-in-module,wrong-import-order from boxsdk.exception import BoxOAuthException @@ -314,3 +316,41 @@ def test_revoke_sends_revoke_request( access_token=access_token, ) assert oauth.access_token is None + + +def test_tokens_get_updated_after_noop_refresh(client_id, client_secret, access_token, new_access_token, refresh_token, mock_network_layer): + """`OAuth2` object should update its state with new tokens, after no-op refresh. + + If the protected method `_get_tokens()` returns new tokens, refresh is + skipped, and those tokens are used. + + This is a regression test for issue #128 [1]. We would return the new + tokens without updating the object state. Subsequent uses of the `OAuth2` + object would use the old tokens. + + [1] <https://github.com/box/box-python-sdk/issues/128> + """ + new_refresh_token = uuid.uuid4().hex + new_tokens = (new_access_token, new_refresh_token) + + class GetTokensOAuth2(OAuth2): + def _get_tokens(self): + """Return a new set of tokens, without updating any state. + + In order for the test to pass, the `OAuth2` object must be + correctly programmed to take this return value and use it to update + its state. + """ + return new_tokens + + oauth = GetTokensOAuth2( + client_id=client_id, + client_secret=client_secret, + access_token=access_token, + refresh_token=refresh_token, + network_layer=mock_network_layer, + ) + assert oauth.access_token == access_token + + assert oauth.refresh(access_token) == new_tokens + assert oauth.access_token == new_access_token diff --git a/test/unit/auth/test_redis_managed_oauth2.py b/test/unit/auth/test_redis_managed_oauth2.py index c03eec1..dc67097 100644 --- a/test/unit/auth/test_redis_managed_oauth2.py +++ b/test/unit/auth/test_redis_managed_oauth2.py @@ -2,6 +2,8 @@ from __future__ import unicode_literals, absolute_import +import uuid + from mock import Mock, patch from boxsdk.auth import redis_managed_oauth2 @@ -21,19 +23,24 @@ def test_redis_managed_oauth2_gets_tokens_from_redis_on_init(access_token, refre assert oauth2.unique_id is unique_id -def test_redis_managed_oauth2_gets_tokens_from_redis_during_refresh(access_token, refresh_token): +def test_redis_managed_oauth2_gets_tokens_from_redis_during_refresh(access_token, refresh_token, new_access_token): + new_refresh_token = uuid.uuid4().hex redis_server = Mock(redis_managed_oauth2.StrictRedis) - redis_server.hvals.return_value = access_token, refresh_token + redis_server.hvals.return_value = new_access_token, new_refresh_token unique_id = Mock() - with patch.object(redis_managed_oauth2.RedisManagedOAuth2Mixin, '_update_current_tokens'): - oauth2 = redis_managed_oauth2.RedisManagedOAuth2( - client_id=None, - client_secret=None, - unique_id=unique_id, - redis_server=redis_server, - ) + oauth2 = redis_managed_oauth2.RedisManagedOAuth2( + access_token=access_token, + refresh_token=refresh_token, + client_id=None, + client_secret=None, + unique_id=unique_id, + redis_server=redis_server, + ) + assert oauth2.access_token == access_token + redis_server.hvals.assert_not_called() - assert oauth2.refresh('bogus_access_token') == (access_token, refresh_token) + assert oauth2.refresh('bogus_access_token') == (new_access_token, new_refresh_token) + assert oauth2.access_token == new_access_token redis_server.hvals.assert_called_once_with(unique_id) diff --git a/test/unit/network/test_logging_network.py b/test/unit/network/test_logging_network.py index 3bd5eb0..58a8c61 100644 --- a/test/unit/network/test_logging_network.py +++ b/test/unit/network/test_logging_network.py @@ -28,7 +28,7 @@ def test_logging_network_does_not_call_setup_logging_if_logger_is_not_none(): logger = Mock(Logger) with patch.object(logging_network, 'setup_logging') as setup_logging: network = LoggingNetwork(logger) - setup_logging.assert_never_called() + setup_logging.assert_not_called() assert network.logger is logger
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 5 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-xdist", "mock", "sqlalchemy", "bottle" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
async-timeout==4.0.3 bottle==0.13.2 -e git+https://github.com/box/box-python-sdk.git@3ba6cf1fe50f2f9b3c273d96375dfdc98ea87d3c#egg=boxsdk certifi @ file:///croot/certifi_1671487769961/work/certifi cffi==1.15.1 charset-normalizer==3.4.1 cryptography==44.0.2 exceptiongroup==1.2.2 execnet==2.0.2 greenlet==3.1.1 idna==3.10 importlib-metadata==6.7.0 iniconfig==2.0.0 mock==5.2.0 packaging==24.0 pluggy==1.2.0 pycparser==2.21 PyJWT==2.8.0 pytest==7.4.4 pytest-xdist==3.5.0 redis==5.0.8 requests==2.31.0 requests-toolbelt==1.0.0 six==1.17.0 SQLAlchemy==2.0.40 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: box-python-sdk channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - async-timeout==4.0.3 - bottle==0.13.2 - cffi==1.15.1 - charset-normalizer==3.4.1 - cryptography==44.0.2 - exceptiongroup==1.2.2 - execnet==2.0.2 - greenlet==3.1.1 - idna==3.10 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - mock==5.2.0 - packaging==24.0 - pluggy==1.2.0 - pycparser==2.21 - pyjwt==2.8.0 - pytest==7.4.4 - pytest-xdist==3.5.0 - redis==5.0.8 - requests==2.31.0 - requests-toolbelt==1.0.0 - six==1.17.0 - sqlalchemy==2.0.40 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/box-python-sdk
[ "test/unit/auth/test_oauth2.py::test_tokens_get_updated_after_noop_refresh" ]
[]
[ "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS512-strong_password]", "test/unit/auth/test_oauth2.py::test_get_correct_authorization_url[https://url.com/foo?bar=baz]", "test/unit/auth/test_oauth2.py::test_get_correct_authorization_url[https://\\u0215\\u0155\\u013e.com/\\u0192\\u0151\\u0151?\\u0184\\u0201\\u0155=\\u0184\\u0201\\u017c]", "test/unit/auth/test_oauth2.py::test_get_correct_authorization_url[None]", "test/unit/auth/test_oauth2.py::test_authenticate_send_post_request_with_correct_params", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[0]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[1]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[2]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[3]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[4]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[5]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[6]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[7]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[8]", "test/unit/auth/test_oauth2.py::test_refresh_send_post_request_with_correct_params_and_handles_multiple_requests[9]", "test/unit/auth/test_oauth2.py::test_authenticate_stores_tokens_correctly", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-0]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-1]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-2]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-3]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-4]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-5]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-6]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-7]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-8]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens0-9]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-0]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-1]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-2]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-3]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-4]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-5]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-6]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-7]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-8]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens1-9]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-0]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-1]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-2]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-3]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-4]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-5]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-6]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-7]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-8]", "test/unit/auth/test_oauth2.py::test_refresh_gives_back_the_correct_response_and_handles_multiple_requests[network_response_with_missing_tokens2-9]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_getting_bad_network_response[test_method0]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_getting_bad_network_response[test_method1]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_no_json_object_can_be_decoded[test_method0]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_no_json_object_can_be_decoded[test_method1]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response[network_response_with_missing_tokens0-test_method0]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response[network_response_with_missing_tokens0-test_method1]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response[network_response_with_missing_tokens1-test_method0]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response[network_response_with_missing_tokens1-test_method1]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response[network_response_with_missing_tokens2-test_method0]", "test/unit/auth/test_oauth2.py::test_token_request_raises_box_oauth_exception_when_tokens_are_not_in_the_response[network_response_with_missing_tokens2-test_method1]", "test/unit/auth/test_oauth2.py::test_token_request_allows_missing_refresh_token", "test/unit/auth/test_oauth2.py::test_revoke_sends_revoke_request[fake_access_token-fake_refresh_token-fake_access_token]", "test/unit/auth/test_oauth2.py::test_revoke_sends_revoke_request[None-fake_refresh_token-fake_refresh_token]", "test/unit/auth/test_redis_managed_oauth2.py::test_redis_managed_oauth2_gets_tokens_from_redis_on_init", "test/unit/auth/test_redis_managed_oauth2.py::test_redis_managed_oauth2_gets_tokens_from_redis_during_refresh", "test/unit/auth/test_redis_managed_oauth2.py::test_redis_managed_oauth2_stores_tokens_to_redis_during_refresh", "test/unit/network/test_logging_network.py::test_logging_network_calls_setup_logging_if_logger_is_none", "test/unit/network/test_logging_network.py::test_logging_network_can_be_initialized_if_logger_is_none", "test/unit/network/test_logging_network.py::test_logging_network_does_not_call_setup_logging_if_logger_is_not_none", "test/unit/network/test_logging_network.py::test_logging_network_logs_requests[GET]", "test/unit/network/test_logging_network.py::test_logging_network_logs_requests[POST]", "test/unit/network/test_logging_network.py::test_logging_network_logs_requests[PUT]", "test/unit/network/test_logging_network.py::test_logging_network_logs_requests[DELETE]", "test/unit/network/test_logging_network.py::test_logging_network_logs_requests[OPTIONS]", "test/unit/network/test_logging_network.py::test_logging_network_logs_successful_responses[GET]", "test/unit/network/test_logging_network.py::test_logging_network_logs_successful_responses[POST]", "test/unit/network/test_logging_network.py::test_logging_network_logs_successful_responses[PUT]", "test/unit/network/test_logging_network.py::test_logging_network_logs_successful_responses[DELETE]", "test/unit/network/test_logging_network.py::test_logging_network_logs_successful_responses[OPTIONS]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[502-GET]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[502-POST]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[502-PUT]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[502-DELETE]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[502-OPTIONS]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[503-GET]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[503-POST]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[503-PUT]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[503-DELETE]", "test/unit/network/test_logging_network.py::test_logging_network_logs_non_successful_responses[503-OPTIONS]" ]
[]
Apache License 2.0
546
Juniper__py-junos-eznc-513
4b7d685336e0a18d6a8a5ef96eb0cb7b87221b37
2016-05-18 07:20:23
3ca08f81e0be85394c6fa3e94675dfe03e958e28
diff --git a/README.md b/README.md index 61ab9f5c..0296eb7a 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ There is a growing interest and need to automate the network infrastructure into For questions and general support, please visit our [Google Group](https://groups.google.com/forum/#!forum/junos-python-ez) -For documentation and more usage examples, please visit the _Junos PyEZ_ project page, [here](https://techwiki.juniper.net/Projects/Junos_PyEZ). +For documentation and more usage examples, please visit the _Junos PyEZ_ project page, [here](http://forums.juniper.net/t5/Automation/Where-can-I-learn-more-about-Junos-PyEZ/ta-p/280496). Issues and bugs can be opened in the repository. diff --git a/lib/jnpr/junos/device.py b/lib/jnpr/junos/device.py index 3dcb71df..3438b910 100644 --- a/lib/jnpr/junos/device.py +++ b/lib/jnpr/junos/device.py @@ -496,7 +496,7 @@ class Device(object): self.connected = True self._nc_transform = self.transform - self._norm_transform = lambda: JXML.normalize_xslt.encode('UTF-8') + self._norm_transform = lambda: JXML.normalize_xslt normalize = kvargs.get('normalize', self._normalize) if normalize is True: diff --git a/lib/jnpr/junos/utils/start_shell.py b/lib/jnpr/junos/utils/start_shell.py index b52c518a..61f97df4 100644 --- a/lib/jnpr/junos/utils/start_shell.py +++ b/lib/jnpr/junos/utils/start_shell.py @@ -3,7 +3,7 @@ from select import select import re _JUNOS_PROMPT = '> ' -_SHELL_PROMPT = '(%|#) ' +_SHELL_PROMPT = '% ' _SELECT_WAIT = 0.1 _RECVSZ = 1024 @@ -35,8 +35,8 @@ class StartShell(object): :param str this: expected string/pattern. - :returns: resulting string of data in a list - :rtype: list + :returns: resulting string of data + :rtype: str .. warning:: need to add a timeout safeguard """ @@ -46,8 +46,6 @@ class StartShell(object): rd, wr, err = select([chan], [], [], _SELECT_WAIT) if rd: data = chan.recv(_RECVSZ) - if isinstance(data, bytes): - data = data.decode('utf-8') got.append(data) if re.search(r'{0}\s?$'.format(this), data): break @@ -84,8 +82,8 @@ class StartShell(object): self._client = client self._chan = chan - got = self.wait_for(r'(%|>|#)') - if got[-1].endswith(_JUNOS_PROMPT): + got = self.wait_for('(%|>)') + if not got[-1].endswith(_SHELL_PROMPT): self.send('start shell') self.wait_for(_SHELL_PROMPT) @@ -118,7 +116,7 @@ class StartShell(object): rc = ''.join(self.wait_for(this)) self.last_ok = True if rc.find('0') > 0 else False - return (self.last_ok, got) + return (self.last_ok,got) # ------------------------------------------------------------------------- # CONTEXT MANAGER
Link to techwiki page is broken on README Hi I noticed that the link to the techwiki in the `Support` section of the README is wrong The link is pointing to the techwiki homepage and not the Junos PyEZ project page as suggested https://github.com/Juniper/py-junos-eznc/blob/master/README.md#support ``` For documentation and more usage examples, please visit the Junos PyEZ project page, here. ```
Juniper/py-junos-eznc
diff --git a/tests/unit/utils/test_start_shell.py b/tests/unit/utils/test_start_shell.py index ee728b02..b3812937 100644 --- a/tests/unit/utils/test_start_shell.py +++ b/tests/unit/utils/test_start_shell.py @@ -19,17 +19,9 @@ class TestStartShell(unittest.TestCase): @patch('paramiko.SSHClient') @patch('jnpr.junos.utils.start_shell.StartShell.wait_for') - def test_startshell_open_with_shell_term(self, mock_wait, mock_connect): - mock_wait.return_value = ["user # "] + def test_startshell_open(self, mock_connect, mock_wait): self.shell.open() - mock_wait.assert_called_with('(%|>|#)') - - @patch('paramiko.SSHClient') - @patch('jnpr.junos.utils.start_shell.StartShell.wait_for') - def test_startshell_open_with_junos_term(self, mock_wait, mock_connect): - mock_wait.return_value = ["user > "] - self.shell.open() - mock_wait.assert_called_with('(%|#) ') + mock_connect.assert_called_with('(%|>)') @patch('paramiko.SSHClient') def test_startshell_close(self, mock_connect):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 3 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "pep8", "pyflakes", "coveralls", "ntc_templates", "cryptography==3.2", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
bcrypt==4.2.1 certifi @ file:///croot/certifi_1671487769961/work/certifi cffi==1.15.1 charset-normalizer==3.4.1 coverage==6.5.0 coveralls==3.3.1 cryptography==44.0.2 docopt==0.6.2 exceptiongroup==1.2.2 future==1.0.0 idna==3.10 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 -e git+https://github.com/Juniper/py-junos-eznc.git@4b7d685336e0a18d6a8a5ef96eb0cb7b87221b37#egg=junos_eznc lxml==5.3.1 MarkupSafe==2.1.5 mock==5.2.0 ncclient==0.6.19 netaddr==1.3.0 nose==1.3.7 ntc_templates==4.0.1 packaging==24.0 paramiko==3.5.1 pep8==1.7.1 pluggy==1.2.0 pycparser==2.21 pyflakes==3.0.1 PyNaCl==1.5.0 pytest==7.4.4 PyYAML==6.0.1 requests==2.31.0 scp==0.15.0 six==1.17.0 textfsm==1.1.3 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: py-junos-eznc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bcrypt==4.2.1 - cffi==1.15.1 - charset-normalizer==3.4.1 - coverage==6.5.0 - coveralls==3.3.1 - cryptography==44.0.2 - docopt==0.6.2 - exceptiongroup==1.2.2 - future==1.0.0 - idna==3.10 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - lxml==5.3.1 - markupsafe==2.1.5 - mock==5.2.0 - ncclient==0.6.19 - netaddr==1.3.0 - nose==1.3.7 - ntc-templates==4.0.1 - packaging==24.0 - paramiko==3.5.1 - pep8==1.7.1 - pluggy==1.2.0 - pycparser==2.21 - pyflakes==3.0.1 - pynacl==1.5.0 - pytest==7.4.4 - pyyaml==6.0.1 - requests==2.31.0 - scp==0.15.0 - six==1.17.0 - textfsm==1.1.3 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/py-junos-eznc
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_open" ]
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_context" ]
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_close", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_run", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_wait_for", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_wait_for_regex" ]
[]
Apache License 2.0
547
Juniper__py-junos-eznc-514
4b7d685336e0a18d6a8a5ef96eb0cb7b87221b37
2016-05-18 17:44:30
3ca08f81e0be85394c6fa3e94675dfe03e958e28
diff --git a/lib/jnpr/junos/utils/start_shell.py b/lib/jnpr/junos/utils/start_shell.py index b52c518a..1631ef63 100644 --- a/lib/jnpr/junos/utils/start_shell.py +++ b/lib/jnpr/junos/utils/start_shell.py @@ -3,7 +3,7 @@ from select import select import re _JUNOS_PROMPT = '> ' -_SHELL_PROMPT = '(%|#) ' +_SHELL_PROMPT = '(%|#)\s' _SELECT_WAIT = 0.1 _RECVSZ = 1024
Shell session does not work for root user. I'm using the below example program. ``` #!/usr/bin/env python import jnpr.junos.utils from jnpr.junos import Device from jnpr.junos.utils import * from jnpr.junos.utils.start_shell import * from jnpr.junos.utils.start_shell import StartShell DUT = Device(host='10.252.191.104', user="root", passwd = "password!") DUT.open() print "Device opened!" DUT_ss = StartShell(DUT) DUT_ss.open() print "got thru shell open." print DUT_ss.run("pwd") print DUT_ss.run("ls") ``` We never print the line "got thru shell open" because the library hangs while waiting for the "% " shell prompt to appear. I have a fix i'll be suggesting.
Juniper/py-junos-eznc
diff --git a/tests/unit/utils/test_start_shell.py b/tests/unit/utils/test_start_shell.py index ee728b02..8a4fb59d 100644 --- a/tests/unit/utils/test_start_shell.py +++ b/tests/unit/utils/test_start_shell.py @@ -29,7 +29,7 @@ class TestStartShell(unittest.TestCase): def test_startshell_open_with_junos_term(self, mock_wait, mock_connect): mock_wait.return_value = ["user > "] self.shell.open() - mock_wait.assert_called_with('(%|#) ') + mock_wait.assert_called_with('(%|#)\s') @patch('paramiko.SSHClient') def test_startshell_close(self, mock_connect):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "pep8", "pyflakes", "coveralls", "ntc_templates", "cryptography==3.2", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
bcrypt==4.2.1 certifi @ file:///croot/certifi_1671487769961/work/certifi cffi==1.15.1 charset-normalizer==3.4.1 coverage==6.5.0 coveralls==3.3.1 cryptography==44.0.2 docopt==0.6.2 exceptiongroup==1.2.2 future==1.0.0 idna==3.10 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 -e git+https://github.com/Juniper/py-junos-eznc.git@4b7d685336e0a18d6a8a5ef96eb0cb7b87221b37#egg=junos_eznc lxml==5.3.1 MarkupSafe==2.1.5 mock==5.2.0 ncclient==0.6.19 netaddr==1.3.0 nose==1.3.7 ntc_templates==4.0.1 packaging==24.0 paramiko==3.5.1 pep8==1.7.1 pluggy==1.2.0 pycparser==2.21 pyflakes==3.0.1 PyNaCl==1.5.0 pytest==7.4.4 PyYAML==6.0.1 requests==2.31.0 scp==0.15.0 six==1.17.0 textfsm==1.1.3 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: py-junos-eznc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bcrypt==4.2.1 - cffi==1.15.1 - charset-normalizer==3.4.1 - coverage==6.5.0 - coveralls==3.3.1 - cryptography==44.0.2 - docopt==0.6.2 - exceptiongroup==1.2.2 - future==1.0.0 - idna==3.10 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - lxml==5.3.1 - markupsafe==2.1.5 - mock==5.2.0 - ncclient==0.6.19 - netaddr==1.3.0 - nose==1.3.7 - ntc-templates==4.0.1 - packaging==24.0 - paramiko==3.5.1 - pep8==1.7.1 - pluggy==1.2.0 - pycparser==2.21 - pyflakes==3.0.1 - pynacl==1.5.0 - pytest==7.4.4 - pyyaml==6.0.1 - requests==2.31.0 - scp==0.15.0 - six==1.17.0 - textfsm==1.1.3 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/py-junos-eznc
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_open_with_junos_term" ]
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_context" ]
[ "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_close", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_open_with_shell_term", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_run", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_wait_for", "tests/unit/utils/test_start_shell.py::TestStartShell::test_startshell_wait_for_regex" ]
[]
Apache License 2.0
548
networkx__networkx-2136
5aefafab2f05b97b150c6bf681c21ba6465c8d10
2016-05-19 01:37:02
3f4fd85765bf2d88188cfd4c84d0707152e6cd1e
diff --git a/networkx/readwrite/gml.py b/networkx/readwrite/gml.py index b6ab5e9eb..af8db1d00 100644 --- a/networkx/readwrite/gml.py +++ b/networkx/readwrite/gml.py @@ -435,10 +435,6 @@ def parse_gml_lines(lines, label, destringizer): if label != 'id': G = nx.relabel_nodes(G, mapping) - if 'name' in graph: - G.graph['name'] = graph['name'] - else: - del G.graph['name'] return G diff --git a/networkx/relabel.py b/networkx/relabel.py index ca069c950..8f885432c 100644 --- a/networkx/relabel.py +++ b/networkx/relabel.py @@ -147,7 +147,8 @@ def _relabel_inplace(G, mapping): def _relabel_copy(G, mapping): H = G.__class__() - H.name = "(%s)" % G.name + if G.name: + H.name = "(%s)" % G.name if G.is_multigraph(): H.add_edges_from( (mapping.get(n1, n1),mapping.get(n2, n2),k,d.copy()) for (n1,n2,k,d) in G.edges(keys=True, data=True))
relabel_nodes adds a graph attribute when copy=True I would have expected the following to work: ``` import networkx as nx graph_a = nx.DiGraph() graph_b = nx.relabel_nodes(graph_a, {}, copy=True) print "graph_a.graph", graph_a.graph print "graph_b.graph", graph_b.graph assert graph_a.graph == graph_b.graph ``` However, it does not since [_relabel_copy attempts to copy a non-existent graph attribute, 'name'](https://github.com/networkx/networkx/blob/1675a824d6cdb17c3144ef46ff52a0c2b53a11d1/networkx/relabel.py#L150). I would have expected relabel_nodes to only change the node labels, while maintaining all graph/node/edge attributes.
networkx/networkx
diff --git a/networkx/tests/test_relabel.py b/networkx/tests/test_relabel.py index 682de98a0..65c29eeab 100644 --- a/networkx/tests/test_relabel.py +++ b/networkx/tests/test_relabel.py @@ -150,6 +150,17 @@ class TestRelabel(): mapping={0:'aardvark'} G=relabel_nodes(G,mapping,copy=False) + def test_relabel_copy_name(self): + G=Graph() + H = relabel_nodes(G, {}, copy=True) + assert_equal(H.graph, G.graph) + H = relabel_nodes(G, {}, copy=False) + assert_equal(H.graph, G.graph) + G.name = "first" + H = relabel_nodes(G, {}, copy=True) + assert_equal(H.graph, G.graph) + H = relabel_nodes(G, {}, copy=False) + assert_equal(H.graph, G.graph) def test_relabel_toposort(self): K5=nx.complete_graph(4)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
help
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libgdal-dev graphviz" ], "python": "3.6", "reqs_path": [ "requirements/default.txt", "requirements/test.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 decorator==5.1.1 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/networkx/networkx.git@5aefafab2f05b97b150c6bf681c21ba6465c8d10#egg=networkx nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: networkx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - decorator==5.1.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/networkx
[ "networkx/tests/test_relabel.py::TestRelabel::test_relabel_copy_name" ]
[ "networkx/tests/test_relabel.py::test" ]
[ "networkx/tests/test_relabel.py::TestRelabel::test_convert_node_labels_to_integers", "networkx/tests/test_relabel.py::TestRelabel::test_convert_to_integers2", "networkx/tests/test_relabel.py::TestRelabel::test_convert_to_integers_raise", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_copy", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_function", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_graph", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_digraph", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_multigraph", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_multidigraph", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_isolated_nodes_to_same", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_nodes_missing", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_toposort", "networkx/tests/test_relabel.py::TestRelabel::test_relabel_selfloop" ]
[]
BSD 3-Clause
549
jubatus__jubatus-python-client-69
34f9f83ee2d230672518102e541286425c92c287
2016-05-19 05:04:03
ecbdecb8eb9ee40694ee39c4bf1de7e7fd984ae5
diff --git a/jubatus/common/client.py b/jubatus/common/client.py index d599319..9cd91a8 100644 --- a/jubatus/common/client.py +++ b/jubatus/common/client.py @@ -54,6 +54,10 @@ class ClientBase(object): (`unpack_encoding=None`) """ def __init__(self, host, port, name, timeout=10): + check_types(host, string_types) + check_types(port, int_types) + check_types(name, string_types) + check_types(timeout, int_types) address = msgpackrpc.Address(host, port) self.client = msgpackrpc.Client(address, timeout=timeout, pack_encoding='utf-8', unpack_encoding=None) self.jubatus_client = Client(self.client, name) @@ -65,6 +69,7 @@ class ClientBase(object): return self.jubatus_client.name def set_name(self, name): + check_types(name, string_types) self.jubatus_client.name = name def save(self, id):
no type validation for constructor arguments Currently argument types are validated, but constructor arguments are not. For example, the following code: ``` c = jubatus.Classifier("localhost", 9199, 0) # it should be ("localhost", 9199, "") to work c.get_status() ``` raises "TypeMismatch (error 2)" on RPC call, which is difficult to understand.
jubatus/jubatus-python-client
diff --git a/test/jubatus_test/common/test_client.py b/test/jubatus_test/common/test_client.py index 0e929f8..065b538 100644 --- a/test/jubatus_test/common/test_client.py +++ b/test/jubatus_test/common/test_client.py @@ -67,5 +67,22 @@ class ClientTest(unittest.TestCase): self.assertEqual("test", c.call("test", [], AnyType(), [])) self.assertRaises(TypeError, c.call, "test", [1], AnyType(), []) +class ClientBaseTest(unittest.TestCase): + def test_constructor(self): + self.assertIsInstance(jubatus.common.ClientBase("127.0.0.1", 9199, "cluster", 10), jubatus.common.ClientBase) + + # invalid host + self.assertRaises(TypeError, jubatus.common.ClientBase, 127001, 9199, "cluster", 10) + + # invalid port + self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", "9199", "cluster", 10) + + # invalid name + self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", 9199, 10, 10) + + # invalid timeout + self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", 9199, "cluster", "test") + self.assertRaises(TypeError, jubatus.common.ClientBase, "127.0.0.1", 9199, "cluster", 1.5) + if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/jubatus/jubatus-python-client.git@34f9f83ee2d230672518102e541286425c92c287#egg=jubatus msgpack-python==0.5.6 msgpack-rpc-python==0.4.1 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==4.5.3
name: jubatus-python-client channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - msgpack-python==0.5.6 - msgpack-rpc-python==0.4.1 - tornado==4.5.3 prefix: /opt/conda/envs/jubatus-python-client
[ "test/jubatus_test/common/test_client.py::ClientBaseTest::test_constructor" ]
[]
[ "test/jubatus_test/common/test_client.py::ClientTest::test_remote_error", "test/jubatus_test/common/test_client.py::ClientTest::test_type_mismatch", "test/jubatus_test/common/test_client.py::ClientTest::test_unknown_method", "test/jubatus_test/common/test_client.py::ClientTest::test_wrong_number_of_arguments" ]
[]
MIT License
550
html5lib__html5lib-python-256
66a2f7763f2dda24d3d2681c22bf799c94ee049c
2016-05-22 03:13:22
563dc298ea43021f9a9306fc7da3734ea5d9d8ec
gsnedders: fixes #228 landscape-bot: [![Code Health](https://landscape.io/badge/381520/landscape.svg?style=flat)](https://landscape.io/diff/354583) Code quality remained the same when pulling **[2f1d040](https://github.com/gsnedders/html5lib-python/commit/2f1d04073f63e7633b8fa2204e7dac221051c7fe) on gsnedders:lxml_treewalker_lxml_tree** into **[5288737](https://github.com/html5lib/html5lib-python/commit/5288737aebcae1fcf25a640c79241f6fb14475a2) on html5lib:master**. codecov-io: ## [Current coverage][cc-pull] is **90.83%** > Merging [#256][cc-pull] into [master][cc-base-branch] will increase coverage by **<.01%** ```diff @@ master #256 diff @@ ========================================== Files 51 51 Lines 6821 6835 +14 Methods 0 0 Messages 0 0 Branches 1313 1312 -1 ========================================== + Hits 6193 6208 +15 Misses 468 468 + Partials 160 159 -1 ``` > Powered by [Codecov](https://codecov.io?src=pr). Last updated by [5288737...2f1d040][cc-compare] [cc-base-branch]: https://codecov.io/gh/html5lib/html5lib-python/branch/master?src=pr [cc-compare]: https://codecov.io/gh/html5lib/html5lib-python/compare/5288737aebcae1fcf25a640c79241f6fb14475a2...2f1d04073f63e7633b8fa2204e7dac221051c7fe [cc-pull]: https://codecov.io/gh/html5lib/html5lib-python/pull/256?src=pr landscape-bot: [![Code Health](https://landscape.io/badge/385132/landscape.svg?style=flat)](https://landscape.io/diff/358204) Code quality remained the same when pulling **[a2ee6e6](https://github.com/gsnedders/html5lib-python/commit/a2ee6e6b0ec015a3a777546192d8af80074d60b0) on gsnedders:lxml_treewalker_lxml_tree** into **[66a2f77](https://github.com/html5lib/html5lib-python/commit/66a2f7763f2dda24d3d2681c22bf799c94ee049c) on html5lib:master**.
diff --git a/html5lib/treewalkers/lxmletree.py b/html5lib/treewalkers/lxmletree.py index 7d99adc..ff31a44 100644 --- a/html5lib/treewalkers/lxmletree.py +++ b/html5lib/treewalkers/lxmletree.py @@ -22,13 +22,20 @@ class Root(object): def __init__(self, et): self.elementtree = et self.children = [] - if et.docinfo.internalDTD: - self.children.append(Doctype(self, - ensure_str(et.docinfo.root_name), - ensure_str(et.docinfo.public_id), - ensure_str(et.docinfo.system_url))) - root = et.getroot() - node = root + + try: + if et.docinfo.internalDTD: + self.children.append(Doctype(self, + ensure_str(et.docinfo.root_name), + ensure_str(et.docinfo.public_id), + ensure_str(et.docinfo.system_url))) + except AttributeError: + pass + + try: + node = et.getroot() + except AttributeError: + node = et while node.getprevious() is not None: node = node.getprevious() @@ -118,12 +125,12 @@ class FragmentWrapper(object): class TreeWalker(_base.NonRecursiveTreeWalker): def __init__(self, tree): # pylint:disable=redefined-variable-type - if hasattr(tree, "getroot"): - self.fragmentChildren = set() - tree = Root(tree) - elif isinstance(tree, list): + if isinstance(tree, list): self.fragmentChildren = set(tree) tree = FragmentRoot(tree) + else: + self.fragmentChildren = set() + tree = Root(tree) _base.NonRecursiveTreeWalker.__init__(self, tree) self.filter = ihatexml.InfosetFilter()
AttributeError: 'TreeWalker' object has no attribute 'fragmentChildren' For some reason my `tree` (`lxml.etree._Element`) object has no attribute getroot and is not a list so there is no `fragmentChildren` attribute on `TreeWalker`: 270a2ca14fafc989f8f1bd4f79db2f4bd9f4d1fc lxml 3.5.0 html5lib-python f796cca5f9ddaaf1e1a8b872f68455551cd3ae2d
html5lib/html5lib-python
diff --git a/html5lib/tests/test_treewalkers.py b/html5lib/tests/test_treewalkers.py index 332027a..81ed277 100644 --- a/html5lib/tests/test_treewalkers.py +++ b/html5lib/tests/test_treewalkers.py @@ -2,6 +2,11 @@ from __future__ import absolute_import, division, unicode_literals import pytest +try: + import lxml.etree +except ImportError: + pass + from .support import treeTypes from html5lib import html5parser, treewalkers @@ -93,3 +98,19 @@ def test_treewalker_six_mix(): for tree in sorted(treeTypes.items()): for intext, attrs, expected in sm_tests: yield runTreewalkerEditTest, intext, expected, attrs, tree + + [email protected](treeTypes["lxml"] is None, reason="lxml not importable") +def test_lxml_xml(): + expected = [ + {'data': {}, 'name': 'div', 'namespace': None, 'type': 'StartTag'}, + {'data': {}, 'name': 'div', 'namespace': None, 'type': 'StartTag'}, + {'name': 'div', 'namespace': None, 'type': 'EndTag'}, + {'name': 'div', 'namespace': None, 'type': 'EndTag'} + ] + + lxmltree = lxml.etree.fromstring('<div><div></div></div>') + walker = treewalkers.getTreeWalker('lxml') + output = Lint(walker(lxmltree)) + + assert list(output) == expected
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
1.08
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock" ], "pre_install": [ "git submodule update --init --recursive" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
chardet==5.2.0 datrie==0.8.2 exceptiongroup==1.2.2 Genshi==0.7.9 -e git+https://github.com/html5lib/html5lib-python.git@66a2f7763f2dda24d3d2681c22bf799c94ee049c#egg=html5lib iniconfig==2.1.0 lxml==5.3.1 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 six==1.17.0 tomli==2.2.1 webencodings==0.5.1
name: html5lib-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - chardet==5.2.0 - datrie==0.8.2 - exceptiongroup==1.2.2 - genshi==0.7.9 - iniconfig==2.1.0 - lxml==5.3.1 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 - webencodings==0.5.1 prefix: /opt/conda/envs/html5lib-python
[ "html5lib/tests/test_treewalkers.py::test_lxml_xml" ]
[]
[ "html5lib/tests/test_treewalkers.py::test_all_tokens" ]
[]
MIT License
551
sympy__sympy-11149
db73ed37b955474ad9f1b3d2c5c762e32ce2cbfe
2016-05-23 10:00:09
8bb5814067cfa0348fb8b708848f35dba2b55ff4
diff --git a/sympy/sets/fancysets.py b/sympy/sets/fancysets.py index d819ea4f59..430a2294b1 100644 --- a/sympy/sets/fancysets.py +++ b/sympy/sets/fancysets.py @@ -552,8 +552,12 @@ def _intersect(self, other): if not all(i.is_number for i in other.args[:2]): return + # In case of null Range, return an EmptySet. + if self.size == 0: + return S.EmptySet + # trim down to self's size, and represent - # as a Range with step 1 + # as a Range with step 1. start = ceiling(max(other.inf, self.inf)) if start not in other: start += 1
Incorrect result for Intersection of S.Integers( and S.Naturals) with Interval ```python In []: Intersection(S.Integers, Interval(0.2, 0.8)) # results in a NotImplementedError In []: Intersection(S.Naturals, Interval(0.2, 0.8)) # results in a NotImplementedError ``` The correct intersection should be an `EmptySet`.
sympy/sympy
diff --git a/sympy/sets/tests/test_fancysets.py b/sympy/sets/tests/test_fancysets.py index ebee5c5668..d4e77e2748 100644 --- a/sympy/sets/tests/test_fancysets.py +++ b/sympy/sets/tests/test_fancysets.py @@ -314,6 +314,10 @@ def test_range_interval_intersection(): assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3) assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet + # Null Range intersections + assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet + assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet + def test_Integers_eval_imageset(): ans = ImageSet(Lambda(x, 2*x + S(3)/7), S.Integers)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mpmath>=0.19", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi exceptiongroup==1.2.2 importlib-metadata==6.7.0 iniconfig==2.0.0 mpmath==1.3.0 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 -e git+https://github.com/sympy/sympy.git@db73ed37b955474ad9f1b3d2c5c762e32ce2cbfe#egg=sympy tomli==2.0.1 typing_extensions==4.7.1 zipp==3.15.0
name: sympy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - mpmath==1.3.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - tomli==2.0.1 - typing-extensions==4.7.1 - zipp==3.15.0 prefix: /opt/conda/envs/sympy
[ "sympy/sets/tests/test_fancysets.py::test_range_interval_intersection" ]
[ "sympy/sets/tests/test_fancysets.py::test_halfcircle" ]
[ "sympy/sets/tests/test_fancysets.py::test_naturals", "sympy/sets/tests/test_fancysets.py::test_naturals0", "sympy/sets/tests/test_fancysets.py::test_integers", "sympy/sets/tests/test_fancysets.py::test_ImageSet", "sympy/sets/tests/test_fancysets.py::test_image_is_ImageSet", "sympy/sets/tests/test_fancysets.py::test_ImageSet_iterator_not_injective", "sympy/sets/tests/test_fancysets.py::test_inf_Range_len", "sympy/sets/tests/test_fancysets.py::test_Range_set", "sympy/sets/tests/test_fancysets.py::test_range_range_intersection", "sympy/sets/tests/test_fancysets.py::test_Integers_eval_imageset", "sympy/sets/tests/test_fancysets.py::test_Range_eval_imageset", "sympy/sets/tests/test_fancysets.py::test_fun", "sympy/sets/tests/test_fancysets.py::test_Reals", "sympy/sets/tests/test_fancysets.py::test_Complex", "sympy/sets/tests/test_fancysets.py::test_intersections", "sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_1", "sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_2", "sympy/sets/tests/test_fancysets.py::test_imageset_intersect_real", "sympy/sets/tests/test_fancysets.py::test_infinitely_indexed_set_3", "sympy/sets/tests/test_fancysets.py::test_ImageSet_simplification", "sympy/sets/tests/test_fancysets.py::test_ImageSet_contains", "sympy/sets/tests/test_fancysets.py::test_ComplexRegion_contains", "sympy/sets/tests/test_fancysets.py::test_ComplexRegion_intersect", "sympy/sets/tests/test_fancysets.py::test_ComplexRegion_union", "sympy/sets/tests/test_fancysets.py::test_ComplexRegion_measure", "sympy/sets/tests/test_fancysets.py::test_normalize_theta_set", "sympy/sets/tests/test_fancysets.py::test_ComplexRegion_FiniteSet", "sympy/sets/tests/test_fancysets.py::test_union_RealSubSet", "sympy/sets/tests/test_fancysets.py::test_issue_9980" ]
[]
BSD
552
pre-commit__pre-commit-376
6654fee5f9c40b4483f30d44a5ccda70b238b3ce
2016-05-25 15:45:51
f11338ccfa612e36a6c1f2dc688080ec08fd66b0
diff --git a/pre_commit/git.py b/pre_commit/git.py index 796a0b8..1f16b6e 100644 --- a/pre_commit/git.py +++ b/pre_commit/git.py @@ -69,7 +69,11 @@ def get_conflicted_files(): @memoize_by_cwd def get_staged_files(): - return cmd_output('git', 'diff', '--staged', '--name-only')[1].splitlines() + return cmd_output( + 'git', 'diff', '--staged', '--name-only', + # Everything except for D + '--diff-filter=ACMRTUXB' + )[1].splitlines() @memoize_by_cwd
Newly gitignored (but file still exists) files are linted (they should not be)
pre-commit/pre-commit
diff --git a/tests/git_test.py b/tests/git_test.py index c4e0145..701d36b 100644 --- a/tests/git_test.py +++ b/tests/git_test.py @@ -33,6 +33,16 @@ def test_get_root_not_git_dir(tempdir_factory): git.get_root() +def test_get_staged_files_deleted(tempdir_factory): + path = git_dir(tempdir_factory) + with cwd(path): + open('test', 'a').close() + cmd_output('git', 'add', 'test') + cmd_output('git', 'commit', '-m', 'foo', '--allow-empty') + cmd_output('git', 'rm', '--cached', 'test') + assert git.get_staged_files() == [] + + def test_is_not_in_merge_conflict(tempdir_factory): path = git_dir(tempdir_factory) with cwd(path):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 attrs==25.3.0 cached-property==2.0.1 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 flake8==7.2.0 iniconfig==2.1.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 mccabe==0.7.0 mock==5.2.0 nodeenv==1.9.1 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 -e git+https://github.com/pre-commit/pre-commit.git@6654fee5f9c40b4483f30d44a5ccda70b238b3ce#egg=pre_commit pycodestyle==2.13.0 pyflakes==3.3.1 pyterminalsize==0.1.0 pytest==8.3.5 PyYAML==6.0.2 referencing==0.36.2 rpds-py==0.24.0 tomli==2.2.1 typing_extensions==4.13.0 virtualenv==20.29.3
name: pre-commit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aspy-yaml==1.3.0 - attrs==25.3.0 - cached-property==2.0.1 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - flake8==7.2.0 - iniconfig==2.1.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - mccabe==0.7.0 - mock==5.2.0 - nodeenv==1.9.1 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pyterminalsize==0.1.0 - pytest==8.3.5 - pyyaml==6.0.2 - referencing==0.36.2 - rpds-py==0.24.0 - setuptools==18.4 - tomli==2.2.1 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/pre-commit
[ "tests/git_test.py::test_get_staged_files_deleted" ]
[]
[ "tests/git_test.py::test_get_root_at_root", "tests/git_test.py::test_get_root_deeper", "tests/git_test.py::test_get_root_not_git_dir", "tests/git_test.py::test_is_not_in_merge_conflict", "tests/git_test.py::test_get_files_matching_base", "tests/git_test.py::test_get_files_matching_total_match", "tests/git_test.py::test_does_search_instead_of_match", "tests/git_test.py::test_does_not_include_deleted_fileS", "tests/git_test.py::test_exclude_removes_files", "tests/git_test.py::test_parse_merge_msg_for_conflicts[Merge" ]
[]
MIT License
553
Duke-GCB__DukeDSClient-61
81d8fc03fdbb9209d949f319bf4b4691b1615a59
2016-05-25 18:51:33
d43333d5372a8115eaaba0a68991a696124bf837
diff --git a/ddsc/core/filedownloader.py b/ddsc/core/filedownloader.py index 5049aac..e8ab7f5 100644 --- a/ddsc/core/filedownloader.py +++ b/ddsc/core/filedownloader.py @@ -106,8 +106,9 @@ class FileDownloader(object): Write out a empty file so the workers can seek to where they should write and write their data. """ with open(self.path, "wb") as outfile: - outfile.seek(int(self.file_size) - 1) - outfile.write(b'\0') + if self.file_size > 0: + outfile.seek(int(self.file_size) - 1) + outfile.write(b'\0') def make_and_start_process(self, range_start, range_end, progress_queue): """ diff --git a/ddsc/core/fileuploader.py b/ddsc/core/fileuploader.py index 43356c5..4b57b61 100644 --- a/ddsc/core/fileuploader.py +++ b/ddsc/core/fileuploader.py @@ -181,12 +181,14 @@ class ParallelChunkProcessor(object): processes.append(self.make_and_start_process(index, num_items, progress_queue)) wait_for_processes(processes, num_chunks, progress_queue, self.watcher, self.local_file) - @staticmethod def determine_num_chunks(chunk_size, file_size): """ Figure out how many pieces we are sending the file in. + NOTE: duke-data-service requires an empty chunk to be uploaded for empty files. """ + if file_size == 0: + return 1 return int(math.ceil(float(file_size) / float(chunk_size))) @staticmethod diff --git a/ddsc/tests/empty_file b/ddsc/tests/empty_file new file mode 100644 index 0000000..e69de29 diff --git a/setup.py b/setup.py index 8fee84a..2fe9f5b 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import setup setup(name='DukeDSClient', - version='0.2.8', + version='0.2.9', description='Command line tool(ddsclient) to upload/manage projects on the duke-data-service.', url='https://github.com/Duke-GCB/DukeDSClient', keywords='duke dds dukedataservice',
“range() step argument must not be zero” Crash at approx. 30% completion, uploading a folder to a new project: “range() step argument must not be zero” <img width="806" alt="screen shot 2016-05-25 at 1 31 11 pm" src="https://cloud.githubusercontent.com/assets/11540881/15551266/38d08f16-2283-11e6-9708-c5f93edb99d9.png"> Is there a verbose logging option we can use to determine where, exactly, this is failing?
Duke-GCB/DukeDSClient
diff --git a/ddsc/core/tests/test_fileuploader.py b/ddsc/core/tests/test_fileuploader.py index f8ca72b..44bfb7e 100644 --- a/ddsc/core/tests/test_fileuploader.py +++ b/ddsc/core/tests/test_fileuploader.py @@ -47,6 +47,7 @@ class TestParallelChunkProcessor(TestCase): (100, 900000, 9000), (125, 123, 1), (122, 123, 2), + (100, 0, 1) ] for chunk_size, file_size, expected in values: num_chunks = ParallelChunkProcessor.determine_num_chunks(chunk_size, file_size) @@ -63,4 +64,4 @@ class TestParallelChunkProcessor(TestCase): ] for upload_workers, num_chunks, expected in values: result = ParallelChunkProcessor.make_work_parcels(upload_workers, num_chunks) - self.assertEqual(expected, result) \ No newline at end of file + self.assertEqual(expected, result)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 3 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/Duke-GCB/DukeDSClient.git@81d8fc03fdbb9209d949f319bf4b4691b1615a59#egg=DukeDSClient exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 PyYAML==3.11 requests==2.9.1 tomli==2.2.1
name: DukeDSClient channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pyyaml==3.11 - requests==2.9.1 - tomli==2.2.1 prefix: /opt/conda/envs/DukeDSClient
[ "ddsc/core/tests/test_fileuploader.py::TestParallelChunkProcessor::test_determine_num_chunks" ]
[]
[ "ddsc/core/tests/test_fileuploader.py::TestFileUploader::test_make_chunk_processor_with_none", "ddsc/core/tests/test_fileuploader.py::TestFileUploader::test_make_chunk_processor_with_one", "ddsc/core/tests/test_fileuploader.py::TestFileUploader::test_make_chunk_processor_with_two", "ddsc/core/tests/test_fileuploader.py::TestParallelChunkProcessor::test_make_work_parcels" ]
[]
MIT License
554
zalando-stups__pierone-cli-33
903f8e27f3e084fd9116929139a1ccd7f700f42f
2016-05-26 16:17:11
560cae1b4fc185c7a8aa3a1a50e0a96b2c7dd8e7
diff --git a/.gitignore b/.gitignore index 1e365e8..e60d986 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ htmlcov/ virtualenv *.sw* .cache/ +.tox/ diff --git a/pierone/cli.py b/pierone/cli.py index 467ff32..1af5790 100644 --- a/pierone/cli.py +++ b/pierone/cli.py @@ -1,20 +1,18 @@ import datetime import os import re - -import click - -import requests import tarfile import tempfile import time -import zign.api -from clickclick import error, AliasedGroup, print_table, OutputFormat, UrlType -from .api import docker_login, request, get_latest_tag, DockerImage +import click import pierone +import requests import stups_cli.config +import zign.api +from clickclick import AliasedGroup, OutputFormat, UrlType, error, print_table +from .api import DockerImage, docker_login, get_latest_tag, request KEYRING_KEY = 'pierone' @@ -24,6 +22,48 @@ output_option = click.option('-o', '--output', type=click.Choice(['text', 'json' help='Use alternative output format') url_option = click.option('--url', help='Pier One URL', metavar='URI') +clair_url_option = click.option('--clair-url', help='Clair URL', metavar='CLAIR_URI') + +CVE_STYLES = { + 'TOO_OLD': { + 'bold': True, + 'fg': 'red' + }, + 'NOT_PROCESSED_YET': { + 'bold': True, + 'fg': 'red' + }, + 'COULDNT_FIGURE_OUT': { + 'bold': True, + 'fg': 'red' + }, + 'CRITICAL': { + 'bold': True, + 'fg': 'red' + }, + 'HIGH': { + 'bold': True, + 'fg': 'red' + }, + 'MEDIUM': { + 'fg': 'yellow' + }, + 'LOW': { + 'fg': 'yellow' + }, + 'NEGLIGIBLE': { + 'fg': 'yellow' + }, + 'UNKNOWN': { + 'fg': 'yellow' + }, + 'PENDING': { + 'fg': 'yellow' + }, + 'NO_CVES_FOUND': { + 'fg': 'green' + } +} TEAM_PATTERN_STR = r'[a-z][a-z0-9-]+' TEAM_PATTERN = re.compile(r'^{}$'.format(TEAM_PATTERN_STR)) @@ -54,6 +94,19 @@ def parse_time(s: str) -> float: return None +def parse_severity(value, clair_id_exists): + '''Parse severity values to displayable values''' + if value is None and clair_id_exists: + return 'NOT_PROCESSED_YET' + elif value is None: + return 'TOO_OLD' + + value = re.sub('^clair:', '', value) + value = re.sub('(?P<upper_letter>(?<=[a-z])[A-Z])', '_\g<upper_letter>', value) + + return value.upper() + + def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return @@ -82,6 +135,28 @@ def set_pierone_url(config: dict, url: str) -> None: return url +def set_clair_url(config: dict, url: str) -> None: + '''Read Clair URL from cli, from config file or from stdin.''' + url = url or config.get('clair_url') + + while not url: + url = click.prompt('Please enter the Clair URL', type=UrlType()) + + try: + requests.get(url, timeout=5) + except: + error('Could not reach {}'.format(url)) + url = None + + if '://' not in url: + # issue 63: gracefully handle URLs without scheme + url = 'https://{}'.format(url) + + config['clair_url'] = url + stups_cli.config.store_config(config, 'pierone') + return url + + @click.group(cls=AliasedGroup, context_settings=CONTEXT_SETTINGS) @click.option('-V', '--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True, help='Print the current version number and exit.') @@ -147,6 +222,19 @@ def get_tags(url, team, art, access_token): return r.json() +def get_clair_features(url, layer_id, access_token): + if layer_id is None: + return [] + + r = request(url, '/v1/layers/{}?vulnerabilities&features'.format(layer_id), access_token) + if r.status_code == 404: + # empty list of tags (layer does not exist) + return [] + else: + r.raise_for_status() + return r.json()['Layer']['Features'] + + @cli.command() @click.argument('team', callback=validate_team) @url_option @@ -184,14 +272,69 @@ def tags(config, team: str, artifact, url, output): 'artifact': art, 'tag': row['name'], 'created_by': row['created_by'], - 'created_time': parse_time(row['created'])} + 'created_time': parse_time(row['created']), + 'severity_fix_available': parse_severity( + row.get('severity_fix_available'), row.get('clair_id', False)), + 'severity_no_fix_available': parse_severity( + row.get('severity_no_fix_available'), row.get('clair_id', False))} for row in r]) # sorts are guaranteed to be stable, i.e. tags will be sorted by time (as returned from REST service) rows.sort(key=lambda row: (row['team'], row['artifact'])) with OutputFormat(output): - print_table(['team', 'artifact', 'tag', 'created_time', 'created_by'], rows, - titles={'created_time': 'Created', 'created_by': 'By'}) + titles = { + 'created_time': 'Created', + 'created_by': 'By', + 'severity_fix_available': 'Fixable CVE Severity', + 'severity_no_fix_available': 'Unfixable CVE Severity' + } + print_table(['team', 'artifact', 'tag', 'created_time', 'created_by', + 'severity_fix_available', 'severity_no_fix_available'], + rows, titles=titles, styles=CVE_STYLES) + + [email protected]() [email protected]('team', callback=validate_team) [email protected]('artifact') [email protected]('tag') +@url_option +@clair_url_option +@output_option [email protected]_obj +def cves(config, team, artifact, tag, url, clair_url, output): + '''List all CVE's found by Clair service for a specific artifact tag''' + set_pierone_url(config, url) + set_clair_url(config, clair_url) + + rows = [] + token = get_token() + for artifact_tag in get_tags(config.get('url'), team, artifact, token): + if artifact_tag['name'] == tag: + installed_software = get_clair_features(config.get('clair_url'), artifact_tag.get('clair_id'), token) + for software_pkg in installed_software: + for cve in software_pkg.get('Vulnerabilities', []): + rows.append({ + 'cve': cve['Name'], + 'severity': cve['Severity'].upper(), + 'affected_feature': '{}:{}'.format(software_pkg['Name'], + software_pkg['Version']), + 'fixing_feature': cve.get( + 'FixedBy') and '{}:{}'.format(software_pkg['Name'], + cve['FixedBy']), + 'link': cve['Link'], + }) + severity_rating = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'NEGLIGIBLE', 'UNKNOWN', 'PENDING'] + rows.sort(key=lambda row: severity_rating.index(row['severity'])) + with OutputFormat(output): + titles = { + 'cve': 'CVE', + 'severity': 'Severity', + 'affected_feature': 'Affected Feature', + 'fixing_feature': 'Fixing Feature', + 'link': 'Link' + } + print_table(['cve', 'severity', 'affected_feature', 'fixing_feature', 'link'], + rows, titles=titles, styles=CVE_STYLES) @cli.command() diff --git a/tox.ini b/tox.ini index aa079ec..4644fe1 100644 --- a/tox.ini +++ b/tox.ini @@ -1,2 +1,8 @@ [flake8] max-line-length=120 + +[tox] +envlist=py34,py35 + +[testenv] +commands=python setup.py test
Display Clair security information. PierOne now supports Clair for vulnerability scanning. Pierone now exposes the following three information for each tag: - clair_id - severity_fix_available - severity_no_fix_available The PierOne CLI should now also enhance the `tags` subcommand with these information and provide a new `cves` subcommand to display full CVE reports. $ pierone tags foo bar Team | Artifact | Tag | Created | By | Fixable CVE Severity | Unfixable CVE Severity | --------|-----------|-------|------------|-----|-----------------------|-------------------------- foo | bar | 1.0 | 5d ago | example | **Critical** | Medium | foo | bar | 1.1 | 2d ago | example | **Critical** | Medium | foo | bar | 2.0 | 1d ago | example | None | Medium | `High` and `Critical` severities should be highlighted. $ pierone cves foo bar 1.0 CVE | Severity | Affected Feature | Fixing Feature | Link -------|------------|------------------------|---------------------|------- CVE-2014-9471 | Low | coreutils:8.23-4 | coreutils:9.23-5 | https://security-tracker.debian.org/tracker/CVE-2014-9471 Again, `High` and `Critical` needs to be highlighted and the whole table should be sorted by severity. PierOne source contains an ordered list of possible values. The information for this output can be retrieved via the [Clair API](https://github.com/coreos/clair/blob/master/api/v1/README.md#get-layersname) using the PierOne provided Clair ID. For this, the PierOne CLI will need to learn about the Clair API's endpoint.
zalando-stups/pierone-cli
diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 diff --git a/tests/fixtures/clair_response.json b/tests/fixtures/clair_response.json new file mode 100644 index 0000000..2638daa --- /dev/null +++ b/tests/fixtures/clair_response.json @@ -0,0 +1,70 @@ +{ + "Layer": { + "Name": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "NamespaceName": "ubuntu:16.04", + "ParentName": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "IndexedByVersion": 2, + "Features": [ + { + "Name": "python3.5", + "NamespaceName": "ubuntu:16.04", + "Version": "3.5.1-10", + "AddedBy": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + { + "Name": "python-pip", + "NamespaceName": "ubuntu:16.04", + "Version": "8.1.1-2", + "Vulnerabilities": [ + { + "Name": "CVE-2013-5123", + "NamespaceName": "ubuntu:16.04", + "Description": "The mirroring support (-M, --use-mirrors) was implemented without any sort of authenticity checks and is downloaded over plaintext HTTP. Further more by default it will dynamically discover the list of available mirrors by querying a DNS entry and extrapolating from that data. It does not attempt to use any sort of method of securing this querying of the DNS like DNSSEC. Software packages are downloaded over these insecure links, unpacked, and then typically the setup.py python file inside of them is executed.", + "Link": "http://people.ubuntu.com/~ubuntu-security/cve/CVE-2013-5123", + "Severity": "Medium" + }, + { + "Name": "CVE-2014-8991", + "NamespaceName": "ubuntu:16.04", + "Description": "pip 1.3 through 1.5.6 allows local users to cause a denial of service (prevention of package installation) by creating a /tmp/pip-build-* file for another user.", + "Link": "http://people.ubuntu.com/~ubuntu-security/cve/CVE-2014-8991", + "Severity": "Low", + "Metadata": { + "NVD": { + "CVSSv2": { + "Score": 2.1, + "Vectors": "AV:L/AC:L/Au:N/C:N/I:N" + } + } + } + } + ], + "AddedBy": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + }, + { + "Name": "openssl", + "NamespaceName": "ubuntu:16.04", + "Version": "1.0.2g-1ubuntu4", + "Vulnerabilities": [ + { + "Name": "CVE-2016-2108", + "NamespaceName": "ubuntu:16.04", + "Description": "The ASN.1 implementation in OpenSSL before 1.0.1o and 1.0.2 before 1.0.2c allows remote attackers to execute arbitrary code or cause a denial of service (buffer underflow and memory corruption) via an ANY field in crafted serialized data, aka the \"negative zero\" issue.", + "Link": "http://people.ubuntu.com/~ubuntu-security/cve/CVE-2016-2108", + "Severity": "High", + "Metadata": { + "NVD": { + "CVSSv2": { + "Score": 10, + "Vectors": "AV:N/AC:L/Au:N/C:C/I:C" + } + } + }, + "FixedBy": "1.0.2g-1ubuntu4.1" + } + ], + "AddedBy": "sha256:0000000000000000000000000000000000000000000000000000000000000000" + } + ] + } +} diff --git a/tests/test_api.py b/tests/test_api.py index 5cb2fc7..3548e01 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,9 +1,11 @@ import json import os from unittest.mock import MagicMock -import yaml -from pierone.api import docker_login, DockerImage, get_latest_tag, Unauthorized, image_exists + import pytest +import yaml +from pierone.api import (DockerImage, Unauthorized, docker_login, + get_latest_tag, image_exists) def test_docker_login(monkeypatch, tmpdir): @@ -12,22 +14,22 @@ def test_docker_login(monkeypatch, tmpdir): response.status_code = 200 response.json.return_value = {'access_token': '12377'} monkeypatch.setattr('requests.get', MagicMock(return_value=response)) - token = docker_login('https://pierone.example.org', 'services', 'mytok', - 'myuser', 'mypass', 'https://token.example.org', use_keyring=False) + docker_login('https://pierone.example.org', 'services', 'mytok', + 'myuser', 'mypass', 'https://token.example.org', use_keyring=False) path = os.path.expanduser('~/.docker/config.json') with open(path) as fd: data = yaml.safe_load(fd) - assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org') + assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org') def test_docker_login_service_token(monkeypatch, tmpdir): monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir))) monkeypatch.setattr('tokens.get', lambda x: '12377') - token = docker_login('https://pierone.example.org', None, 'mytok', 'myuser', 'mypass', 'https://token.example.org') + docker_login('https://pierone.example.org', None, 'mytok', 'myuser', 'mypass', 'https://token.example.org') path = os.path.expanduser('~/.docker/config.json') with open(path) as fd: data = yaml.safe_load(fd) - assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org') + assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org') def test_keep_dockercfg_entries(monkeypatch, tmpdir): @@ -49,12 +51,12 @@ def test_keep_dockercfg_entries(monkeypatch, tmpdir): with open(path, 'w') as fd: json.dump(existing_data, fd) - token = docker_login('https://pierone.example.org', 'services', 'mytok', - 'myuser', 'mypass', 'https://token.example.org', use_keyring=False) + docker_login('https://pierone.example.org', 'services', 'mytok', + 'myuser', 'mypass', 'https://token.example.org', use_keyring=False) with open(path) as fd: data = yaml.safe_load(fd) - assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths', {}).get('https://pierone.example.org') - assert existing_data.get(key) == data.get(key) + assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths', {}).get('https://pierone.example.org') + assert existing_data.get(key) == data.get(key) def test_get_latest_tag(monkeypatch): diff --git a/tests/test_cli.py b/tests/test_cli.py index 6f58d15..6282253 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,9 +1,9 @@ import json import os -from click.testing import CliRunner +import re from unittest.mock import MagicMock -import yaml -import zign.api + +from click.testing import CliRunner from pierone.cli import cli @@ -40,6 +40,7 @@ def test_login_given_url_option(monkeypatch, tmpdir): runner = CliRunner() config = {} + def store(data, section): config.update(**data) @@ -50,9 +51,9 @@ def test_login_given_url_option(monkeypatch, tmpdir): monkeypatch.setattr('requests.get', lambda x, timeout: response) with runner.isolated_filesystem(): - result = runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n') + runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n') assert config == {'url': 'https://pieroneurl'} - result = runner.invoke(cli, ['login', '--url', 'someotherregistry'], catch_exceptions=False) + runner.invoke(cli, ['login', '--url', 'someotherregistry'], catch_exceptions=False) with open(os.path.join(str(tmpdir), '.docker/config.json')) as fd: data = json.load(fd) assert data['auths']['https://pieroneurl']['auth'] == 'b2F1dGgyOnRvazEyMw==' @@ -65,7 +66,7 @@ def test_scm_source(monkeypatch, tmpdir): response.json.return_value = {'url': 'git:somerepo', 'revision': 'myrev123'} runner = CliRunner() - monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url':'foobar'}) + monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar'}) monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123')) monkeypatch.setattr('pierone.cli.get_tags', MagicMock(return_value={})) monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir))) @@ -75,12 +76,13 @@ def test_scm_source(monkeypatch, tmpdir): assert 'myrev123' in result.output assert 'git:somerepo' in result.output + def test_image(monkeypatch, tmpdir): response = MagicMock() response.json.return_value = [{'name': '1.0', 'team': 'stups', 'artifact': 'kio'}] runner = CliRunner() - monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url':'foobar'}) + monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar'}) monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123')) monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir))) monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response)) @@ -93,16 +95,130 @@ def test_image(monkeypatch, tmpdir): def test_tags(monkeypatch, tmpdir): response = MagicMock() - response.json.return_value = [{'name': '1.0', 'created_by': 'myuser', 'created': '2015-08-20T08:14:59.432Z'}] + response.json.return_value = [ + # Former pierone payload + { + 'name': '1.0', + 'created_by': 'myuser', + 'created': '2015-08-20T08:14:59.432Z' + }, + # New pierone payload with clair but no information about CVEs -- old images + { + "name": "1.1", + "created": "2016-05-19T15:23:41.065Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": None, + "severity_fix_available": None, + "severity_no_fix_available": None + }, + # New pierone payload with clair but no information about CVEs -- still processing + { + "name": "1.1", + "created": "2016-05-19T15:23:41.065Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": "sha256:here", + "severity_fix_available": None, + "severity_no_fix_available": None + }, + # New pierone payload with clair but could not figure out + { + "name": "1.1", + "created": "2016-05-19T15:23:41.065Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": "sha256:here", + "severity_fix_available": "clair:CouldntFigureOut", + "severity_no_fix_available": "clair:CouldntFigureOut" + }, + # New pierone payload with clair with no CVEs found + { + "name": "1.1", + "created": "2016-05-19T15:23:41.065Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": "sha256:here", + "severity_fix_available": "clair:NoCVEsFound", + "severity_no_fix_available": "clair:NoCVEsFound" + }, + # New pierone payload with clair input and info about CVEs + { + "name": "1.2", + "created": "2016-05-23T13:29:17.753Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": "sha256:here", + "severity_fix_available": "High", + "severity_no_fix_available": "Medium" + } + ] runner = CliRunner() - monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url':'foobar'}) + monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar'}) monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123')) monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir))) monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response)) with runner.isolated_filesystem(): result = runner.invoke(cli, ['tags', 'myteam', 'myart'], catch_exceptions=False) assert '1.0' in result.output + assert 'Fixable CVE Severity' in result.output + assert 'Unfixable CVE Severity' in result.output + assert 'TOO_OLD' in result.output + assert 'NOT_PROCESSED_YET' in result.output + assert 'NO_CVES_FOUND' in result.output + assert re.search('HIGH\s+MEDIUM', result.output), 'Should how information about CVEs' + + +def test_cves(monkeypatch, tmpdir): + pierone_service_payload = [ + # Former pierone payload + { + 'name': '1.0', + 'created_by': 'myuser', + 'created': '2015-08-20T08:14:59.432Z' + }, + # New pierone payload with clair but no information about CVEs + { + "name": "1.1", + "created": "2016-05-19T15:23:41.065Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": None, + "severity_fix_available": None, + "severity_no_fix_available": None + }, + # New pierone payload with clair input and info about CVEs + { + "name": "1.2", + "created": "2016-05-23T13:29:17.753Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": "sha256:here", + "severity_fix_available": "High", + "severity_no_fix_available": "Medium" + } + ] + + with open(os.path.join(os.path.dirname(__file__), + 'fixtures', 'clair_response.json'), 'r') as fixture: + clair_service_payload = json.loads(fixture.read()) + + response = MagicMock() + response.json.side_effect = [ + pierone_service_payload, + clair_service_payload + ] + + runner = CliRunner() + monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar', 'clair_url': 'barfoo'}) + monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123')) + monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir))) + monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response)) + with runner.isolated_filesystem(): + result = runner.invoke(cli, ['cves', 'myteam', 'myart', '1.2'], catch_exceptions=False) + assert 'CVE-2013-5123' in result.output + assert re.match('[^\n]+\n[^\n]+HIGH', result.output), 'Results should be ordered by highest priority' def test_latest(monkeypatch, tmpdir):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 3 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 clickclick==20.10.2 coverage==7.8.0 dnspython==2.7.0 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 PyYAML==6.0.2 requests==2.32.3 stups-cli-support==1.1.22 -e git+https://github.com/zalando-stups/pierone-cli.git@903f8e27f3e084fd9116929139a1ccd7f700f42f#egg=stups_pierone stups-tokens==1.1.19 stups-zign==1.2 tomli==2.2.1 urllib3==2.3.0
name: pierone-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - clickclick==20.10.2 - coverage==7.8.0 - dnspython==2.7.0 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pyyaml==6.0.2 - requests==2.32.3 - stups-cli-support==1.1.22 - stups-tokens==1.1.19 - stups-zign==1.2 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/pierone-cli
[ "tests/test_cli.py::test_tags", "tests/test_cli.py::test_cves" ]
[ "tests/test_api.py::test_docker_login", "tests/test_api.py::test_keep_dockercfg_entries" ]
[ "tests/test_api.py::test_docker_login_service_token", "tests/test_api.py::test_get_latest_tag", "tests/test_api.py::test_get_latest_tag_IOException", "tests/test_api.py::test_get_latest_tag_non_json", "tests/test_api.py::test_unauthorized", "tests/test_api.py::test_image_exists", "tests/test_api.py::test_image_exists_IOException", "tests/test_api.py::test_image_exists_but_other_version", "tests/test_api.py::test_image_not_exists", "tests/test_cli.py::test_version", "tests/test_cli.py::test_login", "tests/test_cli.py::test_login_given_url_option", "tests/test_cli.py::test_scm_source", "tests/test_cli.py::test_image", "tests/test_cli.py::test_latest", "tests/test_cli.py::test_latest_not_found", "tests/test_cli.py::test_url_without_scheme" ]
[]
Apache License 2.0
555
craffel__mir_eval-195
f858df347c05c83159875e8f6de84f0041dbabca
2016-05-26 17:31:07
a4acbfad96db3241388c818534dc2bd08b48d188
bmcfee: @craffel @justinsalamon ready for CR I think. craffel: One minor comment otherwise LGTM.
diff --git a/mir_eval/sonify.py b/mir_eval/sonify.py index f614684..a40a0d0 100644 --- a/mir_eval/sonify.py +++ b/mir_eval/sonify.py @@ -5,6 +5,8 @@ All functions return a raw signal at the specified sampling rate. import numpy as np from numpy.lib.stride_tricks import as_strided +from scipy.interpolate import interp1d + from . import util from . import chord @@ -140,6 +142,59 @@ def time_frequency(gram, frequencies, times, fs, function=np.sin, length=None): return output +def pitch_contour(times, frequencies, fs, function=np.sin, length=None, + kind='linear'): + '''Sonify a pitch contour. + + Parameters + ---------- + times : np.ndarray + time indices for each frequency measurement, in seconds + + frequencies : np.ndarray + frequency measurements, in Hz. + Non-positive measurements will be interpreted as un-voiced samples. + + fs : int + desired sampling rate of the output signal + + function : function + function to use to synthesize notes, should be 2pi-periodic + + length : int + desired number of samples in the output signal, + defaults to ``max(times)*fs`` + + kind : str + Interpolation mode for the frequency estimator. + See: ``scipy.interpolate.interp1d`` for valid settings. + + Returns + ------- + output : np.ndarray + synthesized version of the pitch contour + ''' + + fs = float(fs) + + if length is None: + length = int(times.max() * fs) + + # Squash the negative frequencies. + # wave(0) = 0, so clipping here will un-voice the corresponding instants + frequencies = np.maximum(frequencies, 0.0) + + # Build a frequency interpolator + f_interp = interp1d(times * fs, 2 * np.pi * frequencies / fs, kind=kind, + fill_value=0.0, bounds_error=False, copy=False) + + # Estimate frequency at sample points + f_est = f_interp(np.arange(length)) + + # Sonify the waveform + return function(np.cumsum(f_est)) + + def chroma(chromagram, times, fs, **kwargs): """Reverse synthesis of a chromagram (semitone matrix)
continuous pitch sonification As per [this discussion](https://github.com/marl/jams/pull/91), we could pull in the code from @justinsalamon 's [melosynth](https://github.com/justinsalamon/melosynth) package.
craffel/mir_eval
diff --git a/tests/test_sonify.py b/tests/test_sonify.py index a1975c9..4d0d564 100644 --- a/tests/test_sonify.py +++ b/tests/test_sonify.py @@ -2,6 +2,7 @@ import mir_eval import numpy as np +import scipy def test_clicks(): @@ -53,3 +54,37 @@ def test_chords(): ['C', 'C:maj', 'D:min7', 'E:min', 'C#', 'C', 'C', 'C', 'C', 'C'], intervals, fs, length=fs*11) assert len(signal) == 11*fs + + +def test_pitch_contour(): + + # Generate some random pitch + fs = 8000 + times = np.linspace(0, 5, num=5 * fs, endpoint=True) + + noise = scipy.ndimage.gaussian_filter1d(np.random.randn(len(times)), + sigma=256) + freqs = 440.0 * 2.0**(16 * noise) + + # negate a bunch of sequences + idx = np.unique(np.random.randint(0, high=len(times), size=32)) + for start, end in zip(idx[::2], idx[1::2]): + freqs[start:end] *= -1 + + # Test with inferring duration + x = mir_eval.sonify.pitch_contour(times, freqs, fs) + assert len(x) == fs * 5 + + # Test with an explicit duration + # This forces the interpolator to go off the end of the sampling grid, + # which should result in a constant sequence in the output + x = mir_eval.sonify.pitch_contour(times, freqs, fs, length=fs * 7) + assert len(x) == fs * 7 + assert np.allclose(x[-fs * 2:], x[-fs * 2]) + + # Test with an explicit duration and a fixed offset + # This forces the interpolator to go off the beginning of + # the sampling grid, which should result in a constant output + x = mir_eval.sonify.pitch_contour(times + 5.0, freqs, fs, length=fs * 7) + assert len(x) == fs * 7 + assert np.allclose(x[:fs * 5], x[0])
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.7.0 scipy>=0.9.0 future six", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 future @ file:///croot/future_1730902796226/work iniconfig==2.1.0 -e git+https://github.com/craffel/mir_eval.git@f858df347c05c83159875e8f6de84f0041dbabca#egg=mir_eval nose==1.3.7 numpy @ file:///croot/numpy_and_numpy_base_1736283260865/work/dist/numpy-2.0.2-cp39-cp39-linux_x86_64.whl#sha256=3387e3e62932fa288bc18e8f445ce19e998b418a65ed2064dd40a054f976a6c7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 scipy @ file:///croot/scipy_1733756309941/work/dist/scipy-1.13.1-cp39-cp39-linux_x86_64.whl#sha256=3b247b926209f2d9f719ebae39faf3ff891b2596150ed8f8349adfc3eb19441c six @ file:///tmp/build/80754af9/six_1644875935023/work tomli==2.2.1
name: mir_eval channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=openblas - ca-certificates=2025.2.25=h06a4308_0 - future=1.0.0=py39h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - numpy=2.0.2=py39heeff2f4_0 - numpy-base=2.0.2=py39h8a23956_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - pybind11-abi=4=hd3eb1b0_1 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - scipy=1.13.1=py39heeff2f4_1 - setuptools=72.1.0=py39h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/mir_eval
[ "tests/test_sonify.py::test_pitch_contour" ]
[ "tests/test_sonify.py::test_clicks", "tests/test_sonify.py::test_chords" ]
[ "tests/test_sonify.py::test_time_frequency", "tests/test_sonify.py::test_chroma" ]
[]
MIT License
556
box__box-python-sdk-137
481a86227d6d063f2e4e4ae880f4e12cd16dab06
2016-05-26 20:10:25
ded623f4b6de0530d8f983d3c3d2cafe646c126b
boxcla: Verified that @jmoldow has signed the CLA. Thanks for the pull request! Jeff-Meadows: 👍
diff --git a/HISTORY.rst b/HISTORY.rst index e7ca71f..25def3f 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -6,7 +6,12 @@ Release History Upcoming ++++++++ -1.5.2 +1.5.3 +++++++++++++++++++ + +- Bugfix so that ``JWTAuth`` opens the PEM private key file in ``'rb'`` mode. + +1.5.2 (2016-05-19) ++++++++++++++++++ - Bugfix so that ``OAuth2`` always has the correct tokens after a call to ``refresh()``. diff --git a/boxsdk/auth/jwt_auth.py b/boxsdk/auth/jwt_auth.py index 2d81697..266fff2 100644 --- a/boxsdk/auth/jwt_auth.py +++ b/boxsdk/auth/jwt_auth.py @@ -1,6 +1,6 @@ # coding: utf-8 -from __future__ import unicode_literals +from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta import random @@ -95,7 +95,7 @@ def __init__( refresh_token=None, network_layer=network_layer, ) - with open(rsa_private_key_file_sys_path) as key_file: + with open(rsa_private_key_file_sys_path, 'rb') as key_file: self._rsa_private_key = serialization.load_pem_private_key( key_file.read(), password=rsa_private_key_passphrase, @@ -182,6 +182,7 @@ def authenticate_instance(self): :rtype: `unicode` """ + self._user_id = None return self._auth_with_jwt(self._enterprise_id, 'enterprise') def _refresh(self, access_token): diff --git a/boxsdk/version.py b/boxsdk/version.py index 9f6ca5f..e4cd37c 100644 --- a/boxsdk/version.py +++ b/boxsdk/version.py @@ -3,4 +3,4 @@ from __future__ import unicode_literals, absolute_import -__version__ = '1.5.2' +__version__ = '1.5.3'
Private key file throws error when trying load_pem_private_key I'm running python-3.5.0 on OS X 10.11.5. When trying to use JWT Authorization, creating a JWTAuth object fails with: ``` Traceback (most recent call last): File "<stdin>", line 6, in <module> File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boxsdk/auth/jwt_auth.py", line 102, in __init__ backend=default_backend(), File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cryptography/hazmat/primitives/serialization.py", line 20, in load_pem_private_key return backend.load_pem_private_key(data, password) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cryptography/hazmat/backends/multibackend.py", line 289, in load_pem_private_key return b.load_pem_private_key(data, password) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1069, in load_pem_private_key password, File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1247, in _load_key mem_bio = self._bytes_to_bio(data) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 477, in _bytes_to_bio data_char_p = self._ffi.new("char[]", data) TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str ``` The default `openssl` backend is what seems to be the problem, but I'm not sure if I'm missing a step. [This issue](https://github.com/pyca/pyopenssl/issues/15) suggests that this is an expected result. I have tried a workaround that seems to work, but there are some issues there, as well.
box/box-python-sdk
diff --git a/test/unit/auth/test_jwt_auth.py b/test/unit/auth/test_jwt_auth.py index a117850..c65af57 100644 --- a/test/unit/auth/test_jwt_auth.py +++ b/test/unit/auth/test_jwt_auth.py @@ -73,7 +73,7 @@ def jwt_auth_init_mocks( } mock_network_layer.request.return_value = successful_token_response - key_file_read_data = 'key_file_read_data' + key_file_read_data = b'key_file_read_data' with patch('boxsdk.auth.jwt_auth.open', mock_open(read_data=key_file_read_data), create=True) as jwt_auth_open: with patch('cryptography.hazmat.primitives.serialization.load_pem_private_key') as load_pem_private_key: oauth = JWTAuth( @@ -88,7 +88,7 @@ def jwt_auth_init_mocks( jwt_key_id=jwt_key_id, ) - jwt_auth_open.assert_called_once_with(sentinel.rsa_path) + jwt_auth_open.assert_called_once_with(sentinel.rsa_path, 'rb') jwt_auth_open.return_value.read.assert_called_once_with() # pylint:disable=no-member load_pem_private_key.assert_called_once_with( key_file_read_data,
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 3 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-xdist", "mock", "sqlalchemy", "bottle" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
async-timeout==4.0.2 attrs==22.2.0 bottle==0.13.2 -e git+https://github.com/box/box-python-sdk.git@481a86227d6d063f2e4e4ae880f4e12cd16dab06#egg=boxsdk certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 cryptography==40.0.2 execnet==1.9.0 greenlet==2.0.2 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 mock==5.2.0 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycparser==2.21 PyJWT==2.4.0 pyparsing==3.1.4 pytest==7.0.1 pytest-xdist==3.0.2 redis==4.3.6 requests==2.27.1 requests-toolbelt==1.0.0 six==1.17.0 SQLAlchemy==1.4.54 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: box-python-sdk channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - async-timeout==4.0.2 - attrs==22.2.0 - bottle==0.13.2 - cffi==1.15.1 - charset-normalizer==2.0.12 - cryptography==40.0.2 - execnet==1.9.0 - greenlet==2.0.2 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==5.2.0 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pyjwt==2.4.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-xdist==3.0.2 - redis==4.3.6 - requests==2.27.1 - requests-toolbelt==1.0.0 - six==1.17.0 - sqlalchemy==1.4.54 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/box-python-sdk
[ "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_app_user_sends_post_request_with_correct_params[128-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_authenticate_instance_sends_post_request_with_correct_params[128-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_app_user_sends_post_request_with_correct_params[128-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[16-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[32-RS512-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS256-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS256-strong_password]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS512-None]", "test/unit/auth/test_jwt_auth.py::test_refresh_instance_sends_post_request_with_correct_params[128-RS512-strong_password]" ]
[]
[]
[]
Apache License 2.0
557
mapbox__mapbox-sdk-py-124
2f24f1661c1083959c4a0cbd2c1cb33139941a65
2016-05-26 22:27:32
2c11fdee6eee83ea82398cc0756ac7f35aada801
diff --git a/README.rst b/README.rst index c20b789..8b6cf8a 100644 --- a/README.rst +++ b/README.rst @@ -75,7 +75,7 @@ To run the examples as integration tests on your own Mapbox account .. code:: bash - MAPBOX_ACCESS_TOKEN="MY_ACCESS_TOKEN" py.test --doctest-glob='*.md' *.md + MAPBOX_ACCESS_TOKEN="MY_ACCESS_TOKEN" py.test --doctest-glob='*.md' docs/*.md See Also ======== diff --git a/docs/geocoding.md b/docs/geocoding.md index 3586829..01d57c6 100644 --- a/docs/geocoding.md +++ b/docs/geocoding.md @@ -129,6 +129,24 @@ Place results may be biased toward a given longitude and latitude. ``` +## Forward geocoding with bounding box + +Place results may be limited to those falling within a given bounding box. + +```python + +>>> response = geocoder.forward( +... "washington", bbox=[-78.338320,38.520792,-77.935454,38.864909]) +>>> response.status_code +200 +>>> first = response.geojson()['features'][0] +>>> first['place_name'] +'Washington, Virginia, United States' +>>> first['geometry']['coordinates'] +[-78.1594, 38.7135] + +``` + ## Reverse geocoding Places at a longitude, latitude point may be found using `Geocoder.reverse()`. diff --git a/mapbox/services/geocoding.py b/mapbox/services/geocoding.py index ef7174f..e357a04 100644 --- a/mapbox/services/geocoding.py +++ b/mapbox/services/geocoding.py @@ -36,7 +36,7 @@ class Geocoder(Service): raise InvalidPlaceTypeError(pt) return {'types': ",".join(types)} - def forward(self, address, types=None, lon=None, lat=None, country=None): + def forward(self, address, types=None, lon=None, lat=None, country=None, bbox=None): """Returns a Requests response object that contains a GeoJSON collection of places matching the given address. @@ -46,7 +46,7 @@ class Geocoder(Service): Place results may be constrained to those of one or more types or be biased toward a given longitude and latitude. - See: https://www.mapbox.com/developers/api/geocoding/#forward.""" + See: https://www.mapbox.com/api-documentation/#geocoding.""" uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand( dataset=self.name, query=address.encode('utf-8')) params = {} @@ -58,6 +58,8 @@ class Geocoder(Service): params.update(proximity='{0},{1}'.format( round(float(lon), self.precision.get('proximity', 3)), round(float(lat), self.precision.get('proximity', 3)))) + if bbox is not None: + params.update(bbox='{0},{1},{2},{3}'.format(*bbox)) resp = self.session.get(uri, params=params) self.handle_http_error(resp) @@ -75,7 +77,7 @@ class Geocoder(Service): `response.geojson()` returns the geocoding result as GeoJSON. `response.status_code` returns the HTTP API status code. - See: https://www.mapbox.com/developers/api/geocoding/#reverse.""" + See: https://www.mapbox.com/api-documentation/#retrieve-places-near-a-location.""" uri = URITemplate(self.baseuri + '/{dataset}/{lon},{lat}.json').expand( dataset=self.name, lon=str(round(float(lon), self.precision.get('reverse', 5))),
Support geocoding bbox parameter
mapbox/mapbox-sdk-py
diff --git a/tests/test_geocoder.py b/tests/test_geocoder.py index e30504c..da98a3d 100644 --- a/tests/test_geocoder.py +++ b/tests/test_geocoder.py @@ -212,6 +212,23 @@ def test_geocoder_proximity_rounding(): for coord in re.split(r'(%2C|,)', match.group(1)): assert _check_coordinate_precision(coord, 3) [email protected] +def test_geocoder_forward_bbox(): + """Bbox parameter works""" + + responses.add( + responses.GET, + 'https://api.mapbox.com/geocoding/v5/mapbox.places/washington.json?bbox=-78.3284%2C38.6039%2C-78.0428%2C38.7841&access_token=pk.test', + match_querystring=True, + body='{"query": ["washington"]}', status=200, + content_type='application/json') + + response = mapbox.Geocoder( + access_token='pk.test').forward( + 'washington', bbox=(-78.3284,38.6039,-78.0428,38.7841)) + assert response.status_code == 200 + assert response.json()['query'] == ["washington"] + @responses.activate def test_geocoder_reverse_rounding(): """Reverse geocoding parameters are rounded to 5 decimal places"""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 3, "test_score": 1 }, "num_modified_files": 3 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "pip install -U pip" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
boto3==1.37.23 botocore==1.37.23 CacheControl==0.14.2 cachetools==5.5.2 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 colorama==0.4.6 coverage==7.8.0 coveralls==4.0.1 distlib==0.3.9 docopt==0.6.2 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work iso3166==2.1.1 jmespath==1.0.1 -e git+https://github.com/mapbox/mapbox-sdk-py.git@2f24f1661c1083959c4a0cbd2c1cb33139941a65#egg=mapbox msgpack==1.1.0 packaging @ file:///croot/packaging_1734472117206/work platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pyproject-api==1.9.0 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 responses==0.25.7 s3transfer==0.11.4 six==1.17.0 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 uritemplate==4.1.1 uritemplate.py==3.0.2 urllib3==1.26.20 virtualenv==20.29.3
name: mapbox-sdk-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.37.23 - botocore==1.37.23 - cachecontrol==0.14.2 - cachetools==5.5.2 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - click-plugins==1.1.1 - cligj==0.7.2 - colorama==0.4.6 - coverage==7.8.0 - coveralls==4.0.1 - distlib==0.3.9 - docopt==0.6.2 - filelock==3.18.0 - idna==3.10 - iso3166==2.1.1 - jmespath==1.0.1 - msgpack==1.1.0 - pip==25.0.1 - platformdirs==4.3.7 - pyproject-api==1.9.0 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - responses==0.25.7 - s3transfer==0.11.4 - six==1.17.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - uritemplate==4.1.1 - uritemplate-py==3.0.2 - urllib3==1.26.20 - virtualenv==20.29.3 prefix: /opt/conda/envs/mapbox-sdk-py
[ "tests/test_geocoder.py::test_geocoder_forward_bbox" ]
[]
[ "tests/test_geocoder.py::test_geocoder_default_name", "tests/test_geocoder.py::test_geocoder_name", "tests/test_geocoder.py::test_geocoder_forward", "tests/test_geocoder.py::test_geocoder_forward_geojson", "tests/test_geocoder.py::test_geocoder_reverse", "tests/test_geocoder.py::test_geocoder_reverse_geojson", "tests/test_geocoder.py::test_geocoder_place_types", "tests/test_geocoder.py::test_validate_country_codes_err", "tests/test_geocoder.py::test_validate_country", "tests/test_geocoder.py::test_validate_place_types_err", "tests/test_geocoder.py::test_validate_place_types", "tests/test_geocoder.py::test_geocoder_forward_types", "tests/test_geocoder.py::test_geocoder_reverse_types", "tests/test_geocoder.py::test_geocoder_forward_proximity", "tests/test_geocoder.py::test_geocoder_proximity_rounding", "tests/test_geocoder.py::test_geocoder_reverse_rounding", "tests/test_geocoder.py::test_geocoder_unicode" ]
[]
MIT License
558
falconry__falcon-801
10d1b7e770045b95ff5cb0cc3b4adfcc583049e2
2016-05-26 23:06:38
67d61029847cbf59e4053c8a424df4f9f87ad36f
painterjd: This looks good. It would be nice to see a test for this, however. codecov-io: ## [Current coverage][cc-pull] is **100%** > Merging [#801][cc-pull] into [master][cc-base-branch] will not change coverage ```diff @@ master #801 diff @@ ========================================== Files 29 29 Lines 1777 1778 +1 Methods 0 0 Messages 0 0 Branches 299 299 ========================================== + Hits 1777 1778 +1 Misses 0 0 Partials 0 0 ``` > Powered by [Codecov](https://codecov.io?src=pr). Last updated by [53b198c...1b84eeb][cc-compare] [cc-base-branch]: https://codecov.io/gh/falconry/falcon/branch/master?src=pr [cc-compare]: https://codecov.io/gh/falconry/falcon/compare/53b198c6d83cb04f051424e9cc33b593c52e65d7...1b84eeb8f3d8941113801958b76939d9bc726841 [cc-pull]: https://codecov.io/gh/falconry/falcon/pull/801?src=pr yashmehrotra: @painterjd Hi, I have added the test for this. Please Review. Thanks.
diff --git a/falcon/responders.py b/falcon/responders.py index b5f6186..34da807 100644 --- a/falcon/responders.py +++ b/falcon/responders.py @@ -58,5 +58,6 @@ def create_default_options(allowed_methods): def on_options(req, resp, **kwargs): resp.status = HTTP_204 resp.set_header('Allow', allowed) + resp.set_header('Content-Length', '0') return on_options diff --git a/falcon/response.py b/falcon/response.py index f3e2c9b..452432d 100644 --- a/falcon/response.py +++ b/falcon/response.py @@ -481,7 +481,12 @@ class Response(object): content_location = header_property( 'Content-Location', - 'Sets the Content-Location header.', + """Sets the Content-Location header. + + This value will be URI encoded per RFC 3986. If the value that is + being set is already URI encoded it should be decoded first or the + header should be set manually using the set_header method. + """, uri_encode) content_range = header_property( @@ -523,7 +528,12 @@ class Response(object): location = header_property( 'Location', - 'Sets the Location header.', + """Sets the Location header. + + This value will be URI encoded per RFC 3986. If the value that is + being set is already URI encoded it should be decoded first or the + header should be set manually using the set_header method. + """, uri_encode) retry_after = header_property( diff --git a/falcon/util/misc.py b/falcon/util/misc.py index c01c05c..5b02f05 100644 --- a/falcon/util/misc.py +++ b/falcon/util/misc.py @@ -19,6 +19,8 @@ import warnings import six +from falcon import status_codes + __all__ = ( 'deprecated', 'http_now', @@ -26,6 +28,7 @@ __all__ = ( 'http_date_to_dt', 'to_query_str', 'get_bound_method', + 'get_http_status' ) @@ -210,3 +213,36 @@ def get_bound_method(obj, method_name): raise AttributeError(msg) return method + + +def get_http_status(status_code, default_reason='Unknown'): + """Gets both the http status code and description from just a code + + Args: + status_code: integer or string that can be converted to an integer + default_reason: default text to be appended to the status_code + if the lookup does not find a result + + Returns: + str: status code e.g. "404 Not Found" + + Raises: + ValueError: the value entered could not be converted to an integer + + """ + # sanitize inputs + try: + code = float(status_code) # float can validate values like "401.1" + code = int(code) # converting to int removes the decimal places + if code < 100: + raise ValueError + except ValueError: + raise ValueError('get_http_status failed: "%s" is not a ' + 'valid status code', status_code) + + # lookup the status code + try: + return getattr(status_codes, 'HTTP_' + str(code)) + except AttributeError: + # not found + return str(code) + ' ' + default_reason diff --git a/tox.ini b/tox.ini index 13a7b9d..7538965 100644 --- a/tox.ini +++ b/tox.ini @@ -27,7 +27,7 @@ commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon whitelist_externals = bash mv commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon - nosetests --with-coverage + nosetests --with-coverage [] bash -c "if [ ! -d .coverage_data ]; then mkdir .coverage_data; fi" mv {toxinidir}/.coverage {toxinidir}/.coverage_data/.coverage.{envname}
Default OPTIONS responder does not set Content-Length to "0" Per RFC 7231: > A server MUST generate a Content-Length field with a value of "0" if no payload body is to be sent in the response.
falconry/falcon
diff --git a/tests/test_headers.py b/tests/test_headers.py index 8880992..838755d 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -534,6 +534,12 @@ class TestHeaders(testing.TestCase): self._check_link_header(resource, expected_value) + def test_content_length_options(self): + result = self.simulate_options() + + content_length = '0' + self.assertEqual(result.headers['Content-Length'], content_length) + # ---------------------------------------------------------------------- # Helpers # ---------------------------------------------------------------------- diff --git a/tests/test_utils.py b/tests/test_utils.py index fef8bec..957a959 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -297,6 +297,21 @@ class TestFalconUtils(testtools.TestCase): self.assertEqual(uri.parse_host('falcon.example.com:42'), ('falcon.example.com', 42)) + def test_get_http_status(self): + self.assertEqual(falcon.get_http_status(404), falcon.HTTP_404) + self.assertEqual(falcon.get_http_status(404.3), falcon.HTTP_404) + self.assertEqual(falcon.get_http_status('404.3'), falcon.HTTP_404) + self.assertEqual(falcon.get_http_status(404.9), falcon.HTTP_404) + self.assertEqual(falcon.get_http_status('404'), falcon.HTTP_404) + self.assertEqual(falcon.get_http_status(123), '123 Unknown') + self.assertRaises(ValueError, falcon.get_http_status, 'not_a_number') + self.assertRaises(ValueError, falcon.get_http_status, 0) + self.assertRaises(ValueError, falcon.get_http_status, 99) + self.assertRaises(ValueError, falcon.get_http_status, -404.3) + self.assertRaises(ValueError, falcon.get_http_status, '-404') + self.assertRaises(ValueError, falcon.get_http_status, '-404.3') + self.assertEqual(falcon.get_http_status(123, 'Go Away'), '123 Go Away') + class TestFalconTesting(testing.TestBase): """Catch some uncommon branches not covered elsewhere."""
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 4 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "ddt", "testtools", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "tools/test-requires" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 ddt==1.7.2 -e git+https://github.com/falconry/falcon.git@10d1b7e770045b95ff5cb0cc3b4adfcc583049e2#egg=falcon fixtures==4.0.1 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 nose==1.3.7 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-mimeparse==1.6.0 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 testtools==2.6.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - ddt==1.7.2 - fixtures==4.0.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-mimeparse==1.6.0 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - testtools==2.6.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/falcon
[ "tests/test_headers.py::TestHeaders::test_content_length_options", "tests/test_utils.py::TestFalconUtils::test_get_http_status" ]
[ "tests/test_utils.py::TestFalconUtils::test_deprecated_decorator" ]
[ "tests/test_headers.py::TestHeaders::test_add_link_complex", "tests/test_headers.py::TestHeaders::test_add_link_multiple", "tests/test_headers.py::TestHeaders::test_add_link_single", "tests/test_headers.py::TestHeaders::test_add_link_with_anchor", "tests/test_headers.py::TestHeaders::test_add_link_with_hreflang", "tests/test_headers.py::TestHeaders::test_add_link_with_hreflang_multi", "tests/test_headers.py::TestHeaders::test_add_link_with_title", "tests/test_headers.py::TestHeaders::test_add_link_with_title_star", "tests/test_headers.py::TestHeaders::test_add_link_with_type_hint", "tests/test_headers.py::TestHeaders::test_content_header_missing", "tests/test_headers.py::TestHeaders::test_content_length", "tests/test_headers.py::TestHeaders::test_content_type_no_body", "tests/test_headers.py::TestHeaders::test_custom_content_type", "tests/test_headers.py::TestHeaders::test_default_media_type", "tests/test_headers.py::TestHeaders::test_default_value", "tests/test_headers.py::TestHeaders::test_headers_as_list", "tests/test_headers.py::TestHeaders::test_no_content_length_1_204_No_Content", "tests/test_headers.py::TestHeaders::test_no_content_length_2_304_Not_Modified", "tests/test_headers.py::TestHeaders::test_no_content_type_1_204_No_Content", "tests/test_headers.py::TestHeaders::test_no_content_type_2_304_Not_Modified", "tests/test_headers.py::TestHeaders::test_override_default_media_type_1___text_plain__charset_UTF_8____Hello_Unicode_____", "tests/test_headers.py::TestHeaders::test_override_default_media_type_2___text_plain____Hello_ISO_8859_1___", "tests/test_headers.py::TestHeaders::test_override_default_media_type_missing_encoding", "tests/test_headers.py::TestHeaders::test_passthrough_request_headers", "tests/test_headers.py::TestHeaders::test_required_header", "tests/test_headers.py::TestHeaders::test_response_append_header", "tests/test_headers.py::TestHeaders::test_response_header_helpers_on_get", "tests/test_headers.py::TestHeaders::test_response_set_and_get_header", "tests/test_headers.py::TestHeaders::test_unicode_headers", "tests/test_headers.py::TestHeaders::test_unicode_location_headers", "tests/test_headers.py::TestHeaders::test_vary_header_1____accept_encoding_____accept_encoding__", "tests/test_headers.py::TestHeaders::test_vary_header_2____accept_encoding____x_auth_token_____accept_encoding__x_auth_token__", "tests/test_headers.py::TestHeaders::test_vary_header_3____accept_encoding____x_auth_token_____accept_encoding__x_auth_token__", "tests/test_headers.py::TestHeaders::test_vary_star", "tests/test_utils.py::TestFalconUtils::test_dt_to_http", "tests/test_utils.py::TestFalconUtils::test_http_date_to_dt", "tests/test_utils.py::TestFalconUtils::test_http_now", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_none", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_one", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_several", "tests/test_utils.py::TestFalconUtils::test_parse_host", "tests/test_utils.py::TestFalconUtils::test_parse_query_string", "tests/test_utils.py::TestFalconUtils::test_prop_uri_decode_models_stdlib_unquote_plus", "tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_models_stdlib_quote", "tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_value_models_stdlib_quote_safe_tilde", "tests/test_utils.py::TestFalconUtils::test_uri_decode", "tests/test_utils.py::TestFalconUtils::test_uri_encode", "tests/test_utils.py::TestFalconUtils::test_uri_encode_value", "tests/test_utils.py::TestFalconTesting::test_decode_empty_result", "tests/test_utils.py::TestFalconTesting::test_httpnow_alias_for_backwards_compat", "tests/test_utils.py::TestFalconTesting::test_none_header_value_in_create_environ", "tests/test_utils.py::TestFalconTesting::test_path_escape_chars_in_create_environ", "tests/test_utils.py::TestFalconTestCase::test_cached_text_in_result", "tests/test_utils.py::TestFalconTestCase::test_path_must_start_with_slash", "tests/test_utils.py::TestFalconTestCase::test_query_string", "tests/test_utils.py::TestFalconTestCase::test_query_string_in_path", "tests/test_utils.py::TestFalconTestCase::test_query_string_no_question", "tests/test_utils.py::TestFalconTestCase::test_simple_resource_body_json_xor", "tests/test_utils.py::TestFalconTestCase::test_status", "tests/test_utils.py::TestFalconTestCase::test_wsgi_iterable_not_closeable", "tests/test_utils.py::FancyTestCase::test_something" ]
[]
Apache License 2.0
559
geowurster__pyin-43
261933156ed3636b10d6ceb7439678f0b52bf3c2
2016-05-27 03:02:59
6047fc3192bfc3d337e8ea98771fa1255d46bf58
diff --git a/.travis.yml b/.travis.yml index 83e97c6..b2bfb42 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,12 @@ +sudo: false + language: python python: - - "2.7" - - "3.3" - - "3.4" + - 2.7 + - 3.3 + - 3.4 + - 3.5 install: - pip install -e .\[dev\] @@ -12,4 +15,4 @@ script: - py.test tests --cov pyin --cov-report term-missing after_success: - - coveralls + - coveralls || echo "!! intermittent coveralls failure" diff --git a/LICENSE.txt b/LICENSE.txt index 9640e3c..9f6aee8 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2015 Kevin D. Wurster +Copyright (c) 2015-2016 Kevin D. Wurster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/pyin/__init__.py b/pyin/__init__.py index 4cb5b31..e48091e 100644 --- a/pyin/__init__.py +++ b/pyin/__init__.py @@ -16,7 +16,7 @@ __source__ = 'https://github.com/geowurster/pyin' __license__ = ''' MIT -Copyright (c) 2015 Kevin D. Wurster +Copyright (c) 2015-2016 Kevin D. Wurster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/pyin/cli.py b/pyin/cli.py index 39295f7..9679678 100644 --- a/pyin/cli.py +++ b/pyin/cli.py @@ -25,16 +25,19 @@ import pyin.core ) @click.option( '--block', is_flag=True, - help="Operate on all input text as though it was a single line." + help="Place all input text into the `line` variable." ) @click.option( '--no-newline', is_flag=True, help="Don't ensure each line ends with a newline character." ) [email protected]( + '--skip', 'skip_lines', type=click.IntRange(0), metavar='INTEGER', default=0, + help='Skip N input lines.') @click.argument( 'expressions', required=True, nargs=-1, ) -def main(infile, outfile, expressions, no_newline, block): +def main(infile, outfile, expressions, no_newline, block, skip_lines): """ It's like sed, but Python! @@ -88,6 +91,12 @@ def main(infile, outfile, expressions, no_newline, block): $ python -c "help('pyin.core.pmap')" """ + for _ in range(skip_lines): + try: + next(infile) + except StopIteration: + raise click.ClickException("Skipped all input") + if block: iterator = [infile.read()] else: diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..8d0d862 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal: 1
Add a flag to skip N input lines Skip some number of lines before processing. Using something like `--skip-lines 2` in conjunction with `--lines 10` should skip the first 2 lines and process only the next ten lines.
geowurster/pyin
diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..32fcccd --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,12 @@ +""" +pytest fixtures +""" + + +from click.testing import CliRunner +import pytest + + [email protected](scope='module') +def runner(): + return CliRunner() diff --git a/tests/test_cli.py b/tests/test_cli.py index 55e3467..20ef908 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,8 +1,14 @@ +""" +Unittests for $ pyin +""" + + import json import os from os import path from click.testing import CliRunner +import pytest import pyin.cli @@ -76,3 +82,23 @@ def test_block_mode(): expected = '{"3": null, "4": null, "0": null, "2": null, "1": null}' assert json.loads(expected) == json.loads(result.output) + + [email protected]("skip_lines", [1, 3]) +def test_skip_single_line(runner, skip_lines): + result = runner.invoke(pyin.cli.main, [ + '--skip', skip_lines, + 'line' + ], input=CSV_WITH_HEADER) + assert result.exit_code == 0 + expected = os.linesep.join(CSV_WITH_HEADER.splitlines()[skip_lines:]) + assert result.output.strip() == expected.strip() + + +def test_skip_all_input(runner): + result = runner.invoke(pyin.cli.main, [ + '--skip', 100, + 'line' + ], input=CSV_WITH_HEADER) + assert result.output != 0 + assert 'skipped' in result.output.lower()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 4 }
0.5
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/geowurster/pyin.git@261933156ed3636b10d6ceb7439678f0b52bf3c2#egg=pyin pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 tomli==2.2.1 urllib3==2.3.0
name: pyin channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/pyin
[ "tests/test_cli.py::test_skip_single_line[1]", "tests/test_cli.py::test_skip_single_line[3]", "tests/test_cli.py::test_skip_all_input" ]
[]
[ "tests/test_cli.py::test_single_expr", "tests/test_cli.py::test_multiple_expr", "tests/test_cli.py::test_with_imports", "tests/test_cli.py::test_with_generator", "tests/test_cli.py::test_with_blank_lines", "tests/test_cli.py::test_block_mode" ]
[]
New BSD License
560
andycasey__ads-64
0afd82e0f48ee4debb9047c086488d860415bce7
2016-05-28 20:54:36
c039d67c2b2e9dad936758bc89df1fdd1cbd0aa1
diff --git a/ads/search.py b/ads/search.py index c8a0bb4..8f36421 100644 --- a/ads/search.py +++ b/ads/search.py @@ -40,21 +40,20 @@ class Article(object): return self.__unicode__().encode("utf-8") def __unicode__(self): - author = self.first_author or "Unknown author" - if self.author and len(self.author) > 1: + author = self._raw.get("first_author", "Unknown author") + if len(self._raw.get("author", [])) > 1: author += " et al." return u"<{author} {year}, {bibcode}>".format( author=author, - year=self.year, - bibcode=self.bibcode, + year=self._raw.get("year", "Unknown year"), + bibcode=self._raw.get("bibcode", "Unknown bibcode") ) def __eq__(self, other): - if (not hasattr(self, 'bibcode') or not hasattr(other, 'bibcode') or - self.bibcode is None or other.bibcode is None): + if self._raw.get("bibcode") is None or other._raw.get("bibcode") is None: raise TypeError("Cannot compare articles without bibcodes") - return self.bibcode == other.bibcode + return self._raw['bibcode'] == other._raw['bibcode'] def __ne__(self, other): return not self.__eq__(other) @@ -196,8 +195,8 @@ class Article(object): return self._get_field('indexstamp') @cached_property - def first_author_norm(self): - return self._get_field('first_author_norm') + def first_author(self): + return self._get_field('first_author') @cached_property def issue(self):
Exception handling in Unicode representation of Articles In the article method `__unicode__()`, the article properties `first_author`, `bibcode` and `year` are used. This can yield an exception if the fields are not included in the original search query; generally for `first_author` as no getter exists, or if deferred loading for `bibcode` and `year` fails. Cf. pull request #55 for a more detailed discussion of the issue.
andycasey/ads
diff --git a/ads/tests/test_search.py b/ads/tests/test_search.py index dc36eda..75d834f 100644 --- a/ads/tests/test_search.py +++ b/ads/tests/test_search.py @@ -49,12 +49,13 @@ class TestArticle(unittest.TestCase): def test_equals(self): """ the __eq__ method should compare bibcodes, and raise if bibcode isn't - defined + defined or is None """ self.assertNotEqual(Article(bibcode="Not the same"), self.article) self.assertEqual(Article(bibcode="2013A&A...552A.143S"), self.article) - with self.assertRaises(TypeError): - # Explicitly set bibcode to None to avoid invoking the getter. + with self.assertRaisesRegexp(TypeError, "Cannot compare articles without bibcodes"): + Article() == self.article + with self.assertRaisesRegexp(TypeError, "Cannot compare articles without bibcodes"): Article(bibcode=None) == self.article def test_init(self): @@ -79,6 +80,10 @@ class TestArticle(unittest.TestCase): self.article.__str__() ) self.assertEqual(self.article.__unicode__(), self.article.__str__()) + self.assertEqual( + Article().__str__(), + "<Unknown author Unknown year, Unknown bibcode>" + ) @patch('ads.search.Article._get_field') def test_cached_properties(self, patched):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/andycasey/ads.git@0afd82e0f48ee4debb9047c086488d860415bce7#egg=ads certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup==1.2.2 httpretty==0.8.10 idna==3.10 iniconfig==2.1.0 MarkupSafe==3.0.2 mock==5.2.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 requests==2.32.3 six==1.17.0 tomli==2.2.1 urllib3==2.3.0 Werkzeug==3.1.3
name: ads channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - exceptiongroup==1.2.2 - httpretty==0.8.10 - idna==3.10 - iniconfig==2.1.0 - markupsafe==3.0.2 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 - werkzeug==3.1.3 prefix: /opt/conda/envs/ads
[ "ads/tests/test_search.py::TestArticle::test_equals", "ads/tests/test_search.py::TestArticle::test_print_methods" ]
[ "ads/tests/test_search.py::TestArticle::test_cached_properties", "ads/tests/test_search.py::TestArticle::test_get_field", "ads/tests/test_search.py::TestArticle::test_init", "ads/tests/test_search.py::TestSearchQuery::test_iter", "ads/tests/test_search.py::TestSearchQuery::test_rows_rewrite", "ads/tests/test_search.py::TestSolrResponse::test_articles" ]
[ "ads/tests/test_search.py::TestSearchQuery::test_init", "ads/tests/test_search.py::TestSolrResponse::test_default_article_fields", "ads/tests/test_search.py::TestSolrResponse::test_init", "ads/tests/test_search.py::TestSolrResponse::test_load_http_response", "ads/tests/test_search.py::Testquery::test_init" ]
[]
MIT License
561
html5lib__html5lib-python-259
2d376737a6246ebb38a79600a7fe75abd923cf3e
2016-05-28 21:05:44
563dc298ea43021f9a9306fc7da3734ea5d9d8ec
codecov-io: ## [Current coverage][cc-pull] is **90.83%** > Merging [#259][cc-pull] into [master][cc-base-branch] will increase coverage by **<.01%** ```diff @@ master #259 diff @@ ========================================== Files 51 51 Lines 6836 6840 +4 Methods 0 0 Messages 0 0 Branches 1312 1312 ========================================== + Hits 6209 6213 +4 Misses 468 468 Partials 159 159 ``` > Powered by [Codecov](https://codecov.io?src=pr). Last updated by [2d37673...cbc1b34][cc-compare] [cc-base-branch]: https://codecov.io/gh/html5lib/html5lib-python/branch/master?src=pr [cc-compare]: https://codecov.io/gh/html5lib/html5lib-python/compare/2d376737a6246ebb38a79600a7fe75abd923cf3e...cbc1b34806178bd5119464865c263c0e254cfa55 [cc-pull]: https://codecov.io/gh/html5lib/html5lib-python/pull/259?src=pr
diff --git a/html5lib/treebuilders/etree.py b/html5lib/treebuilders/etree.py index d394148..4d12bd4 100644 --- a/html5lib/treebuilders/etree.py +++ b/html5lib/treebuilders/etree.py @@ -100,6 +100,7 @@ def getETreeBuilder(ElementTreeImplementation, fullTree=False): node.parent = self def removeChild(self, node): + self._childNodes.remove(node) self._element.remove(node._element) node.parent = None
etree treewalker infinite loop This goes into an infinite loop: ```python import html5lib frag = html5lib.parseFragment("<b><em><foo><foob><fooc><aside></b></em>") walker = html5lib.getTreeWalker("etree") print list(walker(frag)) ```
html5lib/html5lib-python
diff --git a/html5lib/tests/test_parser2.py b/html5lib/tests/test_parser2.py index 0ec5b04..b7a92fd 100644 --- a/html5lib/tests/test_parser2.py +++ b/html5lib/tests/test_parser2.py @@ -7,7 +7,7 @@ import io from . import support # noqa from html5lib.constants import namespaces -from html5lib import parse, HTMLParser +from html5lib import parse, parseFragment, HTMLParser # tests that aren't autogenerated from text files @@ -88,3 +88,8 @@ def test_debug_log(): expected[i] = tuple(log) assert parser.log == expected + + +def test_no_duplicate_clone(): + frag = parseFragment("<b><em><foo><foob><fooc><aside></b></em>") + assert len(frag) == 2
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.08
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock" ], "pre_install": [ "git submodule update --init --recursive" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
chardet==5.2.0 datrie==0.8.2 exceptiongroup==1.2.2 Genshi==0.7.9 -e git+https://github.com/html5lib/html5lib-python.git@2d376737a6246ebb38a79600a7fe75abd923cf3e#egg=html5lib iniconfig==2.1.0 lxml==5.3.1 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 six==1.17.0 tomli==2.2.1 webencodings==0.5.1
name: html5lib-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - chardet==5.2.0 - datrie==0.8.2 - exceptiongroup==1.2.2 - genshi==0.7.9 - iniconfig==2.1.0 - lxml==5.3.1 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 - webencodings==0.5.1 prefix: /opt/conda/envs/html5lib-python
[ "html5lib/tests/test_parser2.py::test_no_duplicate_clone" ]
[]
[ "html5lib/tests/test_parser2.py::test_assertDoctypeCloneable", "html5lib/tests/test_parser2.py::test_line_counter", "html5lib/tests/test_parser2.py::test_namespace_html_elements_0_dom", "html5lib/tests/test_parser2.py::test_namespace_html_elements_1_dom", "html5lib/tests/test_parser2.py::test_namespace_html_elements_0_etree", "html5lib/tests/test_parser2.py::test_namespace_html_elements_1_etree", "html5lib/tests/test_parser2.py::test_unicode_file", "html5lib/tests/test_parser2.py::test_duplicate_attribute", "html5lib/tests/test_parser2.py::test_debug_log" ]
[]
MIT License
562
ifosch__accloudtant-82
9dd6000060b4bddfa5366ef3102fe7d42371d514
2016-05-29 14:55:50
33f90ff0bc1639c9fe793afd837eee80170caf3e
diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py index 4e19b2d..2073f28 100644 --- a/accloudtant/aws/instance.py +++ b/accloudtant/aws/instance.py @@ -62,7 +62,7 @@ class Instance(object): @property def name(self): names = [tag for tag in self.tags if tag['Key'] == 'Name'] - if names is None: + if len(names) == 0: return '' else: return names[0]['Value']
Fails with Python 3 My system have Python 3 installed by default (Archlinux). This is the output of `accloudtant report`: ``` Traceback (most recent call last): File "/usr/bin/accloudtant", line 22, in <module> cli() File "/usr/lib/python3.5/site-packages/click/core.py", line 716, in __call__ return self.main(*args, **kwargs) File "/usr/lib/python3.5/site-packages/click/core.py", line 696, in main rv = self.invoke(ctx) File "/usr/lib/python3.5/site-packages/click/core.py", line 1060, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/lib/python3.5/site-packages/click/core.py", line 889, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/lib/python3.5/site-packages/click/core.py", line 534, in invoke return callback(*args, **kwargs) File "/usr/bin/accloudtant", line 19, in report click.echo(Reports()) File "/usr/lib/python3.5/site-packages/click/utils.py", line 221, in echo message = text_type(message) File "/usr/lib/python3.5/site-packages/accloudtant/aws/reports.py", line 69, in __repr__ instance.name, File "/usr/lib/python3.5/site-packages/accloudtant/aws/instance.py", line 68, in name return names[0]['Value'] IndexError: list index out of range ``` I can't verify that it works well on Python 2 so fell free to close this issue and open a new one if the problem is not caused by the Python version.
ifosch/accloudtant
diff --git a/tests/aws/test_instance.py b/tests/aws/test_instance.py index d90e2c5..a016f7b 100644 --- a/tests/aws/test_instance.py +++ b/tests/aws/test_instance.py @@ -73,6 +73,57 @@ def test_instance(): assert(instance.best == 0.293) +def test_unnamed_instance(): + az = 'us-east-1b' + region = 'us-east-1' + instance_data = { + 'id': 'i-1840273e', + 'tags': [], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': az, + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'RHEL Linux', }, + } + + + ec2_instance = MockEC2Instance(instance_data) + instance = accloudtant.aws.instance.Instance(ec2_instance) + + assert(instance.id == ec2_instance.id) + assert(instance.reserved == 'No') + assert(instance.name == '') + assert(instance.size == ec2_instance.instance_type) + assert(instance.availability_zone == az) + assert(instance.region == region) + assert(instance.operating_system == 'Red Hat Enterprise Linux') + assert(instance.key == 'rhel') + assert(instance.state == ec2_instance.state['Name']) + assert(instance.current == 0.0) + assert(instance.best == 0.0) + + with pytest.raises(ValueError): + instance.reserved = 'Maybe' + + instance.current = 0.392 + instance.best = 0.293 + + assert(instance.current == 0.392) + assert(instance.best == 0.293) + + def test_guess_os(): instance_data_win = { 'id': 'i-912a4392',
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/ifosch/accloudtant.git@9dd6000060b4bddfa5366ef3102fe7d42371d514#egg=accloudtant boto3==1.37.23 botocore==1.37.23 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 jmespath==1.0.1 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 requests==2.32.3 s3transfer==0.11.4 six==1.17.0 tabulate==0.9.0 tomli==2.2.1 urllib3==1.26.20
name: accloudtant channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.37.23 - botocore==1.37.23 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - jmespath==1.0.1 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - requests==2.32.3 - s3transfer==0.11.4 - six==1.17.0 - tabulate==0.9.0 - tomli==2.2.1 - urllib3==1.26.20 prefix: /opt/conda/envs/accloudtant
[ "tests/aws/test_instance.py::test_unnamed_instance" ]
[]
[ "tests/aws/test_instance.py::test_instance", "tests/aws/test_instance.py::test_guess_os", "tests/aws/test_instance.py::test_match_reserved_instance" ]
[]
null
563
Axelrod-Python__Axelrod-603
c919c39d58552c2db4a2719c817cfa3a3c301f92
2016-05-30 15:36:49
e5b85453f0288ec9f9ea9eb91ed6042855a7b86c
diff --git a/axelrod/result_set.py b/axelrod/result_set.py index b2bc1b94..b0a67300 100644 --- a/axelrod/result_set.py +++ b/axelrod/result_set.py @@ -1,5 +1,6 @@ from collections import defaultdict import csv +import tqdm from numpy import mean, nanmedian, std @@ -14,10 +15,25 @@ except ImportError: from io import StringIO +def update_progress_bar(method): + """A decorator to update a progress bar if it exists""" + def wrapper(*args): + """Run the method and update the progress bar if it exists""" + output = method(*args) + + try: + args[0].progress_bar.update(1) + except AttributeError: + pass + + return output + return wrapper + + class ResultSet(object): """A class to hold the results of a tournament.""" - def __init__(self, players, interactions, with_morality=True): + def __init__(self, players, interactions, progress_bar=True): """ Parameters ---------- @@ -26,19 +42,24 @@ class ResultSet(object): interactions : list a list of dictionaries mapping tuples of player indices to interactions (1 for each repetition) - with_morality : bool - a flag to determine whether morality metrics should be - calculated. + progress_bar : bool + Whether or not to create a progress bar which will be updated """ self.players = players self.nplayers = len(players) self.interactions = interactions self.nrepetitions = max([len(rep) for rep in list(interactions.values())]) + if progress_bar: + self.progress_bar = tqdm.tqdm(total=19, desc="Analysing results") + else: + self.progress_bar = False + # Calculate all attributes: - self.build_all(with_morality) + self.build_all() + - def build_all(self, with_morality): + def build_all(self): """Build all the results. In a seperate method to make inheritance more straightforward""" self.wins = self.build_wins() @@ -54,15 +75,19 @@ class ResultSet(object): self.score_diffs = self.build_score_diffs() self.payoff_diffs_means = self.build_payoff_diffs_means() - if with_morality: - self.cooperation = self.build_cooperation() - self.normalised_cooperation = self.build_normalised_cooperation() - self.vengeful_cooperation = self.build_vengeful_cooperation() - self.cooperating_rating = self.build_cooperating_rating() - self.good_partner_matrix = self.build_good_partner_matrix() - self.good_partner_rating = self.build_good_partner_rating() - self.eigenmoses_rating = self.build_eigenmoses_rating() - self.eigenjesus_rating = self.build_eigenjesus_rating() + self.cooperation = self.build_cooperation() + self.normalised_cooperation = self.build_normalised_cooperation() + self.vengeful_cooperation = self.build_vengeful_cooperation() + self.cooperating_rating = self.build_cooperating_rating() + self.good_partner_matrix = self.build_good_partner_matrix() + self.good_partner_rating = self.build_good_partner_rating() + self.eigenmoses_rating = self.build_eigenmoses_rating() + self.eigenjesus_rating = self.build_eigenjesus_rating() + + try: + self.progress_bar.close() + except AttributeError: + pass @property def _null_results_matrix(self): @@ -79,6 +104,7 @@ class ResultSet(object): replist = list(range(self.nrepetitions)) return [[[0 for j in plist] for i in plist] for r in replist] + @update_progress_bar def build_match_lengths(self): """ Returns: @@ -110,6 +136,7 @@ class ResultSet(object): return match_lengths + @update_progress_bar def build_scores(self): """ Returns: @@ -143,6 +170,7 @@ class ResultSet(object): return scores + @update_progress_bar def build_ranked_names(self): """ Returns: @@ -150,8 +178,10 @@ class ResultSet(object): Returns the ranked names. A list of names as calculated by self.ranking. """ + return [str(self.players[i]) for i in self.ranking] + @update_progress_bar def build_wins(self): """ Returns: @@ -187,6 +217,7 @@ class ResultSet(object): return wins + @update_progress_bar def build_normalised_scores(self): """ Returns: @@ -229,6 +260,7 @@ class ResultSet(object): return normalised_scores + @update_progress_bar def build_ranking(self): """ Returns: @@ -244,6 +276,7 @@ class ResultSet(object): return sorted(range(self.nplayers), key=lambda i: -nanmedian(self.normalised_scores[i])) + @update_progress_bar def build_payoffs(self): """ Returns: @@ -281,8 +314,10 @@ class ResultSet(object): utilities.append(iu.compute_final_score_per_turn(interaction)[1]) payoffs[player][opponent] = utilities + return payoffs + @update_progress_bar def build_payoff_matrix(self): """ Returns: @@ -317,6 +352,7 @@ class ResultSet(object): return payoff_matrix + @update_progress_bar def build_payoff_stddevs(self): """ Returns: @@ -353,6 +389,7 @@ class ResultSet(object): return payoff_stddevs + @update_progress_bar def build_score_diffs(self): """ Returns: @@ -391,8 +428,10 @@ class ResultSet(object): scores = iu.compute_final_score_per_turn(interaction) diff = (scores[1] - scores[0]) score_diffs[player][opponent][repetition] = diff + return score_diffs + @update_progress_bar def build_payoff_diffs_means(self): """ Returns: @@ -429,8 +468,10 @@ class ResultSet(object): payoff_diffs_means[player][opponent] = mean(diffs) else: payoff_diffs_means[player][opponent] = 0 + return payoff_diffs_means + @update_progress_bar def build_cooperation(self): """ Returns: @@ -465,8 +506,10 @@ class ResultSet(object): coop_count += iu.compute_cooperations(interaction)[1] cooperations[player][opponent] += coop_count + return cooperations + @update_progress_bar def build_normalised_cooperation(self): """ Returns: @@ -507,8 +550,10 @@ class ResultSet(object): # Mean over all reps: normalised_cooperations[player][opponent] = mean(coop_counts) + return normalised_cooperations + @update_progress_bar def build_vengeful_cooperation(self): """ Returns: @@ -522,6 +567,7 @@ class ResultSet(object): return [[2 * (element - 0.5) for element in row] for row in self.normalised_cooperation] + @update_progress_bar def build_cooperating_rating(self): """ Returns: @@ -552,6 +598,7 @@ class ResultSet(object): return [sum(cs) / max(1, float(sum(ls))) for cs, ls in zip(self.cooperation, lengths)] + @update_progress_bar def build_good_partner_matrix(self): """ Returns: @@ -586,6 +633,7 @@ class ResultSet(object): return good_partner_matrix + @update_progress_bar def build_good_partner_rating(self): """ Returns: @@ -607,6 +655,7 @@ class ResultSet(object): return good_partner_rating + @update_progress_bar def build_eigenjesus_rating(self): """ Returns: @@ -617,8 +666,10 @@ class ResultSet(object): """ eigenvector, eigenvalue = eigen.principal_eigenvector( self.normalised_cooperation) + return eigenvector.tolist() + @update_progress_bar def build_eigenmoses_rating(self): """ Returns: @@ -629,6 +680,7 @@ class ResultSet(object): """ eigenvector, eigenvalue = eigen.principal_eigenvector( self.vengeful_cooperation) + return eigenvector.tolist() def csv(self): @@ -655,22 +707,26 @@ class ResultSetFromFile(ResultSet): by the tournament class. """ - def __init__(self, filename, with_morality=True): + def __init__(self, filename, progress_bar=True): """ Parameters ---------- filename : string name of a file of the correct file. - with_morality : bool - a flag to determine whether morality metrics should be - calculated. + progress_bar : bool + Whether or not to create a progress bar which will be updated """ self.players, self.interactions = self._read_csv(filename) self.nplayers = len(self.players) self.nrepetitions = len(list(self.interactions.values())[0]) + if progress_bar: + self.progress_bar = tqdm.tqdm(total=19, desc="Analysing results") + else: + self.progress_bar = False + # Calculate all attributes: - self.build_all(with_morality) + self.build_all() def _read_csv(self, filename): """ diff --git a/axelrod/tournament.py b/axelrod/tournament.py index 6b638aa1..32684643 100644 --- a/axelrod/tournament.py +++ b/axelrod/tournament.py @@ -85,7 +85,8 @@ class Tournament(object): axelrod.ResultSet """ if progress_bar: - self.progress_bar = tqdm.tqdm(total=len(self.match_generator)) + self.progress_bar = tqdm.tqdm(total=len(self.match_generator), + desc="Playing matches") self.setup_output_file(filename) if not build_results and not filename: @@ -96,13 +97,16 @@ class Tournament(object): else: self._run_parallel(processes=processes, progress_bar=progress_bar) + if progress_bar: + self.progress_bar.close() + # Make sure that python has finished writing to disk self.outputfile.flush() if build_results: - return self._build_result_set() + return self._build_result_set(progress_bar=progress_bar) - def _build_result_set(self): + def _build_result_set(self, progress_bar=True): """ Build the result set (used by the play method) @@ -112,7 +116,7 @@ class Tournament(object): """ result_set = ResultSetFromFile( filename=self.filename, - with_morality=self._with_morality) + progress_bar=progress_bar) self.outputfile.close() return result_set
Results set processing shouldn't be in the progress bar
Axelrod-Python/Axelrod
diff --git a/axelrod/tests/unit/test_resultset.py b/axelrod/tests/unit/test_resultset.py index 2df8666a..c5a084bb 100644 --- a/axelrod/tests/unit/test_resultset.py +++ b/axelrod/tests/unit/test_resultset.py @@ -161,7 +161,9 @@ class TestResultSet(unittest.TestCase): 'Defector,Tit For Tat,Alternator\n2.6,1.7,1.5\n2.6,1.7,1.5\n2.6,1.7,1.5\n') def test_init(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) + self.assertFalse(rs.progress_bar) self.assertEqual(rs.players, self.players) self.assertEqual(rs.nplayers, len(self.players)) self.assertEqual(rs.interactions, self.interactions) @@ -176,13 +178,25 @@ class TestResultSet(unittest.TestCase): self.assertIsInstance(interaction, list) self.assertEqual(len(interaction), self.turns) - def test_null_results_matrix(self): + def test_with_progress_bar(self): rs = axelrod.ResultSet(self.players, self.interactions) + self.assertTrue(rs.progress_bar) + self.assertEqual(rs.progress_bar.total, 19) + + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=True) + self.assertTrue(rs.progress_bar) + self.assertEqual(rs.progress_bar.total, 19) + + def test_null_results_matrix(self): + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertEqual( rs._null_results_matrix, self.expected_null_results_matrix) def test_match_lengths(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.match_lengths, list) self.assertEqual(len(rs.match_lengths), rs.nrepetitions) self.assertEqual(rs.match_lengths, self.expected_match_lengths) @@ -202,49 +216,57 @@ class TestResultSet(unittest.TestCase): self.assertEqual(length, self.turns) def test_scores(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.scores, list) self.assertEqual(len(rs.scores), rs.nplayers) self.assertEqual(rs.scores, self.expected_scores) def test_ranking(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.ranking, list) self.assertEqual(len(rs.ranking), rs.nplayers) self.assertEqual(rs.ranking, self.expected_ranking) def test_ranked_names(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.ranked_names, list) self.assertEqual(len(rs.ranked_names), rs.nplayers) self.assertEqual(rs.ranked_names, self.expected_ranked_names) def test_wins(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.wins, list) self.assertEqual(len(rs.wins), rs.nplayers) self.assertEqual(rs.wins, self.expected_wins) def test_normalised_scores(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.normalised_scores, list) self.assertEqual(len(rs.normalised_scores), rs.nplayers) self.assertEqual(rs.normalised_scores, self.expected_normalised_scores) def test_payoffs(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.payoffs, list) self.assertEqual(len(rs.payoffs), rs.nplayers) self.assertEqual(rs.payoffs, self.expected_payoffs) def test_payoff_matrix(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.payoff_matrix, list) self.assertEqual(len(rs.payoff_matrix), rs.nplayers) self.assertEqual(rs.payoff_matrix, self.expected_payoff_matrix) def test_score_diffs(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.score_diffs, list) self.assertEqual(len(rs.score_diffs), rs.nplayers) for i, row in enumerate(rs.score_diffs): @@ -254,7 +276,8 @@ class TestResultSet(unittest.TestCase): self.expected_score_diffs[i][j][k]) def test_payoff_diffs_means(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.payoff_diffs_means, list) self.assertEqual(len(rs.payoff_diffs_means), rs.nplayers) for i, row in enumerate(rs.payoff_diffs_means): @@ -263,68 +286,78 @@ class TestResultSet(unittest.TestCase): self.expected_payoff_diffs_means[i][j]) def test_payoff_stddevs(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.payoff_stddevs, list) self.assertEqual(len(rs.payoff_stddevs), rs.nplayers) self.assertEqual(rs.payoff_stddevs, self.expected_payoff_stddevs) def test_cooperation(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.cooperation, list) self.assertEqual(len(rs.cooperation), rs.nplayers) self.assertEqual(rs.cooperation, self.expected_cooperation) def test_normalised_cooperation(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.normalised_cooperation, list) self.assertEqual(len(rs.normalised_cooperation), rs.nplayers) self.assertEqual(rs.normalised_cooperation, self.expected_normalised_cooperation) def test_vengeful_cooperation(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.vengeful_cooperation, list) self.assertEqual(len(rs.vengeful_cooperation), rs.nplayers) self.assertEqual(rs.vengeful_cooperation, self.expected_vengeful_cooperation) def test_cooperating_rating(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.cooperating_rating, list) self.assertEqual(len(rs.cooperating_rating), rs.nplayers) self.assertEqual(rs.cooperating_rating, self.expected_cooperating_rating) def test_good_partner_matrix(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.good_partner_matrix, list) self.assertEqual(len(rs.good_partner_matrix), rs.nplayers) self.assertEqual(rs.good_partner_matrix, self.expected_good_partner_matrix) def test_good_partner_rating(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.good_partner_rating, list) self.assertEqual(len(rs.good_partner_rating), rs.nplayers) self.assertEqual(rs.good_partner_rating, self.expected_good_partner_rating) def test_eigenjesus_rating(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.eigenjesus_rating, list) self.assertEqual(len(rs.eigenjesus_rating), rs.nplayers) for j, rate in enumerate(rs.eigenjesus_rating): self.assertAlmostEqual(rate, self.expected_eigenjesus_rating[j]) def test_eigenmoses_rating(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertIsInstance(rs.eigenmoses_rating, list) self.assertEqual(len(rs.eigenmoses_rating), rs.nplayers) for j, rate in enumerate(rs.eigenmoses_rating): self.assertAlmostEqual(rate, self.expected_eigenmoses_rating[j]) def test_csv(self): - rs = axelrod.ResultSet(self.players, self.interactions) + rs = axelrod.ResultSet(self.players, self.interactions, + progress_bar=False) self.assertEqual(rs.csv(), self.expected_csv) @@ -341,7 +374,7 @@ class TestResultSetFromFile(unittest.TestCase): def test_init(self): - rs = axelrod.ResultSetFromFile(self.tmp_file.name) + rs = axelrod.ResultSetFromFile(self.tmp_file.name, progress_bar=False) players = ['Cooperator', 'Tit For Tat', 'Defector'] self.assertEqual(rs.players, players) self.assertEqual(rs.nplayers, len(players)) @@ -354,3 +387,9 @@ class TestResultSetFromFile(unittest.TestCase): (0, 2): [[('C', 'D'), ('C', 'D')]], (1, 1): [[('C', 'C'), ('C', 'C')]]} self.assertEqual(rs.interactions, expected_interactions) + + +class TestDecorator(unittest.TestCase): + def test_update_progress_bar(self): + method = lambda x: None + self.assertEqual(axelrod.result_set.update_progress_bar(method)(1), None)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 2 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 -e git+https://github.com/Axelrod-Python/Axelrod.git@c919c39d58552c2db4a2719c817cfa3a3c301f92#egg=Axelrod coverage==7.8.0 cycler==0.12.1 exceptiongroup==1.2.2 hypothesis==6.130.6 iniconfig==2.1.0 kiwisolver==1.4.7 matplotlib==3.3.4 numpy==2.0.2 packaging==24.2 pillow==11.1.0 pluggy==1.5.0 pyparsing==2.1.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 six==1.17.0 sortedcontainers==2.4.0 testfixtures==4.9.1 tomli==2.2.1 tqdm==3.4.0
name: Axelrod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - coverage==7.8.0 - cycler==0.12.1 - exceptiongroup==1.2.2 - hypothesis==6.130.6 - iniconfig==2.1.0 - kiwisolver==1.4.7 - matplotlib==3.3.4 - numpy==2.0.2 - packaging==24.2 - pillow==11.1.0 - pluggy==1.5.0 - pyparsing==2.1.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - six==1.17.0 - sortedcontainers==2.4.0 - testfixtures==4.9.1 - tomli==2.2.1 - tqdm==3.4.0 prefix: /opt/conda/envs/Axelrod
[ "axelrod/tests/unit/test_resultset.py::TestResultSet::test_cooperating_rating", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_cooperation", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_eigenjesus_rating", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_eigenmoses_rating", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_good_partner_matrix", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_good_partner_rating", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_init", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_match_lengths", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_normalised_cooperation", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_normalised_scores", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_null_results_matrix", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_payoff_diffs_means", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_payoff_matrix", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_payoff_stddevs", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_payoffs", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_ranked_names", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_ranking", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_score_diffs", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_scores", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_vengeful_cooperation", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_wins", "axelrod/tests/unit/test_resultset.py::TestResultSet::test_with_progress_bar", "axelrod/tests/unit/test_resultset.py::TestResultSetFromFile::test_init", "axelrod/tests/unit/test_resultset.py::TestDecorator::test_update_progress_bar" ]
[ "axelrod/tests/unit/test_resultset.py::TestResultSet::test_csv" ]
[]
[]
MIT License
564
zalando-stups__pierone-cli-37
991c05e9c7496b2aac071d85d0a9ca6b8afcf9dd
2016-05-31 08:47:53
560cae1b4fc185c7a8aa3a1a50e0a96b2c7dd8e7
diff --git a/pierone/cli.py b/pierone/cli.py index 1af5790..50dba86 100644 --- a/pierone/cli.py +++ b/pierone/cli.py @@ -232,7 +232,8 @@ def get_clair_features(url, layer_id, access_token): return [] else: r.raise_for_status() - return r.json()['Layer']['Features'] + + return r.json()['Layer'].get('Features', []) @cli.command()
pierone fails with backtrace when the CVE status is COULDNT_FIGURE_OUT ``` Traceback (most recent call last): File "/usr/local/bin/pierone", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.4/dist-packages/pierone/cli.py", line 485, in main cli() File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 716, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 696, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 1060, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 889, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 534, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/click/decorators.py", line 27, in new_func return f(get_current_context().obj, *args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/pierone/cli.py", line 313, in cves installed_software = get_clair_features(config.get('clair_url'), artifact_tag.get('clair_id'), token) File "/usr/local/lib/python3.4/dist-packages/pierone/cli.py", line 235, in get_clair_features return r.json()['Layer']['Features'] KeyError: 'Features' ```
zalando-stups/pierone-cli
diff --git a/tests/test_cli.py b/tests/test_cli.py index 6282253..087d27d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -221,6 +221,61 @@ def test_cves(monkeypatch, tmpdir): assert re.match('[^\n]+\n[^\n]+HIGH', result.output), 'Results should be ordered by highest priority' +def test_no_cves_found(monkeypatch, tmpdir): + pierone_service_payload = [ + # Former pierone payload + { + 'name': '1.0', + 'created_by': 'myuser', + 'created': '2015-08-20T08:14:59.432Z' + }, + # New pierone payload with clair but no information about CVEs + { + "name": "1.1", + "created": "2016-05-19T15:23:41.065Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": None, + "severity_fix_available": None, + "severity_no_fix_available": None + }, + # New pierone payload with clair input and info about CVEs + { + "name": "1.2", + "created": "2016-05-23T13:29:17.753Z", + "created_by": "myuser", + "image": "sha256:here", + "clair_id": "sha256:here", + "severity_fix_available": "High", + "severity_no_fix_available": "Medium" + } + ] + + no_cves_clair_payload = { + "Layer": { + "Name": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "NamespaceName": "ubuntu:16.04", + "ParentName": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "IndexedByVersion": 2 + } + } + + response = MagicMock() + response.json.side_effect = [ + pierone_service_payload, + no_cves_clair_payload + ] + + runner = CliRunner() + monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar', 'clair_url': 'barfoo'}) + monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123')) + monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir))) + monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response)) + with runner.isolated_filesystem(): + result = runner.invoke(cli, ['cves', 'myteam', 'myart', '1.2'], catch_exceptions=False) + assert re.match('^[^\n]+\n$', result.output), 'No results should be shown' + + def test_latest(monkeypatch, tmpdir): response = MagicMock() response.json.return_value = [
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 clickclick==20.10.2 coverage==7.8.0 dnspython==2.7.0 exceptiongroup==1.2.2 execnet==2.1.1 idna==3.10 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 PyYAML==6.0.2 requests==2.32.3 stups-cli-support==1.1.22 -e git+https://github.com/zalando-stups/pierone-cli.git@991c05e9c7496b2aac071d85d0a9ca6b8afcf9dd#egg=stups_pierone stups-tokens==1.1.19 stups-zign==1.2 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0
name: pierone-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - clickclick==20.10.2 - coverage==7.8.0 - dnspython==2.7.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - pyyaml==6.0.2 - requests==2.32.3 - stups-cli-support==1.1.22 - stups-tokens==1.1.19 - stups-zign==1.2 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 prefix: /opt/conda/envs/pierone-cli
[ "tests/test_cli.py::test_no_cves_found" ]
[]
[ "tests/test_cli.py::test_version", "tests/test_cli.py::test_login", "tests/test_cli.py::test_login_given_url_option", "tests/test_cli.py::test_scm_source", "tests/test_cli.py::test_image", "tests/test_cli.py::test_tags", "tests/test_cli.py::test_cves", "tests/test_cli.py::test_latest", "tests/test_cli.py::test_latest_not_found", "tests/test_cli.py::test_url_without_scheme" ]
[]
Apache License 2.0
565
networkx__networkx-2150
df730d96d6490079a6b6fcf3a2bea64324aef02e
2016-05-31 19:16:42
3f4fd85765bf2d88188cfd4c84d0707152e6cd1e
diff --git a/doc/source/reference/classes.multidigraph.rst b/doc/source/reference/classes.multidigraph.rst index ab613964a..ef34f4664 100644 --- a/doc/source/reference/classes.multidigraph.rst +++ b/doc/source/reference/classes.multidigraph.rst @@ -28,6 +28,7 @@ Adding and Removing Nodes and Edges MultiDiGraph.add_edge MultiDiGraph.add_edges_from MultiDiGraph.add_weighted_edges_from + MultiDiGraph.new_edge_key MultiDiGraph.remove_edge MultiDiGraph.remove_edges_from MultiDiGraph.clear diff --git a/doc/source/reference/classes.multigraph.rst b/doc/source/reference/classes.multigraph.rst index 1d598ccfd..5d3984986 100644 --- a/doc/source/reference/classes.multigraph.rst +++ b/doc/source/reference/classes.multigraph.rst @@ -27,6 +27,7 @@ Adding and removing nodes and edges MultiGraph.add_edge MultiGraph.add_edges_from MultiGraph.add_weighted_edges_from + MultiGraph.new_edge_key MultiGraph.remove_edge MultiGraph.remove_edges_from MultiGraph.clear diff --git a/doc/source/tutorial/tutorial.rst b/doc/source/tutorial/tutorial.rst index c86741f95..3875c1a65 100644 --- a/doc/source/tutorial/tutorial.rst +++ b/doc/source/tutorial/tutorial.rst @@ -388,8 +388,8 @@ functions such as: >>> G.add_edges_from([(1,2),(1,3)]) >>> G.add_node("spam") # adds node "spam" ->>> list(nx.connected_components(G)) -[{1, 2, 3}, {'spam'}] +>>> nx.connected_components(G) +[[1, 2, 3], ['spam']] >>> sorted(d for n, d in G.degree()) [0, 1, 1, 2] diff --git a/networkx/algorithms/centrality/eigenvector.py b/networkx/algorithms/centrality/eigenvector.py index a73611c37..f7fac9601 100644 --- a/networkx/algorithms/centrality/eigenvector.py +++ b/networkx/algorithms/centrality/eigenvector.py @@ -78,11 +78,6 @@ def eigenvector_centrality(G, max_iter=100, tol=1.0e-6, nstart=None, NetworkXError If each value in `nstart` is zero. - PowerIterationFailedConvergence - If the algorithm fails to converge to the specified tolerance - within the specified number of iterations of the power iteration - method. - See Also -------- eigenvector_centrality_numpy @@ -146,7 +141,8 @@ def eigenvector_centrality(G, max_iter=100, tol=1.0e-6, nstart=None, # Check for convergence (in the L_1 norm). if sum(abs(x[n] - xlast[n]) for n in x) < nnodes * tol: return x - raise nx.PowerIterationFailedConvergence(max_iter) + raise nx.NetworkXError('power iteration failed to converge within {}' + ' iterations'.format(max_iter)) def eigenvector_centrality_numpy(G, weight='weight', max_iter=50, tol=0): diff --git a/networkx/algorithms/centrality/katz.py b/networkx/algorithms/centrality/katz.py index 39ec75f44..537c8a3af 100644 --- a/networkx/algorithms/centrality/katz.py +++ b/networkx/algorithms/centrality/katz.py @@ -94,11 +94,6 @@ def katz_centrality(G, alpha=0.1, beta=1.0, If the parameter `beta` is not a scalar but lacks a value for at least one node - PowerIterationFailedConvergence - If the algorithm fails to converge to the specified tolerance - within the specified number of iterations of the power iteration - method. - Examples -------- >>> import math @@ -195,8 +190,9 @@ def katz_centrality(G, alpha=0.1, beta=1.0, for n in x: x[n] *= s return x - raise nx.PowerIterationFailedConvergence(max_iter) + raise nx.NetworkXError('Power iteration failed to converge in ' + '%d iterations.' % max_iter) @not_implemented_for('multigraph') def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, diff --git a/networkx/algorithms/community/community_generators.py b/networkx/algorithms/community/community_generators.py index a12fe87db..3cdb948b2 100644 --- a/networkx/algorithms/community/community_generators.py +++ b/networkx/algorithms/community/community_generators.py @@ -77,7 +77,7 @@ def _powerlaw_sequence(gamma, low, high, condition, length, max_iters): ``max_iters`` indicates the number of times to generate a list satisfying ``length``. If the number of iterations exceeds this - value, :exc:`~networkx.exception.ExceededMaxIterations` is raised. + value, :exc:`~networkx.exception.NetworkXError` is raised. """ for i in range(max_iters): @@ -86,7 +86,7 @@ def _powerlaw_sequence(gamma, low, high, condition, length, max_iters): seq.append(_zipf_rv_below(gamma, low, high)) if condition(seq): return seq - raise nx.ExceededMaxIterations("Could not create power law sequence") + raise nx.NetworkXError("Could not create power law sequence") # TODO Needs documentation. @@ -100,7 +100,7 @@ def _generate_min_degree(gamma, average_degree, max_degree, tolerance, mid_avg_deg = 0 while abs(mid_avg_deg - average_degree) > tolerance: if itrs > max_iters: - raise nx.ExceededMaxIterations("Could not match average_degree") + raise nx.NetworkXError("Could not match average_degree") mid_avg_deg = 0 for x in range(int(min_deg_mid), max_degree + 1): mid_avg_deg += (x ** (-gamma + 1)) / zeta(gamma, min_deg_mid, @@ -129,11 +129,15 @@ def _generate_communities(degree_sequence, community_sizes, mu, max_iters): ``mu`` is a float in the interval [0, 1] indicating the fraction of intra-community edges incident to each node. + ``max_iters`` indicates the number of times to generate a list + satisfying ``length``. If the number of iterations exceeds this + value, :exc:`~networkx.exception.NetworkXError` is raised. + ``max_iters`` is the number of times to try to add a node to a community. This must be greater than the length of ``degree_sequence``, otherwise this function will always fail. If the number of iterations exceeds this value, - :exc:`~networkx.exception.ExceededMaxIterations` is raised. + :exc:`~networkx.exception.NetworkXError` is raised. The communities returned by this are sets of integers in the set {0, ..., *n* - 1}, where *n* is the length of ``degree_sequence``. @@ -160,8 +164,8 @@ def _generate_communities(degree_sequence, community_sizes, mu, max_iters): free.append(result[c].pop()) if not free: return result - msg = 'Could not assign communities; try increasing min_community' - raise nx.ExceededMaxIterations(msg) + raise nx.NetworkXError('Could not assign communities; try increasing' + ' min_community') def LFR_benchmark_graph(n, tau1, tau2, mu, average_degree=None, @@ -280,7 +284,6 @@ def LFR_benchmark_graph(n, tau1, tau2, mu, average_degree=None, If ``min_degree`` is not specified and a suitable ``min_degree`` cannot be found. - ExceededMaxIterations If a valid degree sequence cannot be created within ``max_iters`` number of iterations. diff --git a/networkx/algorithms/isomorphism/isomorph.py b/networkx/algorithms/isomorphism/isomorph.py index 8f1d4a478..42ff26496 100644 --- a/networkx/algorithms/isomorphism/isomorph.py +++ b/networkx/algorithms/isomorphism/isomorph.py @@ -186,7 +186,9 @@ def is_isomorphic(G1, G2, node_match=None, edge_match=None): For multidigraphs G1 and G2, using 'weight' edge attribute (default: 7) >>> G1.add_edge(1,2, weight=7) + 1 >>> G2.add_edge(10,20) + 1 >>> em = iso.numerical_multiedge_match('weight', 7, rtol=1e-6) >>> nx.is_isomorphic(G1, G2, edge_match=em) True diff --git a/networkx/algorithms/link_analysis/hits_alg.py b/networkx/algorithms/link_analysis/hits_alg.py index 2ca56beaf..7325352c4 100644 --- a/networkx/algorithms/link_analysis/hits_alg.py +++ b/networkx/algorithms/link_analysis/hits_alg.py @@ -42,13 +42,6 @@ def hits(G,max_iter=100,tol=1.0e-8,nstart=None,normalized=True): Two dictionaries keyed by node containing the hub and authority values. - Raises - ------ - PowerIterationFailedConvergence - If the algorithm fails to converge to the specified tolerance - within the specified number of iterations of the power iteration - method. - Examples -------- >>> G=nx.path_graph(4) @@ -89,7 +82,8 @@ def hits(G,max_iter=100,tol=1.0e-8,nstart=None,normalized=True): s=1.0/sum(h.values()) for k in h: h[k]*=s - for _ in range(max_iter): # power iteration: make up to max_iter iterations + i=0 + while True: # power iteration: make up to max_iter iterations hlast=h h=dict.fromkeys(hlast.keys(),0) a=dict.fromkeys(hlast.keys(),0) @@ -112,8 +106,10 @@ def hits(G,max_iter=100,tol=1.0e-8,nstart=None,normalized=True): err=sum([abs(h[n]-hlast[n]) for n in h]) if err < tol: break - else: - raise nx.PowerIterationFailedConvergence(max_iter) + if i>max_iter: + raise NetworkXError(\ + "HITS: power iteration failed to converge in %d iterations."%(i+1)) + i+=1 if normalized: s = 1.0/sum(a.values()) for n in a: @@ -251,13 +247,6 @@ def hits_scipy(G,max_iter=100,tol=1.0e-6,normalized=True): algorithm does not check if the input graph is directed and will execute on undirected graphs. - Raises - ------ - PowerIterationFailedConvergence - If the algorithm fails to converge to the specified tolerance - within the specified number of iterations of the power iteration - method. - References ---------- .. [1] A. Langville and C. Meyer, @@ -292,7 +281,8 @@ def hits_scipy(G,max_iter=100,tol=1.0e-6,normalized=True): if err < tol: break if i>max_iter: - raise nx.PowerIterationFailedConvergence(max_iter) + raise NetworkXError(\ + "HITS: power iteration failed to converge in %d iterations."%(i+1)) i+=1 a=np.asarray(x).flatten() diff --git a/networkx/algorithms/link_analysis/pagerank_alg.py b/networkx/algorithms/link_analysis/pagerank_alg.py index a105f8f28..050179075 100644 --- a/networkx/algorithms/link_analysis/pagerank_alg.py +++ b/networkx/algorithms/link_analysis/pagerank_alg.py @@ -35,8 +35,7 @@ def pagerank(G, alpha=0.85, personalization=None, personalization: dict, optional The "personalization vector" consisting of a dictionary with a - key for every graph node and personalization value for each node. - At least one personalization value must be non-zero. + key for every graph node and nonzero personalization value for each node. By default, a uniform distribution is used. max_iter : integer, optional @@ -73,11 +72,9 @@ def pagerank(G, alpha=0.85, personalization=None, Notes ----- The eigenvector calculation is done by the power iteration method - and has no guarantee of convergence. The iteration will stop after - an error tolerance of ``len(G) * tol`` has been reached. If the - number of iterations exceed `max_iter`, a - :exc:`networkx.exception.PowerIterationFailedConvergence` exception - is raised. + and has no guarantee of convergence. The iteration will stop + after max_iter iterations or an error tolerance of + number_of_nodes(G)*tol has been reached. The PageRank algorithm was designed for directed graphs but this algorithm does not check if the input graph is directed and will @@ -88,13 +85,6 @@ def pagerank(G, alpha=0.85, personalization=None, -------- pagerank_numpy, pagerank_scipy, google_matrix - Raises - ------ - PowerIterationFailedConvergence - If the algorithm fails to converge to the specified tolerance - within the specified number of iterations of the power iteration - method. - References ---------- .. [1] A. Langville and C. Meyer, @@ -103,7 +93,6 @@ def pagerank(G, alpha=0.85, personalization=None, .. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry, The PageRank citation ranking: Bringing order to the Web. 1999 http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf - """ if len(G) == 0: return {} @@ -165,7 +154,8 @@ def pagerank(G, alpha=0.85, personalization=None, err = sum([abs(x[n] - xlast[n]) for n in x]) if err < N*tol: return x - raise nx.PowerIterationFailedConvergence(max_iter) + raise NetworkXError('pagerank: power iteration failed to converge ' + 'in %d iterations.' % max_iter) def google_matrix(G, alpha=0.85, personalization=None, @@ -415,13 +405,6 @@ def pagerank_scipy(G, alpha=0.85, personalization=None, -------- pagerank, pagerank_numpy, google_matrix - Raises - ------ - PowerIterationFailedConvergence - If the algorithm fails to converge to the specified tolerance - within the specified number of iterations of the power iteration - method. - References ---------- .. [1] A. Langville and C. Meyer, @@ -485,7 +468,8 @@ def pagerank_scipy(G, alpha=0.85, personalization=None, err = scipy.absolute(x - xlast).sum() if err < N * tol: return dict(zip(nodelist, map(float, x))) - raise nx.PowerIterationFailedConvergence(max_iter) + raise NetworkXError('pagerank_scipy: power iteration failed to converge ' + 'in %d iterations.' % max_iter) # fixture for nose tests diff --git a/networkx/algorithms/traversal/depth_first_search.py b/networkx/algorithms/traversal/depth_first_search.py index 73897cf1c..2b5cea636 100644 --- a/networkx/algorithms/traversal/depth_first_search.py +++ b/networkx/algorithms/traversal/depth_first_search.py @@ -69,7 +69,7 @@ def dfs_edges(G, source=None): except StopIteration: stack.pop() -def dfs_tree(G, source=None): +def dfs_tree(G, source): """Return oriented tree constructed from a depth-first-search from source. Parameters diff --git a/networkx/classes/multidigraph.py b/networkx/classes/multidigraph.py index 22bfed174..2b850483c 100644 --- a/networkx/classes/multidigraph.py +++ b/networkx/classes/multidigraph.py @@ -83,22 +83,22 @@ class MultiDiGraph(MultiGraph,DiGraph): Add one edge, - >>> G.add_edge(1, 2) + >>> key = G.add_edge(1, 2) a list of edges, - >>> G.add_edges_from([(1,2),(1,3)]) + >>> keys = G.add_edges_from([(1,2),(1,3)]) or a collection of edges, - >>> G.add_edges_from(H.edges()) + >>> keys = G.add_edges_from(H.edges()) If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists, an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused integer. - >>> G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))]) + >>> keys = G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))]) >>> G[4] {5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}} @@ -130,9 +130,9 @@ class MultiDiGraph(MultiGraph,DiGraph): Add edge attributes using add_edge(), add_edges_from(), subscript notation, or G.edge. - >>> G.add_edge(1, 2, weight=4.7 ) - >>> G.add_edges_from([(3,4),(4,5)], color='red') - >>> G.add_edges_from([(1,2,{'color':'blue'}), (2,3,{'weight':8})]) + >>> key = G.add_edge(1, 2, weight=4.7 ) + >>> keys = G.add_edges_from([(3,4),(4,5)], color='red') + >>> keys = G.add_edges_from([(1,2,{'color':'blue'}), (2,3,{'weight':8})]) >>> G[1][2][0]['weight'] = 4.7 >>> G.edge[1][2][0]['weight'] = 4 @@ -222,7 +222,7 @@ class MultiDiGraph(MultiGraph,DiGraph): >>> G.add_nodes_from( (2,1) ) >>> list(G.nodes()) [2, 1] - >>> G.add_edges_from( ((2,2), (2,1), (2,1), (1,1)) ) + >>> keys = G.add_edges_from( ((2,2), (2,1), (2,1), (1,1)) ) >>> list(G.edges()) [(2, 1), (2, 1), (2, 2), (1, 1)] @@ -238,7 +238,8 @@ class MultiDiGraph(MultiGraph,DiGraph): >>> G.add_nodes_from( (2,1) ) >>> list(G.nodes()) [2, 1] - >>> G.add_edges_from( ((2,2), (2,1,2,{'weight':0.1}), (2,1,1,{'weight':0.2}), (1,1)) ) + >>> elist = ((2,2), (2,1,2,{'weight':0.1}), (2,1,1,{'weight':0.2}), (1,1)) + >>> keys = G.add_edges_from(elist) >>> list(G.edges(keys=True)) [(2, 2, 0), (2, 1, 2), (2, 1, 1), (1, 1, 0)] @@ -275,6 +276,10 @@ class MultiDiGraph(MultiGraph,DiGraph): Edge data (or labels or objects) can be assigned using keyword arguments. + Returns + ------- + The edge key assigned to the edge. + See Also -------- add_edges_from : add a collection of edges @@ -289,21 +294,27 @@ class MultiDiGraph(MultiGraph,DiGraph): multiedge weights. Convert to Graph using edge attribute 'weight' to enable weighted graph algorithms. + Default keys are generated using the method `new_edge_key()`. + This method can be overridden by subclassing the base class and + providing a custom `new_edge_key()` method. + Examples -------- The following all add the edge e=(1,2) to graph G: >>> G = nx.MultiDiGraph() >>> e = (1,2) - >>> G.add_edge(1, 2) # explicit two-node form + >>> key = G.add_edge(1, 2) # explicit two-node form >>> G.add_edge(*e) # single edge as tuple of two nodes + 1 >>> G.add_edges_from( [(1,2)] ) # add edges from iterable container + [2] Associate data to edges using keywords: - >>> G.add_edge(1, 2, weight=3) - >>> G.add_edge(1, 2, key=0, weight=4) # update data for key=0 - >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7) + >>> key = G.add_edge(1, 2, weight=3) + >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0 + >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7) For non-string associations, directly access the edge's attribute dictionary. @@ -317,27 +328,22 @@ class MultiDiGraph(MultiGraph,DiGraph): self.succ[v] = self.adjlist_dict_factory() self.pred[v] = self.adjlist_dict_factory() self.node[v] = {} + if key is None: + key = self.new_edge_key(u, v) if v in self.succ[u]: keydict = self.adj[u][v] - if key is None: - # find a unique integer key - # other methods might be better here? - key = len(keydict) - while key in keydict: - key += 1 datadict = keydict.get(key, self.edge_key_dict_factory()) datadict.update(attr) keydict[key] = datadict else: # selfloops work this way without special treatment - if key is None: - key = 0 datadict = self.edge_attr_dict_factory() datadict.update(attr) keydict = self.edge_key_dict_factory() keydict[key] = datadict self.succ[u][v] = keydict self.pred[v][u] = keydict + return key def remove_edge(self, u, v, key=None): @@ -372,14 +378,17 @@ class MultiDiGraph(MultiGraph,DiGraph): For multiple edges >>> G = nx.MultiDiGraph() - >>> G.add_edges_from([(1,2),(1,2),(1,2)]) + >>> G.add_edges_from([(1,2),(1,2),(1,2)]) # key_list returned + [0, 1, 2] >>> G.remove_edge(1,2) # remove a single (arbitrary) edge For edges with keys >>> G = nx.MultiDiGraph() >>> G.add_edge(1,2,key='first') + 'first' >>> G.add_edge(1,2,key='second') + 'second' >>> G.remove_edge(1,2,key='second') """ @@ -437,7 +446,7 @@ class MultiDiGraph(MultiGraph,DiGraph): -------- >>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2]) - >>> G.add_edge(2,3,weight=5) + >>> key = G.add_edge(2,3,weight=5) >>> [e for e in G.edges()] [(0, 1), (1, 2), (2, 3)] >>> list(G.edges(data=True)) # default data is {} (empty dict) @@ -795,7 +804,7 @@ class MultiDiGraph(MultiGraph,DiGraph): If already directed, return a (deep) copy >>> G = nx.MultiDiGraph() - >>> G.add_edge(0, 1) + >>> key = G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges()) [(0, 1)] @@ -833,7 +842,7 @@ class MultiDiGraph(MultiGraph,DiGraph): See the Python copy module for more information on shallow and deep copies, http://docs.python.org/library/copy.html. - Warning: If you have subclassed MultiGraph to use dict-like objects + Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiDiGraph created by this method. @@ -964,10 +973,10 @@ class MultiDiGraph(MultiGraph,DiGraph): >>> # Create a graph in which some edges are "good" and some "bad". >>> G = nx.MultiDiGraph() - >>> G.add_edge(0, 1, key=0, good=True) - >>> G.add_edge(0, 1, key=1, good=False) - >>> G.add_edge(1, 2, key=0, good=False) - >>> G.add_edge(1, 2, key=1, good=True) + >>> key = G.add_edge(0, 1, key=0, good=True) + >>> key = G.add_edge(0, 1, key=1, good=False) + >>> key = G.add_edge(1, 2, key=0, good=False) + >>> key = G.add_edge(1, 2, key=1, good=True) >>> # Keep only those edges that are marked as "good". >>> edges = G.edges(keys=True, data='good') >>> edges = ((u, v, k) for (u, v, k, good) in edges if good) diff --git a/networkx/classes/multigraph.py b/networkx/classes/multigraph.py index d6f925d0c..0b58059d7 100644 --- a/networkx/classes/multigraph.py +++ b/networkx/classes/multigraph.py @@ -82,22 +82,22 @@ class MultiGraph(Graph): Add one edge, - >>> G.add_edge(1, 2) + >>> key = G.add_edge(1, 2) a list of edges, - >>> G.add_edges_from([(1,2),(1,3)]) + >>> keys = G.add_edges_from([(1,2),(1,3)]) or a collection of edges, - >>> G.add_edges_from(list(H.edges())) + >>> keys = G.add_edges_from(list(H.edges())) If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists, an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused integer. - >>> G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))]) + >>> keys = G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))]) >>> G[4] {3: {0: {}}, 5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}} @@ -129,9 +129,9 @@ class MultiGraph(Graph): Add edge attributes using add_edge(), add_edges_from(), subscript notation, or G.edge. - >>> G.add_edge(1, 2, weight=4.7 ) - >>> G.add_edges_from([(3,4),(4,5)], color='red') - >>> G.add_edges_from([(1,2,{'color':'blue'}), (2,3,{'weight':8})]) + >>> key = G.add_edge(1, 2, weight=4.7 ) + >>> keys = G.add_edges_from([(3,4),(4,5)], color='red') + >>> keys = G.add_edges_from([(1,2,{'color':'blue'}), (2,3,{'weight':8})]) >>> G[1][2][0]['weight'] = 4.7 >>> G.edge[1][2][0]['weight'] = 4 @@ -223,7 +223,7 @@ class MultiGraph(Graph): >>> G.add_nodes_from( (2,1) ) >>> list(G.nodes()) [2, 1] - >>> G.add_edges_from( ((2,2), (2,1), (2,1), (1,1)) ) + >>> keys = G.add_edges_from( ((2,2), (2,1), (2,1), (1,1)) ) >>> list(G.edges()) [(2, 1), (2, 1), (2, 2), (1, 1)] @@ -239,7 +239,8 @@ class MultiGraph(Graph): >>> G.add_nodes_from( (2,1) ) >>> list(G.nodes()) [2, 1] - >>> G.add_edges_from( ((2,2), (2,1,2,{'weight':0.1}), (2,1,1,{'weight':0.2}), (1,1)) ) + >>> elist = ((2,2), (2,1,2,{'weight':0.1}), (2,1,1,{'weight':0.2}), (1,1)) + >>> keys = G.add_edges_from(elist) >>> list(G.edges(keys=True)) [(2, 2, 0), (2, 1, 2), (2, 1, 1), (1, 1, 0)] @@ -253,6 +254,36 @@ class MultiGraph(Graph): self.edge_key_dict_factory = self.edge_key_dict_factory Graph.__init__(self, data, **attr) + def new_edge_key(self, u, v): + """Return an unused key for edges between nodes `u` and `v`. + + The nodes `u` and `v` do not need to be already in the graph. + + Notes + ----- + + In the standard MultiGraph class the new key is the number of existing + edges between `u` and `v` (increased if necessary to ensure unused). + The first edge will have key 0, then 1, etc. If an edge is removed + further new_edge_keys may not be in this order. + + Parameters + ---------- + u, v : nodes + + Returns + ------- + key : int + """ + try: + keydict = self.adj[u][v] + except KeyError: + return 0 + key = len(keydict) + while key in keydict: + key += 1 + return key + def add_edge(self, u, v, key=None, **attr): """Add an edge between u and v. @@ -273,6 +304,10 @@ class MultiGraph(Graph): Edge data (or labels or objects) can be assigned using keyword arguments. + Returns + ------- + The edge key assigned to the edge. + See Also -------- add_edges_from : add a collection of edges @@ -287,6 +322,10 @@ class MultiGraph(Graph): multiedge weights. Convert to Graph using edge attribute 'weight' to enable weighted graph algorithms. + Default keys are generated using the method `new_edge_key()`. + This method can be overridden by subclassing the base class and + providing a custom `new_edge_key()` method. + Examples -------- The following all add the edge e=(1,2) to graph G: @@ -310,27 +349,22 @@ class MultiGraph(Graph): if v not in self.adj: self.adj[v] = self.adjlist_dict_factory() self.node[v] = {} + if key is None: + key = self.new_edge_key(u, v) if v in self.adj[u]: keydict = self.adj[u][v] - if key is None: - # find a unique integer key - # other methods might be better here? - key = len(keydict) - while key in keydict: - key += 1 datadict = keydict.get(key, self.edge_attr_dict_factory()) datadict.update(attr) keydict[key] = datadict else: # selfloops work this way without special treatment - if key is None: - key = 0 datadict = self.edge_attr_dict_factory() datadict.update(attr) keydict = self.edge_key_dict_factory() keydict[key] = datadict self.adj[u][v] = keydict self.adj[v][u] = keydict + return key def add_edges_from(self, ebunch, **attr): """Add all the edges in ebunch. @@ -349,6 +383,10 @@ class MultiGraph(Graph): Edge data (or labels or objects) can be assigned using keyword arguments. + Returns + ------- + A list of edge keys assigned to the edges in `ebunch`. + See Also -------- add_edge : add a single edge @@ -359,9 +397,13 @@ class MultiGraph(Graph): Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added. - Edge attributes specified in an ebunch take precedence over + Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments. + Default keys are generated using the method ``new_edge_key()``. + This method can be overridden by subclassing the base class and + providing a custom ``new_edge_key()`` method. + Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc @@ -374,6 +416,7 @@ class MultiGraph(Graph): >>> G.add_edges_from([(1,2),(2,3)], weight=3) >>> G.add_edges_from([(3,4),(1,4)], label='WN2898') """ + keylist=[] # process ebunch for e in ebunch: ne = len(e) @@ -392,15 +435,10 @@ class MultiGraph(Graph): ddd = {} ddd.update(attr) ddd.update(dd) - if key is None: - k = 0 - if u in self and v in self[u]: - while k in self[u][v]: - k += 1 - else: - k = key - self.add_edge(u, v, k) - self[u][v][k].update(ddd) + key = self.add_edge(u, v, key) + self[u][v][key].update(ddd) + keylist.append(key) + return keylist def remove_edge(self, u, v, key=None): """Remove an edge between u and v. @@ -434,14 +472,17 @@ class MultiGraph(Graph): For multiple edges >>> G = nx.MultiGraph() # or MultiDiGraph, etc - >>> G.add_edges_from([(1,2),(1,2),(1,2)]) + >>> G.add_edges_from([(1,2),(1,2),(1,2)]) # key_list returned + [0, 1, 2] >>> G.remove_edge(1,2) # remove a single (arbitrary) edge For edges with keys >>> G = nx.MultiGraph() # or MultiDiGraph, etc >>> G.add_edge(1,2,key='first') + 'first' >>> G.add_edge(1,2,key='second') + 'second' >>> G.remove_edge(1,2,key='second') """ @@ -496,7 +537,7 @@ class MultiGraph(Graph): Removing multiple copies of edges >>> G = nx.MultiGraph() - >>> G.add_edges_from([(1,2),(1,2),(1,2)]) + >>> keys = G.add_edges_from([(1,2),(1,2),(1,2)]) >>> G.remove_edges_from([(1,2),(1,2)]) >>> list(G.edges()) [(1, 2)] @@ -540,6 +581,7 @@ class MultiGraph(Graph): >>> G.has_edge(*e) # e is a 2-tuple (u,v) True >>> G.add_edge(0,1,key='a') + 'a' >>> G.has_edge(0,1,key='a') # specify key True >>> e=(0,1,'a') @@ -600,7 +642,7 @@ class MultiGraph(Graph): -------- >>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2]) - >>> G.add_edge(2,3,weight=5) + >>> key = G.add_edge(2,3,weight=5) >>> [e for e in G.edges()] [(0, 1), (1, 2), (2, 3)] >>> list(G.edges(data=True)) # default data is {} (empty dict) @@ -672,7 +714,7 @@ class MultiGraph(Graph): It is faster to use G[u][v][key]. >>> G = nx.MultiGraph() # or MultiDiGraph - >>> G.add_edge(0,1,key='a',weight=7) + >>> key = G.add_edge(0,1,key='a',weight=7) >>> G[0][1]['a'] # key='a' {'weight': 7} @@ -868,7 +910,9 @@ class MultiGraph(Graph): -------- >>> G = nx.MultiGraph() # or MultiDiGraph >>> G.add_edge(1,1) + 0 >>> G.add_edge(1,2) + 0 >>> list(G.selfloop_edges()) [(1, 1)] >>> list(G.selfloop_edges(data=True)) @@ -1048,10 +1092,10 @@ class MultiGraph(Graph): >>> # Create a graph in which some edges are "good" and some "bad". >>> G = nx.MultiGraph() - >>> G.add_edge(0, 1, key=0, good=True) - >>> G.add_edge(0, 1, key=1, good=False) - >>> G.add_edge(1, 2, key=0, good=False) - >>> G.add_edge(1, 2, key=1, good=True) + >>> key = G.add_edge(0, 1, key=0, good=True) + >>> key = G.add_edge(0, 1, key=1, good=False) + >>> key = G.add_edge(1, 2, key=0, good=False) + >>> key = G.add_edge(1, 2, key=1, good=True) >>> # Keep only those edges that are marked as "good". >>> edges = G.edges(keys=True, data='good') >>> edges = ((u, v, k) for (u, v, k, good) in edges if good) diff --git a/networkx/convert_matrix.py b/networkx/convert_matrix.py index 3aab7db79..c89704c79 100644 --- a/networkx/convert_matrix.py +++ b/networkx/convert_matrix.py @@ -105,9 +105,13 @@ def to_pandas_dataframe(G, nodelist=None, dtype=None, order=None, -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0,1,weight=2) + 0 >>> G.add_edge(1,0) + 0 >>> G.add_edge(2,2,weight=3) + 0 >>> G.add_edge(2,2) + 1 >>> nx.to_pandas_dataframe(G, nodelist=[0,1,2], dtype=int) 0 1 2 0 0 2 0 @@ -304,9 +308,13 @@ def to_numpy_matrix(G, nodelist=None, dtype=None, order=None, -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0,1,weight=2) + 0 >>> G.add_edge(1,0) + 0 >>> G.add_edge(2,2,weight=3) + 0 >>> G.add_edge(2,2) + 1 >>> nx.to_numpy_matrix(G, nodelist=[0,1,2]) matrix([[ 0., 2., 0.], [ 1., 0., 0.], @@ -680,9 +688,13 @@ def to_scipy_sparse_matrix(G, nodelist=None, dtype=None, -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0,1,weight=2) + 0 >>> G.add_edge(1,0) + 0 >>> G.add_edge(2,2,weight=3) + 0 >>> G.add_edge(2,2) + 1 >>> S = nx.to_scipy_sparse_matrix(G, nodelist=[0,1,2]) >>> print(S.todense()) [[0 2 0] diff --git a/networkx/drawing/layout.py b/networkx/drawing/layout.py index 8dbb77262..872787d04 100644 --- a/networkx/drawing/layout.py +++ b/networkx/drawing/layout.py @@ -139,7 +139,7 @@ def circular_layout(G, scale=1, center=None, dim=2): if len(G) == 0: pos = {} elif len(G) == 1: - pos = {nx.utils.arbitrary_element(G): center} + pos = {G.nodes()[0]: center} else: # Discard the extra angle since it matches 0 radians. theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi @@ -287,7 +287,7 @@ def fruchterman_reingold_layout(G, k=None, if pos is not None: # Determine size of existing domain to adjust initial positions - dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup) + dom_size = max(coord for coord in pos_tup for pos_tup in pos.values()) shape = (len(G), dim) pos_arr = np.random.random(shape) * dom_size + center for i, n in enumerate(G): diff --git a/networkx/exception.py b/networkx/exception.py index 01aec88b1..7d0880248 100644 --- a/networkx/exception.py +++ b/networkx/exception.py @@ -55,29 +55,3 @@ class NetworkXNotImplemented(NetworkXException): class NodeNotFound(NetworkXException): """Exception raised if requested node is not present in the graph""" - - -class ExceededMaxIterations(NetworkXException): - """Raised if a loop iterates too many times without breaking. - - This may occur, for example, in an algorithm that computes - progressively better approximations to a value but exceeds an - iteration bound specified by the user. - - """ - - -class PowerIterationFailedConvergence(ExceededMaxIterations): - """Raised when the power iteration method fails to converge within a - specified iteration limit. - - `num_iterations` is the number of iterations that have been - completed when this exception was raised. - - """ - - def __init__(self, num_iterations, *args, **kw): - msg = 'power iteration failed to converge within {} iterations' - msg = msg.format(num_iterations) - superinit = super(PowerIterationFailedConvergence, self).__init__ - superinit(self, msg, *args, **kw)
Multigraph key simplification? It seems that the way we handle multigraph edge keys is sometimes hard to maintain (see #2107 but true elsewhere too). Is there a way to handle it more simply? Some thoughts include: - defaulting to ```key=None``` for all add_edge actions. The first ```G.add_edge(1,2)``` gives ```(1,2,None)```. The second does nothing! To get a multiedge one must specify a key. - default to using a UUID for the key to each multiedge. (unique key within the MultiGraph and actually across all MultiGraphs). Here ```G.add_edge(1,2)``` twice does add two separate edges. Other thoughts?
networkx/networkx
diff --git a/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py b/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py index babe0039c..465415f32 100644 --- a/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py +++ b/networkx/algorithms/centrality/tests/test_eigenvector_centrality.py @@ -56,7 +56,7 @@ class TestEigenvectorCentrality(object): - @raises(nx.PowerIterationFailedConvergence) + @raises(nx.NetworkXError) def test_maxiter(self): G=nx.path_graph(3) b=nx.eigenvector_centrality(G,max_iter=0) diff --git a/networkx/algorithms/centrality/tests/test_katz_centrality.py b/networkx/algorithms/centrality/tests/test_katz_centrality.py index 8886711e3..69b015f12 100644 --- a/networkx/algorithms/centrality/tests/test_katz_centrality.py +++ b/networkx/algorithms/centrality/tests/test_katz_centrality.py @@ -30,7 +30,7 @@ class TestKatzCentrality(object): for n in sorted(G): assert_almost_equal(b[n], b_answer[n], places=4) - @raises(nx.PowerIterationFailedConvergence) + @raises(nx.NetworkXError) def test_maxiter(self): alpha = 0.1 G = nx.path_graph(3) diff --git a/networkx/algorithms/link_analysis/tests/test_hits.py b/networkx/algorithms/link_analysis/tests/test_hits.py index b8849bc7a..7092d1dfd 100644 --- a/networkx/algorithms/link_analysis/tests/test_hits.py +++ b/networkx/algorithms/link_analysis/tests/test_hits.py @@ -91,9 +91,3 @@ class TestHITS: raise SkipTest('scipy not available.') G=networkx.Graph() assert_equal(networkx.hits_scipy(G),({},{})) - - - @raises(networkx.PowerIterationFailedConvergence) - def test_hits_not_convergent(self): - G = self.G - networkx.hits(G, max_iter=0) diff --git a/networkx/algorithms/link_analysis/tests/test_pagerank.py b/networkx/algorithms/link_analysis/tests/test_pagerank.py index a64899d5f..d27ea2454 100644 --- a/networkx/algorithms/link_analysis/tests/test_pagerank.py +++ b/networkx/algorithms/link_analysis/tests/test_pagerank.py @@ -52,9 +52,8 @@ class TestPageRank(object): for n in G: assert_almost_equal(p[n], G.pagerank[n], places=4) - @raises(networkx.PowerIterationFailedConvergence) - def test_pagerank_max_iter(self): - networkx.pagerank(self.G, max_iter=0) + assert_raises(networkx.NetworkXError, networkx.pagerank, G, + max_iter=0) def test_numpy_pagerank(self): G = self.G @@ -81,28 +80,14 @@ class TestPageRank(object): def test_personalization(self): G = networkx.complete_graph(4) personalize = {0: 1, 1: 1, 2: 4, 3: 4} - answer = {0: 0.23246732615667579, 1: 0.23246732615667579, 2: 0.267532673843324, 3: 0.2675326738433241} - p = networkx.pagerank(G, alpha=0.85, personalization=personalize) + answer = {0: 0.1, 1: 0.1, 2: 0.4, 3: 0.4} + p = networkx.pagerank(G, alpha=0.0, personalization=personalize) for n in G: assert_almost_equal(p[n], answer[n], places=4) personalize.pop(0) assert_raises(networkx.NetworkXError, networkx.pagerank, G, personalization=personalize) - def test_zero_personalization_vector(self): - G = networkx.complete_graph(4) - personalize = {0: 0, 1: 0, 2: 0, 3: 0} - assert_raises(ZeroDivisionError, networkx.pagerank, G, - personalization=personalize) - - def test_one_nonzero_personalization_value(self): - G = networkx.complete_graph(4) - personalize = {0: 0, 1: 0, 2: 0, 3: 1} - answer = {0: 0.22077931820379187, 1: 0.22077931820379187, 2: 0.22077931820379187, 3: 0.3376620453886241} - p = networkx.pagerank(G, alpha=0.85, personalization=personalize) - for n in G: - assert_almost_equal(p[n], answer[n], places=4) - def test_dangling_matrix(self): """ Tests that the google_matrix doesn't change except for the dangling @@ -162,9 +147,8 @@ class TestPageRankScipy(TestPageRank): p = networkx.pagerank_scipy(G, alpha=0.9, tol=1.e-08, personalization=personalize) - @raises(networkx.PowerIterationFailedConvergence) - def test_scipy_pagerank_max_iter(self): - networkx.pagerank_scipy(self.G, max_iter=0) + assert_raises(networkx.NetworkXError, networkx.pagerank_scipy, G, + max_iter=0) def test_dangling_scipy_pagerank(self): pr = networkx.pagerank_scipy(self.G, dangling=self.dangling_edges) diff --git a/networkx/algorithms/traversal/tests/test_dfs.py b/networkx/algorithms/traversal/tests/test_dfs.py index 3d0d13e4d..9fad98584 100644 --- a/networkx/algorithms/traversal/tests/test_dfs.py +++ b/networkx/algorithms/traversal/tests/test_dfs.py @@ -36,20 +36,9 @@ class TestDFS: assert_equal(nx.dfs_predecessors(self.D), {1: 0, 3: 2}) def test_dfs_tree(self): - exp_nodes = sorted(self.G.nodes()) - exp_edges = [(0, 1), (1, 2), (2, 4), (4, 3)] - # Search from first node T=nx.dfs_tree(self.G,source=0) - assert_equal(sorted(T.nodes()), exp_nodes) - assert_equal(sorted(T.edges()), exp_edges) - # Check source=None - T = nx.dfs_tree(self.G, source=None) - assert_equal(sorted(T.nodes()), exp_nodes) - assert_equal(sorted(T.edges()), exp_edges) - # Check source=None is the default - T = nx.dfs_tree(self.G) - assert_equal(sorted(T.nodes()), exp_nodes) - assert_equal(sorted(T.edges()), exp_edges) + assert_equal(sorted(T.nodes()),sorted(self.G.nodes())) + assert_equal(sorted(T.edges()),[(0, 1), (1, 2), (2, 4), (4, 3)]) def test_dfs_edges(self): edges=nx.dfs_edges(self.G,source=0) diff --git a/networkx/drawing/tests/test_layout.py b/networkx/drawing/tests/test_layout.py index 12b47be70..5763eca5e 100644 --- a/networkx/drawing/tests/test_layout.py +++ b/networkx/drawing/tests/test_layout.py @@ -1,7 +1,7 @@ """Unit tests for layout functions.""" import sys from nose import SkipTest -from nose.tools import assert_equal, assert_false, assert_raises +from nose.tools import assert_equal import networkx as nx @@ -16,10 +16,10 @@ class TestLayout(object): raise SkipTest('numpy not available.') def setUp(self): - self.Gi = nx.grid_2d_graph(5, 5) + self.Gi = nx.grid_2d_graph(5,5) self.Gs = nx.Graph() nx.add_path(self.Gs, 'abcdef') - self.bigG = nx.grid_2d_graph(25, 25) #bigger than 500 nodes for sparse + self.bigG = nx.grid_2d_graph(25,25) #bigger than 500 nodes for sparse def test_smoke_int(self): G = self.Gi @@ -27,7 +27,6 @@ class TestLayout(object): vpos = nx.circular_layout(G) vpos = nx.spring_layout(G) vpos = nx.fruchterman_reingold_layout(G) - vpos = nx.fruchterman_reingold_layout(self.bigG) vpos = nx.spectral_layout(G) vpos = nx.spectral_layout(self.bigG) vpos = nx.shell_layout(G) @@ -44,9 +43,8 @@ class TestLayout(object): def test_adjacency_interface_numpy(self): A = nx.to_numpy_matrix(self.Gs) pos = nx.drawing.layout._fruchterman_reingold(A) - assert_equal(pos.shape, (6, 2)) pos = nx.drawing.layout._fruchterman_reingold(A, dim=3) - assert_equal(pos.shape, (6, 3)) + assert_equal(pos.shape, (6,3)) def test_adjacency_interface_scipy(self): try: @@ -55,70 +53,14 @@ class TestLayout(object): raise SkipTest('scipy not available.') A = nx.to_scipy_sparse_matrix(self.Gs, dtype='d') pos = nx.drawing.layout._sparse_fruchterman_reingold(A) - assert_equal(pos.shape, (6, 2)) pos = nx.drawing.layout._sparse_spectral(A) - assert_equal(pos.shape, (6, 2)) pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3) - assert_equal(pos.shape, (6, 3)) + assert_equal(pos.shape, (6,3)) def test_single_nodes(self): G = nx.path_graph(1) vpos = nx.shell_layout(G) - assert_false(vpos[0].any()) + assert(vpos[0].any() == False) G = nx.path_graph(3) - vpos = nx.shell_layout(G, [[0], [1, 2]]) - assert_false(vpos[0].any()) - - def test_smoke_initial_pos_fruchterman_reingold(self): - pos = nx.circular_layout(self.Gi) - npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos) - - def test_fixed_node_fruchterman_reingold(self): - # Dense version (numpy based) - pos = nx.circular_layout(self.Gi) - npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos, fixed=[(0, 0)]) - assert_equal(tuple(pos[(0, 0)]), tuple(npos[(0, 0)])) - # Sparse version (scipy based) - pos = nx.circular_layout(self.bigG) - npos = nx.fruchterman_reingold_layout(self.bigG, pos=pos, fixed=[(0, 0)]) - assert_equal(tuple(pos[(0, 0)]), tuple(npos[(0, 0)])) - - def test_center_parameter(self): - G = nx.path_graph(1) - vpos = nx.random_layout(G, center=(1, 1)) - vpos = nx.circular_layout(G, center=(1, 1)) - assert_equal(tuple(vpos[0]), (1, 1)) - vpos = nx.spring_layout(G, center=(1, 1)) - assert_equal(tuple(vpos[0]), (1, 1)) - vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) - assert_equal(tuple(vpos[0]), (1, 1)) - vpos = nx.spectral_layout(G, center=(1, 1)) - assert_equal(tuple(vpos[0]), (1, 1)) - vpos = nx.shell_layout(G, center=(1, 1)) - assert_equal(tuple(vpos[0]), (1, 1)) - - def test_center_wrong_dimensions(self): - G = nx.path_graph(1) - assert_raises(ValueError, nx.random_layout, G, center=(1, 1, 1)) - assert_raises(ValueError, nx.circular_layout, G, center=(1, 1, 1)) - assert_raises(ValueError, nx.spring_layout, G, center=(1, 1, 1)) - assert_raises(ValueError, nx.fruchterman_reingold_layout, G, center=(1, 1, 1)) - assert_raises(ValueError, nx.fruchterman_reingold_layout, G, dim=3, center=(1, 1)) - assert_raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1)) - assert_raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1)) - assert_raises(ValueError, nx.shell_layout, G, center=(1, 1, 1)) - - def test_empty_graph(self): - G = nx.empty_graph() - vpos = nx.random_layout(G, center=(1, 1)) - assert_equal(vpos, {}) - vpos = nx.circular_layout(G, center=(1, 1)) - assert_equal(vpos, {}) - vpos = nx.spring_layout(G, center=(1, 1)) - assert_equal(vpos, {}) - vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) - assert_equal(vpos, {}) - vpos = nx.spectral_layout(G, center=(1, 1)) - assert_equal(vpos, {}) - vpos = nx.shell_layout(G, center=(1, 1)) - assert_equal(vpos, {}) + vpos = nx.shell_layout(G, [[0], [1,2]]) + assert(vpos[0].any() == False)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 15 }
help
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libgdal-dev graphviz" ], "python": "3.6", "reqs_path": [ "requirements/default.txt", "requirements/test.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 decorator==5.1.1 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/networkx/networkx.git@df730d96d6490079a6b6fcf3a2bea64324aef02e#egg=networkx nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: networkx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - decorator==5.1.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/networkx
[ "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentrality::test_maxiter", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_maxiter" ]
[ "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentrality::test_K5", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentrality::test_P3", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentrality::test_P3_unweighted", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityDirected::test_eigenvector_centrality_weighted", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityDirected::test_eigenvector_centrality_weighted_numpy", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityDirected::test_eigenvector_centrality_unweighted", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityDirected::test_eigenvector_centrality_unweighted_numpy", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityExceptions::test_multigraph_numpy", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityExceptions::test_empty_numpy", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_K5", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_P3", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_beta_as_scalar", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_beta_as_dict", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_multiple_alpha", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_bad_beta", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_bad_beta_numbe", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_K5_unweighted", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_P3_unweighted", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityDirected::test_katz_centrality_weighted", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityDirected::test_katz_centrality_unweighted", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityDirectedNumpy::test_katz_centrality_weighted", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityDirectedNumpy::test_katz_centrality_unweighted", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzEigenvectorVKatz::test_eigenvector_v_katz_random", "networkx/algorithms/link_analysis/tests/test_hits.py::TestHITS::test_hits", "networkx/algorithms/link_analysis/tests/test_hits.py::TestHITS::test_hits_nstart", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_numpy_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_google_matrix", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_dangling_matrix", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_dangling_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_dangling_numpy_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_empty", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_numpy_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_google_matrix", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_dangling_matrix", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_dangling_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_dangling_numpy_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_empty", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_scipy_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_dangling_scipy_pagerank", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_empty_scipy", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_preorder_nodes", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_postorder_nodes", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_successor", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_predecessor", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_dfs_tree", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_dfs_edges", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_dfs_labeled_edges", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_dfs_labeled_disconnected_edges", "networkx/drawing/tests/test_layout.py::TestLayout::test_smoke_int", "networkx/drawing/tests/test_layout.py::TestLayout::test_smoke_string", "networkx/drawing/tests/test_layout.py::TestLayout::test_adjacency_interface_numpy", "networkx/drawing/tests/test_layout.py::TestLayout::test_single_nodes" ]
[ "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityExceptions::test_multigraph", "networkx/algorithms/centrality/tests/test_eigenvector_centrality.py::TestEigenvectorCentralityExceptions::test_empty", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_K5", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_P3", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_beta_as_scalar", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_beta_as_dict", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_multiple_alpha", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_multigraph", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_empty", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_bad_beta", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentrality::test_bad_beta_numbe", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_multigraph", "networkx/algorithms/centrality/tests/test_katz_centrality.py::TestKatzCentralityNumpy::test_empty", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRank::test_personalization", "networkx/algorithms/link_analysis/tests/test_pagerank.py::TestPageRankScipy::test_personalization", "networkx/algorithms/traversal/tests/test_dfs.py::TestDFS::test_dfs_tree_isolates" ]
[]
BSD 3-Clause
566
cdent__gabbi-137
e31f9b4f621f46bbd192b240f368fe915557e199
2016-06-01 12:36:40
e31f9b4f621f46bbd192b240f368fe915557e199
diff --git a/docs/source/runner.rst b/docs/source/runner.rst index fe35932..aaa5815 100644 --- a/docs/source/runner.rst +++ b/docs/source/runner.rst @@ -32,5 +32,8 @@ or in the target URL:: The value of prefix will be prepended to the path portion of URLs that are not fully qualified. +Anywhere host is used, if it is a raw IPV6 address it should be +wrapped in ``[`` and ``]``. + If a ``-x`` or ``--failfast`` argument is provided then ``gabbi-run`` will exit after the first test failure. diff --git a/gabbi/runner.py b/gabbi/runner.py index 463f030..25036a4 100644 --- a/gabbi/runner.py +++ b/gabbi/runner.py @@ -67,7 +67,9 @@ def run(): 'target', nargs='?', default='stub', help='A fully qualified URL (with optional path as prefix) ' - 'to the primary target or a host and port, : separated' + 'to the primary target or a host and port, : separated. ' + 'If using an IPV6 address for the host in either form, ' + 'wrap it in \'[\' and \']\'.' ) parser.add_argument( 'prefix', @@ -98,11 +100,14 @@ def run(): target = args.target prefix = args.prefix - if ':' in target: - host, port = target.split(':') + if ':' in target and '[' not in target: + host, port = target.rsplit(':', 1) + elif ']:' in target: + host, port = target.rsplit(':', 1) else: host = target port = None + host = host.replace('[', '').replace(']', '') # Initialize response handlers. custom_response_handlers = [] diff --git a/gabbi/utils.py b/gabbi/utils.py index f433dd2..a0f812e 100644 --- a/gabbi/utils.py +++ b/gabbi/utils.py @@ -29,10 +29,17 @@ from six.moves.urllib import parse as urlparse def create_url(base_url, host, port=None, prefix='', ssl=False): """Given pieces of a path-based url, return a fully qualified url.""" scheme = 'http' - netloc = host + + # A host with : in it at this stage is assumed to be an IPv6 + # address of some kind (they come in many forms). Port should + # already have been stripped off. + if ':' in host and not (host.startswith('[') and host.endswith(']')): + host = '[%s]' % host if port and not _port_follows_standard(port, ssl): netloc = '%s:%s' % (host, port) + else: + netloc = host if ssl: scheme = 'https'
gabbi can't cope with an ipv6 host argument If an ipv6 address is passed in host when doing `build_tests` the built url is incorrect. An ipv6 address in a url is supposed to be bracketed: `[::1]`.
cdent/gabbi
diff --git a/gabbi/tests/test_parse_url.py b/gabbi/tests/test_parse_url.py index 8879cec..43066c7 100644 --- a/gabbi/tests/test_parse_url.py +++ b/gabbi/tests/test_parse_url.py @@ -40,21 +40,21 @@ class UrlParseTest(unittest.TestCase): return http_case def test_parse_url(self): - host = uuid.uuid4() + host = uuid.uuid4().hex http_case = self.make_test_case(host) parsed_url = http_case._parse_url('/foobar') self.assertEqual('http://%s:8000/foobar' % host, parsed_url) def test_parse_prefix(self): - host = uuid.uuid4() + host = uuid.uuid4().hex http_case = self.make_test_case(host, prefix='/noise') parsed_url = http_case._parse_url('/foobar') self.assertEqual('http://%s:8000/noise/foobar' % host, parsed_url) def test_parse_full(self): - host = uuid.uuid4() + host = uuid.uuid4().hex http_case = self.make_test_case(host) parsed_url = http_case._parse_url('http://example.com/house') @@ -102,6 +102,37 @@ class UrlParseTest(unittest.TestCase): self.assertEqual('https://%s:80/foobar' % host, parsed_url) + def test_ipv6_url(self): + host = '::1' + http_case = self.make_test_case(host, port='80', ssl=True) + parsed_url = http_case._parse_url('/foobar') + + self.assertEqual('https://[%s]:80/foobar' % host, parsed_url) + + def test_ipv6_full_url(self): + host = '::1' + http_case = self.make_test_case(host, port='80', ssl=True) + parsed_url = http_case._parse_url( + 'http://[2001:4860:4860::8888]/foobar') + + self.assertEqual('http://[2001:4860:4860::8888]/foobar', parsed_url) + + def test_ipv6_no_double_colon_wacky_ssl(self): + host = 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210' + http_case = self.make_test_case(host, port='80', ssl=True) + parsed_url = http_case._parse_url('/foobar') + + self.assertEqual( + 'https://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/foobar', + parsed_url) + + http_case = self.make_test_case(host, ssl=True) + parsed_url = http_case._parse_url('/foobar') + + self.assertEqual( + 'https://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8000/foobar', + parsed_url) + def test_add_query_params(self): host = uuid.uuid4().hex # Use a sequence of tuples to ensure order. @@ -121,7 +152,7 @@ class UrlParseTest(unittest.TestCase): self.assertEqual('http://%s:8000/foobar?alpha=beta&x=1&y=2' % host, parsed_url) - def test_extend_query_params_full_ulr(self): + def test_extend_query_params_full_url(self): host = 'stub' query = OrderedDict([('x', 1), ('y', 2)]) http_case = self.make_test_case(host, params=query) diff --git a/gabbi/tests/test_runner.py b/gabbi/tests/test_runner.py index c0b6925..a5c9ea0 100644 --- a/gabbi/tests/test_runner.py +++ b/gabbi/tests/test_runner.py @@ -13,6 +13,7 @@ """Test that the CLI works as expected """ +import mock import sys import unittest from uuid import uuid4 @@ -218,6 +219,72 @@ class RunnerTest(unittest.TestCase): self._stderr.write(sys.stderr.read()) +class RunnerHostArgParse(unittest.TestCase): + + @mock.patch('sys.exit') + @mock.patch('sys.stdin') + @mock.patch('gabbi.driver.test_suite_from_dict') + @mock.patch('yaml.safe_load', return_value={}) + def _test_hostport(self, url_or_host, expected_host, + portmock_yaml, mock_test_suite, mock_read, mock_exit, + provided_prefix=None, expected_port=None, + expected_prefix=None,): + sys.argv = ['gabbi-run', url_or_host] + if provided_prefix: + sys.argv.append(provided_prefix) + runner.run() + + mock_test_suite.assert_called_with( + unittest.defaultTestLoader, 'input', {}, '.', expected_host, + expected_port, None, None, prefix=expected_prefix + ) + + def test_plain_url(self): + self._test_hostport('http://foobar.com:80/news', + 'foobar.com', + expected_port='80', + expected_prefix='/news') + + def test_simple_hostport(self): + self._test_hostport('foobar.com:999', + 'foobar.com', + expected_port='999') + + def test_simple_hostport_with_prefix(self): + self._test_hostport('foobar.com:999', + 'foobar.com', + provided_prefix='/news', + expected_port='999', + expected_prefix='/news') + + def test_ipv6_url_long(self): + self._test_hostport( + 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/news', + 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', + expected_port='999', + expected_prefix='/news') + + def test_ipv6_url_localhost(self): + self._test_hostport( + 'http://[::1]:999/news', + '::1', + expected_port='999', + expected_prefix='/news') + + def test_ipv6_host_localhost(self): + # If a user wants to use the hostport form, then they need + # to hack it with the brackets. + self._test_hostport( + '[::1]', + '::1') + + def test_ipv6_hostport_localhost(self): + self._test_hostport( + '[::1]:999', + '::1', + expected_port='999') + + class HTMLResponseHandler(handlers.ResponseHandler): test_key_suffix = 'html' diff --git a/gabbi/tests/test_utils.py b/gabbi/tests/test_utils.py index a69d72b..1754dad 100644 --- a/gabbi/tests/test_utils.py +++ b/gabbi/tests/test_utils.py @@ -132,3 +132,29 @@ class CreateURLTest(unittest.TestCase): url = utils.create_url('/foo/bar?x=1&y=2', 'test.host.com', ssl=True, port=80) self.assertEqual('https://test.host.com:80/foo/bar?x=1&y=2', url) + + def test_create_url_ipv6_ssl(self): + url = utils.create_url('/foo/bar?x=1&y=2', '::1', ssl=True) + self.assertEqual('https://[::1]/foo/bar?x=1&y=2', url) + + def test_create_url_ipv6_ssl_weird_port(self): + url = utils.create_url('/foo/bar?x=1&y=2', '::1', ssl=True, port=80) + self.assertEqual('https://[::1]:80/foo/bar?x=1&y=2', url) + + def test_create_url_ipv6_full(self): + url = utils.create_url('/foo/bar?x=1&y=2', + '2607:f8b0:4000:801::200e', port=8080) + self.assertEqual( + 'http://[2607:f8b0:4000:801::200e]:8080/foo/bar?x=1&y=2', url) + + def test_create_url_ipv6_already_bracket(self): + url = utils.create_url( + '/foo/bar?x=1&y=2', '[2607:f8b0:4000:801::200e]', port=999) + self.assertEqual( + 'http://[2607:f8b0:4000:801::200e]:999/foo/bar?x=1&y=2', url) + + def test_create_url_no_double_colon(self): + url = utils.create_url( + '/foo', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', port=999) + self.assertEqual( + 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/foo', url)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 3 }
1.19
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mock", "testrepository", "coverage", "hacking", "sphinx", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 colorama==0.4.5 coverage==6.2 decorator==5.1.1 docutils==0.18.1 extras==1.0.0 fixtures==4.0.1 flake8==3.8.4 -e git+https://github.com/cdent/gabbi.git@e31f9b4f621f46bbd192b240f368fe915557e199#egg=gabbi hacking==4.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 iso8601==1.1.0 Jinja2==3.0.3 jsonpath-rw==1.4.0 jsonpath-rw-ext==1.2.2 MarkupSafe==2.0.1 mccabe==0.6.1 mock==5.2.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 ply==3.11 py==1.11.0 pycodestyle==2.6.0 pyflakes==2.2.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 python-subunit==1.4.2 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testrepository==0.0.21 testtools==2.6.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 wsgi_intercept==1.13.1 zipp==3.6.0
name: gabbi channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - colorama==0.4.5 - coverage==6.2 - decorator==5.1.1 - docutils==0.18.1 - extras==1.0.0 - fixtures==4.0.1 - flake8==3.8.4 - hacking==4.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - iso8601==1.1.0 - jinja2==3.0.3 - jsonpath-rw==1.4.0 - jsonpath-rw-ext==1.2.2 - markupsafe==2.0.1 - mccabe==0.6.1 - mock==5.2.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - ply==3.11 - py==1.11.0 - pycodestyle==2.6.0 - pyflakes==2.2.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-subunit==1.4.2 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testrepository==0.0.21 - testtools==2.6.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wsgi-intercept==1.13.1 - zipp==3.6.0 prefix: /opt/conda/envs/gabbi
[ "gabbi/tests/test_parse_url.py::UrlParseTest::test_ipv6_no_double_colon_wacky_ssl", "gabbi/tests/test_parse_url.py::UrlParseTest::test_ipv6_url", "gabbi/tests/test_runner.py::RunnerHostArgParse::test_ipv6_host_localhost", "gabbi/tests/test_runner.py::RunnerHostArgParse::test_ipv6_hostport_localhost", "gabbi/tests/test_runner.py::RunnerHostArgParse::test_ipv6_url_localhost", "gabbi/tests/test_runner.py::RunnerHostArgParse::test_ipv6_url_long", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_full", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl_weird_port", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_no_double_colon" ]
[]
[ "gabbi/tests/test_parse_url.py::UrlParseTest::test_add_query_params", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_http", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_https", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_https_no_ssl", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_int", "gabbi/tests/test_parse_url.py::UrlParseTest::test_extend_query_params", "gabbi/tests/test_parse_url.py::UrlParseTest::test_extend_query_params_full_url", "gabbi/tests/test_parse_url.py::UrlParseTest::test_https_port_80_ssl", "gabbi/tests/test_parse_url.py::UrlParseTest::test_ipv6_full_url", "gabbi/tests/test_parse_url.py::UrlParseTest::test_parse_full", "gabbi/tests/test_parse_url.py::UrlParseTest::test_parse_prefix", "gabbi/tests/test_parse_url.py::UrlParseTest::test_parse_url", "gabbi/tests/test_parse_url.py::UrlParseTest::test_with_ssl", "gabbi/tests/test_runner.py::RunnerTest::test_custom_response_handler", "gabbi/tests/test_runner.py::RunnerTest::test_exit_code", "gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing", "gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing_standard_port", "gabbi/tests/test_runner.py::RunnerHostArgParse::test_plain_url", "gabbi/tests/test_runner.py::RunnerHostArgParse::test_simple_hostport", "gabbi/tests/test_runner.py::RunnerHostArgParse::test_simple_hostport_with_prefix", "gabbi/tests/test_utils.py::BinaryTypesTest::test_binary", "gabbi/tests/test_utils.py::BinaryTypesTest::test_not_binary", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_bad_params", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_both", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_charset", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_multiple_params", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_with_charset", "gabbi/tests/test_utils.py::ColorizeTest::test_colorize_missing_color", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_already_bracket", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_not_ssl_on_443", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port_and_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_prefix", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_preserve_query", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_simple", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl_on_80" ]
[]
Apache License 2.0
567
mattjmcnaughton__sdep-30
be2be4bbfbdb2442fa446174055bb6cf61c4125b
2016-06-01 21:15:26
be2be4bbfbdb2442fa446174055bb6cf61c4125b
diff --git a/docs/cli.rst b/docs/cli.rst index ab80b6a..62fcaee 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -61,6 +61,12 @@ options can be set in configuration files: **Optional** +- :command:`INDEX_SUFFIX`: When hosting with Amazon S3, it is necessary to + specify an index suffix, which is appended to all urls ending in :command:`/`. The + default value is :command:`index.html`. +- :command:`ERROR_KEY`: The S3 key of the file Amazon should serve in case of + error (i.e. incorrect url). The default value is :command:`404.html`. + Environment Variables ~~~~~~~~~~~~~~~~~~~~~ diff --git a/sdep/app.py b/sdep/app.py index ecf518f..ad923f8 100644 --- a/sdep/app.py +++ b/sdep/app.py @@ -28,12 +28,6 @@ class Sdep(object): # Constant names of AWS objects. BUCKET_NAME = "bucket_name" - # Default index and error. - # @TODO This specification is temporary, as eventually we will make these - # configurable options with `Config`. - DEFAULT_INDEX_SUFFIX = "index.html" - DEFAULT_ERROR_KEY = "404.html" - def __init__(self, config): self._config = config self._s3_client = self._establish_s3_client() @@ -199,10 +193,10 @@ class Sdep(object): """ website_config = { "IndexDocument": { - "Suffix": self.DEFAULT_INDEX_SUFFIX + "Suffix": self._config.get(Config.INDEX_SUFFIX_FIELD) }, "ErrorDocument": { - "Key": self.DEFAULT_ERROR_KEY + "Key": self._config.get(Config.ERROR_KEY_FIELD) } } diff --git a/sdep/config.py b/sdep/config.py index 636f97a..22298f8 100644 --- a/sdep/config.py +++ b/sdep/config.py @@ -65,6 +65,8 @@ class Config(object): AWS_SECRET_ACCESS_KEY_FIELD = "aws_secret_access_key" SITE_DIR_FIELD = "site_dir" DOMAIN_FIELD = "domain" + INDEX_SUFFIX_FIELD = "index_suffix" + ERROR_KEY_FIELD = "error_key" def __init__(self, config_file=None, test_mode=False): # @TODO I wonder if it would make more sense for the `Config` class to @@ -144,13 +146,11 @@ class Config(object): ConfigImproperFormatError: If vital configuration data is either in the incorrect format or nonexistent. """ - for field in self.required_config_fields(env=True): - value = os.environ.get(field) - - if value is None: - raise ConfigImproperFormatError - else: - self._config_hash[field.lower()] = value + self._config_hash = self._parse_from_store( + self.required_config_fields(env=True), + self.optional_config_fields(env=True), + os.environ + ) def _parse_from_config_file(self, config_file): """ @@ -172,15 +172,46 @@ class Config(object): except (IOError, json.JSONDecodeError): raise ConfigImproperFormatError - # @TODO Should a common helper method implement this functionality - # for both `_parse_from_config_file` and `_parse_from_env`. - for field in self.required_config_fields(env=False): - value = config_data.get(field) + self._config_hash = self._parse_from_store( + self.required_config_fields(env=False), + self.optional_config_fields(env=False), + config_data + ) + + @classmethod + def _parse_from_store(cls, required_fields, optional_fields, data_store): + """ + Parse the configuration from a data store object (i.e. the json hash or + `os.environ`). This method is useful because the process for parsing the + data from either the environment or a configuration file shares many of + the same components. Abstracting to a single method ensures less + duplicate code. + + Args: + required_fields (list): A list of the required fields. + optional_fields (list): A list of the optional fields. + data_store (dict): A dictionary containing key/value pairs with the + fields as a key. + + Returns: + dict: A configuration dictionary. + """ + # Start with all of the defaults filled in. We will overwrite with any + # specified info. + config_hash = cls._optional_fields_and_defaults() + + fields = [(f, True) for f in required_fields] + [(f, False) for f in optional_fields] + + for field, required in fields: + value = data_store.get(field) if value is None: - raise ConfigImproperFormatError + if required: + raise ConfigImproperFormatError else: - self._config_hash[field.lower()] = value + config_hash[field.lower()] = value + + return config_hash @classmethod def required_config_fields(cls, env=False): @@ -207,8 +238,8 @@ class Config(object): else: return required_fields - @staticmethod - def optional_config_fields(env=False): + @classmethod + def optional_config_fields(cls, env=False): """ Return the optinal configuration fields either in `snake_case` or in all upper-case `snake_case`, depending on whether the `env` flag is set. @@ -220,23 +251,40 @@ class Config(object): Returns: [str]: A list of optional configuration fields. """ - optional_fields = [] + optional_fields = list(cls._optional_fields_and_defaults().keys()) if env: return [field.upper() for field in optional_fields] else: return optional_fields + @classmethod + def _optional_fields_and_defaults(cls): + """ + Return a dictionary of optional fields and their defaults. + + Returns: + dict: Optional fields and their defaults. + """ + return { + cls.INDEX_SUFFIX_FIELD: "index.html", + cls.ERROR_KEY_FIELD: "404.html" + } + def _prepopulate_config(self): """ Prepopulate this instance of `Config` with sensible default values which we can use when testing. """ - # @TODO Determine a better method for automatically including all - # `required` variables. - self._config_hash = { + populate_hash = { self.AWS_ACCESS_KEY_ID_FIELD: "MY_ACCESS_KEY", self.AWS_SECRET_ACCESS_KEY_FIELD: "MY_SECRET_KEY", self.SITE_DIR_FIELD: "./static", self.DOMAIN_FIELD: "sdep-test.com" } + + self._config_hash = self._parse_from_store( + self.required_config_fields(env=False), + self.optional_config_fields(env=False), + populate_hash + )
Add `index_suffix` and `error_key` as optional fields When telling AWS to have our bucket perform like a website, with this [boto call](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_bucket_website), we have the option of specifying which suffix will represent an index file (currently `index.html`) and the file to display when there is an error (currently `404.html`). Make both of these configurable options with sensible defaults.
mattjmcnaughton/sdep
diff --git a/tests/test_app.py b/tests/test_app.py index 8dd700f..08b5da0 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -117,9 +117,8 @@ class SdepTestCase(unittest.TestCase): # with `Config`. resp = self._s3_client.get_bucket_website(Bucket=bucket_name) - self.assertEqual(resp["IndexDocument"]["Suffix"], - Sdep.DEFAULT_INDEX_SUFFIX) - self.assertEqual(resp["ErrorDocument"]["Key"], Sdep.DEFAULT_ERROR_KEY) + self.assertNotEqual(resp["IndexDocument"]["Suffix"], None) + self.assertNotEqual(resp["ErrorDocument"]["Key"], None) @classmethod def _create_test_upload_dir(cls): diff --git a/tests/test_config.py b/tests/test_config.py index 0feb7be..a1be9d8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -35,7 +35,7 @@ class ConfigTestCase(unittest.TestCase): config_file = self._create_config_file() config = Config(config_file=config_file) - for field in Config.required_config_fields(): + for field in self._all_fields(): self.assertNotEqual(config.get(field), None) os.remove(config_file) @@ -51,7 +51,7 @@ class ConfigTestCase(unittest.TestCase): with patch.dict(os.environ, environ_dict, clear=True): config = Config() - for field in Config.required_config_fields(): + for field in self._all_fields(): self.assertNotEqual(config.get(field), None) def test_find_config_in_curr_dir(self): @@ -71,7 +71,7 @@ class ConfigTestCase(unittest.TestCase): config = Config() self.assertEqual(config_in_curr, Config.locate_config_file()) - for field in Config.required_config_fields(): + for field in self._all_fields(): self.assertNotEqual(config.get(field), None) for temp_dir in [temp_dirs.current, temp_dirs.home]: @@ -97,13 +97,12 @@ class ConfigTestCase(unittest.TestCase): config = Config() self.assertEqual(config_in_home, Config.locate_config_file()) - for field in Config.required_config_fields(): + for field in self._all_fields(): self.assertNotEqual(config.get(field), None) for temp_dir in [temp_dirs.current, temp_dirs.home]: shutil.rmtree(temp_dir, ignore_errors=True) - def test_bad_config(self): """ Test loading the configuration from a file with an improperly specified @@ -114,15 +113,23 @@ class ConfigTestCase(unittest.TestCase): with self.assertRaises(ConfigParseError): Config(config_file=config_file) - @staticmethod - def _config_dict(): + @classmethod + def _config_dict(cls): """ A dictionary of property formatted config. Returns: dict: A properly formatted config. """ - return {field: str(uuid.uuid4()) for field in Config.required_config_fields()} + base_dict = {field: str(uuid.uuid4()) for field in cls._all_fields()} + + # Remove one of the optional fields so that we can test the default value + # being filled in. + + field_to_remove = Config.optional_config_fields()[0] + del base_dict[field_to_remove] + + return base_dict @classmethod def _create_mock_dirs(cls): @@ -176,3 +183,13 @@ class ConfigTestCase(unittest.TestCase): bad_config_file.write(json.dumps({})) return file_name + + @staticmethod + def _all_fields(): + """ + Helper method to return all configuration fields. + + Returns: + list: List of the strings for all configuration fields. + """ + return Config.required_config_fields() + Config.optional_config_fields()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose2", "pytest" ], "pre_install": [], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 argh==0.27.2 astroid==2.11.7 attrs==22.2.0 Babel==2.11.0 boto==2.49.0 boto3==1.23.10 botocore==1.26.10 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 cookies==2.2.1 dataclasses==0.8 dicttoxml==1.7.16 dill==0.3.4 docutils==0.18.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 Jinja2==3.0.3 jmespath==0.10.0 lazy-object-proxy==1.7.1 livereload==2.6.3 MarkupSafe==2.0.1 mccabe==0.7.0 mock==2.0.0 moto==1.0.0 nose2==0.13.0 packaging==21.3 pathtools==0.1.2 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 pockets==0.9.1 port-for==0.3.1 py==1.11.0 pyaml==23.5.8 Pygments==2.14.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 s3transfer==0.5.2 -e git+https://github.com/mattjmcnaughton/sdep.git@be2be4bbfbdb2442fa446174055bb6cf61c4125b#egg=sdep simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-autobuild==0.7.1 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-napoleon==0.7 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 tornado==6.1 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 watchdog==2.3.1 Werkzeug==2.0.3 wrapt==1.16.0 xmltodict==0.14.2 zipp==3.6.0
name: sdep channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - argh==0.27.2 - astroid==2.11.7 - attrs==22.2.0 - babel==2.11.0 - boto==2.49.0 - boto3==1.23.10 - botocore==1.26.10 - charset-normalizer==2.0.12 - click==8.0.4 - cookies==2.2.1 - dataclasses==0.8 - dicttoxml==1.7.16 - dill==0.3.4 - docutils==0.18.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - jinja2==3.0.3 - jmespath==0.10.0 - lazy-object-proxy==1.7.1 - livereload==2.6.3 - markupsafe==2.0.1 - mccabe==0.7.0 - mock==2.0.0 - moto==1.0.0 - nose2==0.13.0 - packaging==21.3 - pathtools==0.1.2 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - pockets==0.9.1 - port-for==0.3.1 - py==1.11.0 - pyaml==23.5.8 - pygments==2.14.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - s3transfer==0.5.2 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-autobuild==0.7.1 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-napoleon==0.7 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - tornado==6.1 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - watchdog==2.3.1 - werkzeug==2.0.3 - wrapt==1.16.0 - xmltodict==0.14.2 - zipp==3.6.0 prefix: /opt/conda/envs/sdep
[ "tests/test_config.py::ConfigTestCase::test_find_config_in_curr_dir", "tests/test_config.py::ConfigTestCase::test_find_config_in_home_dir", "tests/test_config.py::ConfigTestCase::test_load_config_from_env", "tests/test_config.py::ConfigTestCase::test_load_config_from_file" ]
[ "tests/test_app.py::SdepTestCase::test_configure_bucket_website", "tests/test_app.py::SdepTestCase::test_create", "tests/test_app.py::SdepTestCase::test_create_s3_buckets", "tests/test_app.py::SdepTestCase::test_upload", "tests/test_app.py::SdepTestCase::test_upload_files_to_s3" ]
[ "tests/test_config.py::ConfigTestCase::test_bad_config" ]
[]
MIT License
568
tableau__document-api-python-15
07aad9550d3d36a4d74c4751832c50fe81882a01
2016-06-02 00:21:16
07aad9550d3d36a4d74c4751832c50fe81882a01
diff --git a/tableaudocumentapi/datasource.py b/tableaudocumentapi/datasource.py index 93ebe55..617004a 100644 --- a/tableaudocumentapi/datasource.py +++ b/tableaudocumentapi/datasource.py @@ -72,7 +72,7 @@ class Datasource(object): """ # save the file - self._datasourceTree.write(self._filename) + self._datasourceTree.write(self._filename, encoding="utf-8", xml_declaration=True) def save_as(self, new_filename): """ @@ -85,7 +85,7 @@ class Datasource(object): Nothing. """ - self._datasourceTree.write(new_filename) + self._datasourceTree.write(new_filename, encoding="utf-8", xml_declaration=True) ########### # name diff --git a/tableaudocumentapi/workbook.py b/tableaudocumentapi/workbook.py index 67dbc32..889f746 100644 --- a/tableaudocumentapi/workbook.py +++ b/tableaudocumentapi/workbook.py @@ -76,7 +76,7 @@ class Workbook(object): """ # save the file - self._workbookTree.write(self._filename) + self._workbookTree.write(self._filename, encoding="utf-8", xml_declaration=True) def save_as(self, new_filename): """ @@ -90,7 +90,7 @@ class Workbook(object): """ - self._workbookTree.write(new_filename) + self._workbookTree.write(new_filename, encoding="utf-8", xml_declaration=True) ########################################################################### #
Tabcmd publish with .twb created via Document API I can successfully create a .twb file via the Document API, but attempting to publish it to my Tableau Server via Tabcmd results in an unexpected error: **Bad request unexpected error occurred opening the packaged workbook.** Attached is the template workbook created in Tableau Desktop (superstore_sales.twb) and one of the workbooks created from that template via the Document API (superstore_sales_arizona.twb) [superstore_twbs.zip](https://github.com/tableau/document-api-python/files/285303/superstore_twbs.zip)
tableau/document-api-python
diff --git a/test.py b/test.py index fd7d1bd..5606005 100644 --- a/test.py +++ b/test.py @@ -17,6 +17,7 @@ TABLEAU_10_WORKBOOK = '''<?xml version='1.0' encoding='utf-8' ?><workbook source TABLEAU_CONNECTION_XML = ET.fromstring( '''<connection authentication='sspi' class='sqlserver' dbname='TestV1' odbc-native-protocol='yes' one-time-sql='' server='mssql2012.test.tsi.lan' username=''></connection>''') + class HelperMethodTests(unittest.TestCase): def test_is_valid_file_with_valid_inputs(self): @@ -39,7 +40,6 @@ class ConnectionParserTests(unittest.TestCase): self.assertIsInstance(connections[0], Connection) self.assertEqual(connections[0].dbname, 'TestV1') - def test_can_extract_federated_connections(self): parser = ConnectionParser(ET.fromstring(TABLEAU_10_TDS), '10.0') connections = parser.get_connections() @@ -97,6 +97,17 @@ class DatasourceModelTests(unittest.TestCase): new_tds = Datasource.from_file(self.tds_file.name) self.assertEqual(new_tds.connections[0].dbname, 'newdb.test.tsi.lan') + def test_save_has_xml_declaration(self): + original_tds = Datasource.from_file(self.tds_file.name) + original_tds.connections[0].dbname = 'newdb.test.tsi.lan' + + original_tds.save() + + with open(self.tds_file.name) as f: + first_line = f.readline().strip() # first line should be xml tag + self.assertEqual( + first_line, "<?xml version='1.0' encoding='utf-8'?>") + class WorkbookModelTests(unittest.TestCase): @@ -122,7 +133,8 @@ class WorkbookModelTests(unittest.TestCase): original_wb.save() new_wb = Workbook(self.workbook_file.name) - self.assertEqual(new_wb.datasources[0].connections[0].dbname, 'newdb.test.tsi.lan') + self.assertEqual(new_wb.datasources[0].connections[ + 0].dbname, 'newdb.test.tsi.lan') class WorkbookModelV10Tests(unittest.TestCase): @@ -152,7 +164,19 @@ class WorkbookModelV10Tests(unittest.TestCase): original_wb.save() new_wb = Workbook(self.workbook_file.name) - self.assertEqual(new_wb.datasources[0].connections[0].dbname, 'newdb.test.tsi.lan') + self.assertEqual(new_wb.datasources[0].connections[ + 0].dbname, 'newdb.test.tsi.lan') + + def test_save_has_xml_declaration(self): + original_wb = Workbook(self.workbook_file.name) + original_wb.datasources[0].connections[0].dbname = 'newdb.test.tsi.lan' + + original_wb.save() + + with open(self.workbook_file.name) as f: + first_line = f.readline().strip() # first line should be xml tag + self.assertEqual( + first_line, "<?xml version='1.0' encoding='utf-8'?>") if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work -e git+https://github.com/tableau/document-api-python.git@07aad9550d3d36a4d74c4751832c50fe81882a01#egg=tableaudocumentapi tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: document-api-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/document-api-python
[ "test.py::DatasourceModelTests::test_save_has_xml_declaration", "test.py::WorkbookModelV10Tests::test_save_has_xml_declaration" ]
[]
[ "test.py::HelperMethodTests::test_is_valid_file_with_invalid_inputs", "test.py::HelperMethodTests::test_is_valid_file_with_valid_inputs", "test.py::ConnectionParserTests::test_can_extract_federated_connections", "test.py::ConnectionParserTests::test_can_extract_legacy_connection", "test.py::ConnectionModelTests::test_can_read_attributes_from_connection", "test.py::ConnectionModelTests::test_can_write_attributes_to_connection", "test.py::DatasourceModelTests::test_can_extract_connection", "test.py::DatasourceModelTests::test_can_extract_datasource_from_file", "test.py::DatasourceModelTests::test_can_save_tds", "test.py::WorkbookModelTests::test_can_extract_datasource", "test.py::WorkbookModelTests::test_can_update_datasource_connection_and_save", "test.py::WorkbookModelV10Tests::test_can_extract_datasourceV10", "test.py::WorkbookModelV10Tests::test_can_update_datasource_connection_and_saveV10" ]
[]
MIT License
569
docker__docker-py-1079
88811a26593e8a87e8d820d8820736fea6d8d20a
2016-06-03 00:58:40
299ffadb95c90eb7134b9cee2648fb683912c303
diff --git a/docker/client.py b/docker/client.py index de3cb3ca..b96a78ce 100644 --- a/docker/client.py +++ b/docker/client.py @@ -14,7 +14,6 @@ import json import struct -import sys import requests import requests.exceptions @@ -26,10 +25,14 @@ from . import api from . import constants from . import errors from .auth import auth -from .unixconn import unixconn from .ssladapter import ssladapter -from .utils import utils, check_resource, update_headers, kwargs_from_env from .tls import TLSConfig +from .transport import UnixAdapter +from .utils import utils, check_resource, update_headers, kwargs_from_env +try: + from .transport import NpipeAdapter +except ImportError: + pass def from_env(**kwargs): @@ -59,11 +62,26 @@ class Client( self._auth_configs = auth.load_config() - base_url = utils.parse_host(base_url, sys.platform, tls=bool(tls)) + base_url = utils.parse_host( + base_url, constants.IS_WINDOWS_PLATFORM, tls=bool(tls) + ) if base_url.startswith('http+unix://'): - self._custom_adapter = unixconn.UnixAdapter(base_url, timeout) + self._custom_adapter = UnixAdapter(base_url, timeout) self.mount('http+docker://', self._custom_adapter) self.base_url = 'http+docker://localunixsocket' + elif base_url.startswith('npipe://'): + if not constants.IS_WINDOWS_PLATFORM: + raise errors.DockerException( + 'The npipe:// protocol is only supported on Windows' + ) + try: + self._custom_adapter = NpipeAdapter(base_url, timeout) + except NameError: + raise errors.DockerException( + 'Install pypiwin32 package to enable npipe:// support' + ) + self.mount('http+docker://', self._custom_adapter) + self.base_url = 'http+docker://localnpipe' else: # Use SSLAdapter for the ability to specify SSL version if isinstance(tls, TLSConfig): diff --git a/docker/constants.py b/docker/constants.py index 6c381de3..0388f705 100644 --- a/docker/constants.py +++ b/docker/constants.py @@ -1,3 +1,5 @@ +import sys + DEFAULT_DOCKER_API_VERSION = '1.22' DEFAULT_TIMEOUT_SECONDS = 60 STREAM_HEADER_SIZE_BYTES = 8 @@ -8,3 +10,5 @@ CONTAINER_LIMITS_KEYS = [ INSECURE_REGISTRY_DEPRECATION_WARNING = \ 'The `insecure_registry` argument to {} ' \ 'is deprecated and non-functional. Please remove it.' + +IS_WINDOWS_PLATFORM = (sys.platform == 'win32') diff --git a/docker/transport/__init__.py b/docker/transport/__init__.py new file mode 100644 index 00000000..d647483e --- /dev/null +++ b/docker/transport/__init__.py @@ -0,0 +1,6 @@ +# flake8: noqa +from .unixconn import UnixAdapter +try: + from .npipeconn import NpipeAdapter +except ImportError: + pass \ No newline at end of file diff --git a/docker/transport/npipeconn.py b/docker/transport/npipeconn.py new file mode 100644 index 00000000..736ddf67 --- /dev/null +++ b/docker/transport/npipeconn.py @@ -0,0 +1,80 @@ +import six +import requests.adapters + +from .npipesocket import NpipeSocket + +if six.PY3: + import http.client as httplib +else: + import httplib + +try: + import requests.packages.urllib3 as urllib3 +except ImportError: + import urllib3 + + +RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer + + +class NpipeHTTPConnection(httplib.HTTPConnection, object): + def __init__(self, npipe_path, timeout=60): + super(NpipeHTTPConnection, self).__init__( + 'localhost', timeout=timeout + ) + self.npipe_path = npipe_path + self.timeout = timeout + + def connect(self): + sock = NpipeSocket() + sock.settimeout(self.timeout) + sock.connect(self.npipe_path) + self.sock = sock + + +class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): + def __init__(self, npipe_path, timeout=60): + super(NpipeHTTPConnectionPool, self).__init__( + 'localhost', timeout=timeout + ) + self.npipe_path = npipe_path + self.timeout = timeout + + def _new_conn(self): + return NpipeHTTPConnection( + self.npipe_path, self.timeout + ) + + +class NpipeAdapter(requests.adapters.HTTPAdapter): + def __init__(self, base_url, timeout=60): + self.npipe_path = base_url.replace('npipe://', '') + self.timeout = timeout + self.pools = RecentlyUsedContainer( + 10, dispose_func=lambda p: p.close() + ) + super(NpipeAdapter, self).__init__() + + def get_connection(self, url, proxies=None): + with self.pools.lock: + pool = self.pools.get(url) + if pool: + return pool + + pool = NpipeHTTPConnectionPool( + self.npipe_path, self.timeout + ) + self.pools[url] = pool + + return pool + + def request_url(self, request, proxies): + # The select_proxy utility in requests errors out when the provided URL + # doesn't have a hostname, like is the case when using a UNIX socket. + # Since proxies are an irrelevant notion in the case of UNIX sockets + # anyway, we simply return the path URL directly. + # See also: https://github.com/docker/docker-py/issues/811 + return request.path_url + + def close(self): + self.pools.clear() diff --git a/docker/transport/npipesocket.py b/docker/transport/npipesocket.py new file mode 100644 index 00000000..35418ef1 --- /dev/null +++ b/docker/transport/npipesocket.py @@ -0,0 +1,191 @@ +import functools +import io + +import win32file +import win32pipe + +cSECURITY_SQOS_PRESENT = 0x100000 +cSECURITY_ANONYMOUS = 0 +cPIPE_READMODE_MESSAGE = 2 + + +def check_closed(f): + @functools.wraps(f) + def wrapped(self, *args, **kwargs): + if self._closed: + raise RuntimeError( + 'Can not reuse socket after connection was closed.' + ) + return f(self, *args, **kwargs) + return wrapped + + +class NpipeSocket(object): + """ Partial implementation of the socket API over windows named pipes. + This implementation is only designed to be used as a client socket, + and server-specific methods (bind, listen, accept...) are not + implemented. + """ + def __init__(self, handle=None): + self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT + self._handle = handle + self._closed = False + + def accept(self): + raise NotImplementedError() + + def bind(self, address): + raise NotImplementedError() + + def close(self): + self._handle.Close() + self._closed = True + + @check_closed + def connect(self, address): + win32pipe.WaitNamedPipe(address, self._timeout) + handle = win32file.CreateFile( + address, + win32file.GENERIC_READ | win32file.GENERIC_WRITE, + 0, + None, + win32file.OPEN_EXISTING, + cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT, + 0 + ) + self.flags = win32pipe.GetNamedPipeInfo(handle)[0] + + self._handle = handle + self._address = address + + @check_closed + def connect_ex(self, address): + return self.connect(address) + + @check_closed + def detach(self): + self._closed = True + return self._handle + + @check_closed + def dup(self): + return NpipeSocket(self._handle) + + @check_closed + def fileno(self): + return int(self._handle) + + def getpeername(self): + return self._address + + def getsockname(self): + return self._address + + def getsockopt(self, level, optname, buflen=None): + raise NotImplementedError() + + def ioctl(self, control, option): + raise NotImplementedError() + + def listen(self, backlog): + raise NotImplementedError() + + def makefile(self, mode=None, bufsize=None): + if mode.strip('b') != 'r': + raise NotImplementedError() + rawio = NpipeFileIOBase(self) + if bufsize is None: + bufsize = io.DEFAULT_BUFFER_SIZE + return io.BufferedReader(rawio, buffer_size=bufsize) + + @check_closed + def recv(self, bufsize, flags=0): + err, data = win32file.ReadFile(self._handle, bufsize) + return data + + @check_closed + def recvfrom(self, bufsize, flags=0): + data = self.recv(bufsize, flags) + return (data, self._address) + + @check_closed + def recvfrom_into(self, buf, nbytes=0, flags=0): + return self.recv_into(buf, nbytes, flags), self._address + + @check_closed + def recv_into(self, buf, nbytes=0): + readbuf = buf + if not isinstance(buf, memoryview): + readbuf = memoryview(buf) + + err, data = win32file.ReadFile( + self._handle, + readbuf[:nbytes] if nbytes else readbuf + ) + return len(data) + + @check_closed + def send(self, string, flags=0): + err, nbytes = win32file.WriteFile(self._handle, string) + return nbytes + + @check_closed + def sendall(self, string, flags=0): + return self.send(string, flags) + + @check_closed + def sendto(self, string, address): + self.connect(address) + return self.send(string) + + def setblocking(self, flag): + if flag: + return self.settimeout(None) + return self.settimeout(0) + + def settimeout(self, value): + if value is None: + self._timeout = win32pipe.NMPWAIT_NOWAIT + elif not isinstance(value, (float, int)) or value < 0: + raise ValueError('Timeout value out of range') + elif value == 0: + self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT + else: + self._timeout = value + + def gettimeout(self): + return self._timeout + + def setsockopt(self, level, optname, value): + raise NotImplementedError() + + @check_closed + def shutdown(self, how): + return self.close() + + +class NpipeFileIOBase(io.RawIOBase): + def __init__(self, npipe_socket): + self.sock = npipe_socket + + def close(self): + super(NpipeFileIOBase, self).close() + self.sock = None + + def fileno(self): + return self.sock.fileno() + + def isatty(self): + return False + + def readable(self): + return True + + def readinto(self, buf): + return self.sock.recv_into(buf) + + def seekable(self): + return False + + def writable(self): + return False diff --git a/docker/unixconn/unixconn.py b/docker/transport/unixconn.py similarity index 100% rename from docker/unixconn/unixconn.py rename to docker/transport/unixconn.py diff --git a/docker/unixconn/__init__.py b/docker/unixconn/__init__.py deleted file mode 100644 index 53711fc6..00000000 --- a/docker/unixconn/__init__.py +++ /dev/null @@ -1,1 +0,0 @@ -from .unixconn import UnixAdapter # flake8: noqa diff --git a/docker/utils/utils.py b/docker/utils/utils.py index caa98314..4a56829d 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -383,13 +383,13 @@ def parse_repository_tag(repo_name): # fd:// protocol unsupported (for obvious reasons) # Added support for http and https # Protocol translation: tcp -> http, unix -> http+unix -def parse_host(addr, platform=None, tls=False): +def parse_host(addr, is_win32=False, tls=False): proto = "http+unix" host = DEFAULT_HTTP_HOST port = None path = '' - if not addr and platform == 'win32': + if not addr and is_win32: addr = '{0}:{1}'.format(DEFAULT_HTTP_HOST, 2375) if not addr or addr.strip() == 'unix://': @@ -413,6 +413,9 @@ def parse_host(addr, platform=None, tls=False): elif addr.startswith('https://'): proto = "https" addr = addr[8:] + elif addr.startswith('npipe://'): + proto = 'npipe' + addr = addr[8:] elif addr.startswith('fd://'): raise errors.DockerException("fd protocol is not implemented") else: @@ -448,7 +451,7 @@ def parse_host(addr, platform=None, tls=False): else: host = addr - if proto == "http+unix": + if proto == "http+unix" or proto == 'npipe': return "{0}://{1}".format(proto, host) return "{0}://{1}:{2}{3}".format(proto, host, port, path) diff --git a/setup.py b/setup.py index 85427110..ac58b1f9 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,10 @@ #!/usr/bin/env python import os +import sys + from setuptools import setup + ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) @@ -11,6 +14,9 @@ requirements = [ 'websocket-client >= 0.32.0', ] +if sys.platform == 'win32': + requirements.append('pypiwin32 >= 219') + extras_require = { ':python_version < "3.5"': 'backports.ssl_match_hostname >= 3.5', ':python_version < "3.3"': 'ipaddress >= 1.0.16', @@ -29,7 +35,7 @@ setup( description="Python client for Docker.", url='https://github.com/docker/docker-py/', packages=[ - 'docker', 'docker.api', 'docker.auth', 'docker.unixconn', + 'docker', 'docker.api', 'docker.auth', 'docker.transport', 'docker.utils', 'docker.utils.ports', 'docker.ssladapter' ], install_requires=requirements, diff --git a/win32-requirements.txt b/win32-requirements.txt new file mode 100644 index 00000000..e77c3d90 --- /dev/null +++ b/win32-requirements.txt @@ -0,0 +1,2 @@ +-r requirements.txt +pypiwin32==219 \ No newline at end of file
Support windows named pipes for docker api https://github.com/docker/compose/issues/3170 Apparently the pywin32 API provides some tools for working with this (http://docs.activestate.com/activepython/3.4/pywin32/win32pipe.html). Also available as `pypiwin32` on pypi. Examples: http://codereview.stackexchange.com/questions/88672/python-wrapper-for-windows-pipes
docker/docker-py
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index ef927d36..ae821fd3 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -388,6 +388,7 @@ class ParseHostTest(base.BaseTestCase): 'somehost.net:80/service/swarm': ( 'http://somehost.net:80/service/swarm' ), + 'npipe:////./pipe/docker_engine': 'npipe:////./pipe/docker_engine', } for host in invalid_hosts: @@ -402,10 +403,8 @@ class ParseHostTest(base.BaseTestCase): tcp_port = 'http://127.0.0.1:2375' for val in [None, '']: - for platform in ['darwin', 'linux2', None]: - assert parse_host(val, platform) == unix_socket - - assert parse_host(val, 'win32') == tcp_port + assert parse_host(val, is_win32=False) == unix_socket + assert parse_host(val, is_win32=True) == tcp_port def test_parse_host_tls(self): host_value = 'myhost.docker.net:3348'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 4 }
1.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 -e git+https://github.com/docker/docker-py.git@88811a26593e8a87e8d820d8820736fea6d8d20a#egg=docker_py importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 requests==2.5.3 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 websocket-client==0.32.0 zipp==3.6.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - requests==2.5.3 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - websocket-client==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/docker-py
[ "tests/unit/utils_test.py::ParseHostTest::test_parse_host", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value" ]
[]
[ "tests/unit/utils_test.py::HostConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_score_adj", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_alternate_env", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false_no_cert", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_with_equals_character", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls_tcp_proto", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_create_ipam_config", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_leading_dot_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_with_path_traversal", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks" ]
[]
Apache License 2.0
570
aio-libs__multidict-3
ae23ed4adbfff861bd2621223a0e50bb0313cf32
2016-06-04 15:22:44
ae23ed4adbfff861bd2621223a0e50bb0313cf32
diff --git a/multidict/_multidict_py.py b/multidict/_multidict_py.py index f9c8f38..bff8276 100644 --- a/multidict/_multidict_py.py +++ b/multidict/_multidict_py.py @@ -185,12 +185,13 @@ class MultiDict(_Base, abc.MutableMapping): elif hasattr(arg, 'items'): items = arg.items() else: + items = [] for item in arg: if not len(item) == 2: raise TypeError( "{} takes either dict or list of (key, value) " "tuples".format(name)) - items = arg + items.append(item) for key, value in items: method(key, value)
Python MultiDict constructor discards generator content When using the pure Python implementation, if a `MultiDict` is constructed with a generator argument: headers = CIMultiDict( ( k.decode('utf-8', 'surrogateescape'), v.decode('utf-8', 'surrogateescape'), ) for k, v in event.headers ) then the resulting `MultiDict` will be empty, instead of containing the key/value pairs as expected. This is because the generator is iterated over twice, and the first iteration discards all of the pairs.
aio-libs/multidict
diff --git a/tests/test_multidict.py b/tests/test_multidict.py index 8fa6e78..268a26e 100644 --- a/tests/test_multidict.py +++ b/tests/test_multidict.py @@ -73,6 +73,15 @@ class _BaseTest(_Root): self.assertEqual(sorted(d.items()), [('key', 'value1'), ('key2', 'value2')]) + def test_instantiate__from_generator(self): + d = self.make_dict((str(i), i) for i in range(2)) + + self.assertEqual(d, {'0': 0, '1': 1}) + self.assertEqual(len(d), 2) + self.assertEqual(sorted(d.keys()), ['0', '1']) + self.assertEqual(sorted(d.values()), [0, 1]) + self.assertEqual(sorted(d.items()), [('0', 0), ('1', 1)]) + def test_getone(self): d = self.make_dict([('key', 'value1')], key='value2') self.assertEqual(d.getone('key'), 'value1')
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "pip install -U -r requirements-dev.txt" ], "python": "3.5", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 backcall==0.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 Cython==3.0.12 decorator==5.1.1 distlib==0.3.9 docutils==0.17.1 filelock==3.4.1 flake8==5.0.4 idna==3.10 imagesize==1.4.1 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 ipdb==0.13.13 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 MarkupSafe==2.0.1 mccabe==0.7.0 -e git+https://github.com/aio-libs/multidict.git@ae23ed4adbfff861bd2621223a0e50bb0313cf32#egg=multidict packaging==21.3 parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 platformdirs==2.4.0 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pycodestyle==2.9.1 pyenchant==3.2.2 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-sugar==0.9.6 pytz==2025.2 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==4.3.2 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-newsfeed==0.1.4 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 sphinxcontrib-spelling==7.7.0 termcolor==1.1.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.16.2 wcwidth==0.2.13 zipp==3.6.0
name: multidict channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - backcall==0.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - cython==3.0.12 - decorator==5.1.1 - distlib==0.3.9 - docutils==0.17.1 - filelock==3.4.1 - flake8==5.0.4 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - ipdb==0.13.13 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - markupsafe==2.0.1 - mccabe==0.7.0 - packaging==21.3 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pip==21.3.1 - platformdirs==2.4.0 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pycodestyle==2.9.1 - pyenchant==3.2.2 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-sugar==0.9.6 - pytz==2025.2 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==4.3.2 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-newsfeed==0.1.4 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sphinxcontrib-spelling==7.7.0 - termcolor==1.1.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.16.2 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/multidict
[ "tests/test_multidict.py::TestPyMultiDictProxy::test_instantiate__from_generator", "tests/test_multidict.py::PyMutableMultiDictTests::test_instantiate__from_generator" ]
[]
[ "tests/test_multidict.py::TestPyMultiDictProxy::test__iter__", "tests/test_multidict.py::TestPyMultiDictProxy::test__repr__", "tests/test_multidict.py::TestPyMultiDictProxy::test_and", "tests/test_multidict.py::TestPyMultiDictProxy::test_and_issue_410", "tests/test_multidict.py::TestPyMultiDictProxy::test_cannot_create_from_unaccepted", "tests/test_multidict.py::TestPyMultiDictProxy::test_copy", "tests/test_multidict.py::TestPyMultiDictProxy::test_eq", "tests/test_multidict.py::TestPyMultiDictProxy::test_exposed_names", "tests/test_multidict.py::TestPyMultiDictProxy::test_get", "tests/test_multidict.py::TestPyMultiDictProxy::test_getall", "tests/test_multidict.py::TestPyMultiDictProxy::test_getone", "tests/test_multidict.py::TestPyMultiDictProxy::test_instantiate__empty", "tests/test_multidict.py::TestPyMultiDictProxy::test_instantiate__from_arg0", "tests/test_multidict.py::TestPyMultiDictProxy::test_instantiate__from_arg0_dict", "tests/test_multidict.py::TestPyMultiDictProxy::test_instantiate__with_kwargs", "tests/test_multidict.py::TestPyMultiDictProxy::test_isdisjoint", "tests/test_multidict.py::TestPyMultiDictProxy::test_isdisjoint2", "tests/test_multidict.py::TestPyMultiDictProxy::test_items__contains", "tests/test_multidict.py::TestPyMultiDictProxy::test_items__repr__", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys__contains", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys__repr__", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys_is_set_equal", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys_is_set_greater", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys_is_set_greater_equal", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys_is_set_less", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys_is_set_less_equal", "tests/test_multidict.py::TestPyMultiDictProxy::test_keys_is_set_not_equal", "tests/test_multidict.py::TestPyMultiDictProxy::test_ne", "tests/test_multidict.py::TestPyMultiDictProxy::test_or", "tests/test_multidict.py::TestPyMultiDictProxy::test_or_issue_410", "tests/test_multidict.py::TestPyMultiDictProxy::test_preserve_stable_ordering", "tests/test_multidict.py::TestPyMultiDictProxy::test_repr_issue_410", "tests/test_multidict.py::TestPyMultiDictProxy::test_sub", "tests/test_multidict.py::TestPyMultiDictProxy::test_sub_issue_410", "tests/test_multidict.py::TestPyMultiDictProxy::test_values__contains", "tests/test_multidict.py::TestPyMultiDictProxy::test_values__repr__", "tests/test_multidict.py::TestPyMultiDictProxy::test_xor", "tests/test_multidict.py::TestPyMultiDictProxy::test_xor_issue_410", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_basics", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_copy", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_exposed_names", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_get", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_getall", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_items__repr__", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_keys__repr__", "tests/test_multidict.py::TestPyCIMultiDictProxy::test_values__repr__", "tests/test_multidict.py::PyMutableMultiDictTests::test__iter__", "tests/test_multidict.py::PyMutableMultiDictTests::test__repr__", "tests/test_multidict.py::PyMutableMultiDictTests::test_add", "tests/test_multidict.py::PyMutableMultiDictTests::test_and", "tests/test_multidict.py::PyMutableMultiDictTests::test_and_issue_410", "tests/test_multidict.py::PyMutableMultiDictTests::test_cannot_create_from_unaccepted", "tests/test_multidict.py::PyMutableMultiDictTests::test_clear", "tests/test_multidict.py::PyMutableMultiDictTests::test_copy", "tests/test_multidict.py::PyMutableMultiDictTests::test_del", "tests/test_multidict.py::PyMutableMultiDictTests::test_eq", "tests/test_multidict.py::PyMutableMultiDictTests::test_exposed_names", "tests/test_multidict.py::PyMutableMultiDictTests::test_extend", "tests/test_multidict.py::PyMutableMultiDictTests::test_extend_from_proxy", "tests/test_multidict.py::PyMutableMultiDictTests::test_getall", "tests/test_multidict.py::PyMutableMultiDictTests::test_getone", "tests/test_multidict.py::PyMutableMultiDictTests::test_instantiate__empty", "tests/test_multidict.py::PyMutableMultiDictTests::test_instantiate__from_arg0", "tests/test_multidict.py::PyMutableMultiDictTests::test_instantiate__from_arg0_dict", "tests/test_multidict.py::PyMutableMultiDictTests::test_instantiate__with_kwargs", "tests/test_multidict.py::PyMutableMultiDictTests::test_isdisjoint", "tests/test_multidict.py::PyMutableMultiDictTests::test_isdisjoint2", "tests/test_multidict.py::PyMutableMultiDictTests::test_items__contains", "tests/test_multidict.py::PyMutableMultiDictTests::test_keys__contains", "tests/test_multidict.py::PyMutableMultiDictTests::test_keys_is_set_equal", "tests/test_multidict.py::PyMutableMultiDictTests::test_keys_is_set_greater", "tests/test_multidict.py::PyMutableMultiDictTests::test_keys_is_set_greater_equal", "tests/test_multidict.py::PyMutableMultiDictTests::test_keys_is_set_less", "tests/test_multidict.py::PyMutableMultiDictTests::test_keys_is_set_less_equal", "tests/test_multidict.py::PyMutableMultiDictTests::test_keys_is_set_not_equal", "tests/test_multidict.py::PyMutableMultiDictTests::test_ne", "tests/test_multidict.py::PyMutableMultiDictTests::test_or", "tests/test_multidict.py::PyMutableMultiDictTests::test_or_issue_410", "tests/test_multidict.py::PyMutableMultiDictTests::test_pop", "tests/test_multidict.py::PyMutableMultiDictTests::test_pop_default", "tests/test_multidict.py::PyMutableMultiDictTests::test_pop_raises", "tests/test_multidict.py::PyMutableMultiDictTests::test_popitem", "tests/test_multidict.py::PyMutableMultiDictTests::test_popitem_empty_multidict", "tests/test_multidict.py::PyMutableMultiDictTests::test_repr_issue_410", "tests/test_multidict.py::PyMutableMultiDictTests::test_set_default", "tests/test_multidict.py::PyMutableMultiDictTests::test_sub", "tests/test_multidict.py::PyMutableMultiDictTests::test_sub_issue_410", "tests/test_multidict.py::PyMutableMultiDictTests::test_update", "tests/test_multidict.py::PyMutableMultiDictTests::test_values__contains", "tests/test_multidict.py::PyMutableMultiDictTests::test_xor", "tests/test_multidict.py::PyMutableMultiDictTests::test_xor_issue_410", "tests/test_multidict.py::PyCIMutableMultiDictTests::test__repr__", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_add", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_basics", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_clear", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_copy", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_ctor", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_del", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_delitem", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_exposed_names", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_extend", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_extend_from_proxy", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_extend_with_upstr", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_get", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_getall", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_items__repr__", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_keys__repr__", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_pop", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_pop_default", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_pop_raises", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_popitem", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_popitem_empty_multidict", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_set_default", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_setitem", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_update", "tests/test_multidict.py::PyCIMutableMultiDictTests::test_values__repr__", "tests/test_multidict.py::TestMultiDictProxy::test__iter__", "tests/test_multidict.py::TestMultiDictProxy::test__repr__", "tests/test_multidict.py::TestMultiDictProxy::test_and", "tests/test_multidict.py::TestMultiDictProxy::test_and_issue_410", "tests/test_multidict.py::TestMultiDictProxy::test_cannot_create_from_unaccepted", "tests/test_multidict.py::TestMultiDictProxy::test_copy", "tests/test_multidict.py::TestMultiDictProxy::test_eq", "tests/test_multidict.py::TestMultiDictProxy::test_exposed_names", "tests/test_multidict.py::TestMultiDictProxy::test_get", "tests/test_multidict.py::TestMultiDictProxy::test_getall", "tests/test_multidict.py::TestMultiDictProxy::test_getone", "tests/test_multidict.py::TestMultiDictProxy::test_instantiate__empty", "tests/test_multidict.py::TestMultiDictProxy::test_instantiate__from_arg0", "tests/test_multidict.py::TestMultiDictProxy::test_instantiate__from_arg0_dict", "tests/test_multidict.py::TestMultiDictProxy::test_instantiate__from_generator", "tests/test_multidict.py::TestMultiDictProxy::test_instantiate__with_kwargs", "tests/test_multidict.py::TestMultiDictProxy::test_isdisjoint", "tests/test_multidict.py::TestMultiDictProxy::test_isdisjoint2", "tests/test_multidict.py::TestMultiDictProxy::test_items__contains", "tests/test_multidict.py::TestMultiDictProxy::test_items__repr__", "tests/test_multidict.py::TestMultiDictProxy::test_keys__contains", "tests/test_multidict.py::TestMultiDictProxy::test_keys__repr__", "tests/test_multidict.py::TestMultiDictProxy::test_keys_is_set_equal", "tests/test_multidict.py::TestMultiDictProxy::test_keys_is_set_greater", "tests/test_multidict.py::TestMultiDictProxy::test_keys_is_set_greater_equal", "tests/test_multidict.py::TestMultiDictProxy::test_keys_is_set_less", "tests/test_multidict.py::TestMultiDictProxy::test_keys_is_set_less_equal", "tests/test_multidict.py::TestMultiDictProxy::test_keys_is_set_not_equal", "tests/test_multidict.py::TestMultiDictProxy::test_ne", "tests/test_multidict.py::TestMultiDictProxy::test_or", "tests/test_multidict.py::TestMultiDictProxy::test_or_issue_410", "tests/test_multidict.py::TestMultiDictProxy::test_preserve_stable_ordering", "tests/test_multidict.py::TestMultiDictProxy::test_repr_issue_410", "tests/test_multidict.py::TestMultiDictProxy::test_sub", "tests/test_multidict.py::TestMultiDictProxy::test_sub_issue_410", "tests/test_multidict.py::TestMultiDictProxy::test_values__contains", "tests/test_multidict.py::TestMultiDictProxy::test_values__repr__", "tests/test_multidict.py::TestMultiDictProxy::test_xor", "tests/test_multidict.py::TestMultiDictProxy::test_xor_issue_410", "tests/test_multidict.py::TestCIMultiDictProxy::test_basics", "tests/test_multidict.py::TestCIMultiDictProxy::test_copy", "tests/test_multidict.py::TestCIMultiDictProxy::test_exposed_names", "tests/test_multidict.py::TestCIMultiDictProxy::test_get", "tests/test_multidict.py::TestCIMultiDictProxy::test_getall", "tests/test_multidict.py::TestCIMultiDictProxy::test_items__repr__", "tests/test_multidict.py::TestCIMultiDictProxy::test_keys__repr__", "tests/test_multidict.py::TestCIMultiDictProxy::test_values__repr__", "tests/test_multidict.py::MutableMultiDictTests::test__iter__", "tests/test_multidict.py::MutableMultiDictTests::test__repr__", "tests/test_multidict.py::MutableMultiDictTests::test_add", "tests/test_multidict.py::MutableMultiDictTests::test_and", "tests/test_multidict.py::MutableMultiDictTests::test_and_issue_410", "tests/test_multidict.py::MutableMultiDictTests::test_cannot_create_from_unaccepted", "tests/test_multidict.py::MutableMultiDictTests::test_clear", "tests/test_multidict.py::MutableMultiDictTests::test_copy", "tests/test_multidict.py::MutableMultiDictTests::test_del", "tests/test_multidict.py::MutableMultiDictTests::test_eq", "tests/test_multidict.py::MutableMultiDictTests::test_exposed_names", "tests/test_multidict.py::MutableMultiDictTests::test_extend", "tests/test_multidict.py::MutableMultiDictTests::test_extend_from_proxy", "tests/test_multidict.py::MutableMultiDictTests::test_getall", "tests/test_multidict.py::MutableMultiDictTests::test_getone", "tests/test_multidict.py::MutableMultiDictTests::test_instantiate__empty", "tests/test_multidict.py::MutableMultiDictTests::test_instantiate__from_arg0", "tests/test_multidict.py::MutableMultiDictTests::test_instantiate__from_arg0_dict", "tests/test_multidict.py::MutableMultiDictTests::test_instantiate__from_generator", "tests/test_multidict.py::MutableMultiDictTests::test_instantiate__with_kwargs", "tests/test_multidict.py::MutableMultiDictTests::test_isdisjoint", "tests/test_multidict.py::MutableMultiDictTests::test_isdisjoint2", "tests/test_multidict.py::MutableMultiDictTests::test_items__contains", "tests/test_multidict.py::MutableMultiDictTests::test_keys__contains", "tests/test_multidict.py::MutableMultiDictTests::test_keys_is_set_equal", "tests/test_multidict.py::MutableMultiDictTests::test_keys_is_set_greater", "tests/test_multidict.py::MutableMultiDictTests::test_keys_is_set_greater_equal", "tests/test_multidict.py::MutableMultiDictTests::test_keys_is_set_less", "tests/test_multidict.py::MutableMultiDictTests::test_keys_is_set_less_equal", "tests/test_multidict.py::MutableMultiDictTests::test_keys_is_set_not_equal", "tests/test_multidict.py::MutableMultiDictTests::test_ne", "tests/test_multidict.py::MutableMultiDictTests::test_or", "tests/test_multidict.py::MutableMultiDictTests::test_or_issue_410", "tests/test_multidict.py::MutableMultiDictTests::test_pop", "tests/test_multidict.py::MutableMultiDictTests::test_pop_default", "tests/test_multidict.py::MutableMultiDictTests::test_pop_raises", "tests/test_multidict.py::MutableMultiDictTests::test_popitem", "tests/test_multidict.py::MutableMultiDictTests::test_popitem_empty_multidict", "tests/test_multidict.py::MutableMultiDictTests::test_repr_issue_410", "tests/test_multidict.py::MutableMultiDictTests::test_set_default", "tests/test_multidict.py::MutableMultiDictTests::test_sub", "tests/test_multidict.py::MutableMultiDictTests::test_sub_issue_410", "tests/test_multidict.py::MutableMultiDictTests::test_update", "tests/test_multidict.py::MutableMultiDictTests::test_values__contains", "tests/test_multidict.py::MutableMultiDictTests::test_xor", "tests/test_multidict.py::MutableMultiDictTests::test_xor_issue_410", "tests/test_multidict.py::CIMutableMultiDictTests::test__repr__", "tests/test_multidict.py::CIMutableMultiDictTests::test_add", "tests/test_multidict.py::CIMutableMultiDictTests::test_basics", "tests/test_multidict.py::CIMutableMultiDictTests::test_clear", "tests/test_multidict.py::CIMutableMultiDictTests::test_copy", "tests/test_multidict.py::CIMutableMultiDictTests::test_ctor", "tests/test_multidict.py::CIMutableMultiDictTests::test_del", "tests/test_multidict.py::CIMutableMultiDictTests::test_delitem", "tests/test_multidict.py::CIMutableMultiDictTests::test_exposed_names", "tests/test_multidict.py::CIMutableMultiDictTests::test_extend", "tests/test_multidict.py::CIMutableMultiDictTests::test_extend_from_proxy", "tests/test_multidict.py::CIMutableMultiDictTests::test_extend_with_upstr", "tests/test_multidict.py::CIMutableMultiDictTests::test_get", "tests/test_multidict.py::CIMutableMultiDictTests::test_getall", "tests/test_multidict.py::CIMutableMultiDictTests::test_items__repr__", "tests/test_multidict.py::CIMutableMultiDictTests::test_keys__repr__", "tests/test_multidict.py::CIMutableMultiDictTests::test_pop", "tests/test_multidict.py::CIMutableMultiDictTests::test_pop_default", "tests/test_multidict.py::CIMutableMultiDictTests::test_pop_raises", "tests/test_multidict.py::CIMutableMultiDictTests::test_popitem", "tests/test_multidict.py::CIMutableMultiDictTests::test_popitem_empty_multidict", "tests/test_multidict.py::CIMutableMultiDictTests::test_set_default", "tests/test_multidict.py::CIMutableMultiDictTests::test_setitem", "tests/test_multidict.py::CIMutableMultiDictTests::test_update", "tests/test_multidict.py::CIMutableMultiDictTests::test_values__repr__", "tests/test_multidict.py::TestPyUpStr::test_ctor", "tests/test_multidict.py::TestPyUpStr::test_ctor_buffer", "tests/test_multidict.py::TestPyUpStr::test_ctor_repr", "tests/test_multidict.py::TestPyUpStr::test_ctor_str", "tests/test_multidict.py::TestPyUpStr::test_ctor_str_uppercase", "tests/test_multidict.py::TestPyUpStr::test_upper", "tests/test_multidict.py::TestUpStr::test_ctor", "tests/test_multidict.py::TestUpStr::test_ctor_buffer", "tests/test_multidict.py::TestUpStr::test_ctor_repr", "tests/test_multidict.py::TestUpStr::test_ctor_str", "tests/test_multidict.py::TestUpStr::test_ctor_str_uppercase", "tests/test_multidict.py::TestUpStr::test_upper", "tests/test_multidict.py::TestPyTypes::test_create_ci_multidict_proxy_from_multidict", "tests/test_multidict.py::TestPyTypes::test_create_cimultidict_proxy_from_nonmultidict", "tests/test_multidict.py::TestPyTypes::test_create_multidict_proxy_from_cimultidict", "tests/test_multidict.py::TestPyTypes::test_create_multidict_proxy_from_nonmultidict", "tests/test_multidict.py::TestPyTypes::test_dict_not_inherited_from_proxy", "tests/test_multidict.py::TestPyTypes::test_dicts", "tests/test_multidict.py::TestPyTypes::test_proxies", "tests/test_multidict.py::TestPyTypes::test_proxy_not_inherited_from_dict", "tests/test_multidict.py::TestTypes::test_create_ci_multidict_proxy_from_multidict", "tests/test_multidict.py::TestTypes::test_create_cimultidict_proxy_from_nonmultidict", "tests/test_multidict.py::TestTypes::test_create_multidict_proxy_from_cimultidict", "tests/test_multidict.py::TestTypes::test_create_multidict_proxy_from_nonmultidict", "tests/test_multidict.py::TestTypes::test_dict_not_inherited_from_proxy", "tests/test_multidict.py::TestTypes::test_dicts", "tests/test_multidict.py::TestTypes::test_proxies", "tests/test_multidict.py::TestTypes::test_proxy_not_inherited_from_dict" ]
[]
Apache License 2.0
571
cherrypy__cherrypy-1442
adb7ff5aa1f48506e2838a22176c43c6f3aa4fb5
2016-06-05 23:10:54
adb7ff5aa1f48506e2838a22176c43c6f3aa4fb5
jaraco: This idea is a very cool one. And the implementation is so short and concise, signs of an elegant implementation. I have a couple of comments to make about the specific implementation, but I don't see why this change couldn't be rolled into an upcoming release in short order.
diff --git a/CHANGES.txt b/CHANGES.txt index 20877f63..b06461ad 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -4,6 +4,7 @@ * Issue #1411: Fix issue where autoreload fails when the host interpreter for CherryPy was launched using ``python -m``. +* #1441: Added tool to automatically convert request params. 6.1.0 ----- diff --git a/cherrypy/_cptools.py b/cherrypy/_cptools.py index 54c63734..060ca76f 100644 --- a/cherrypy/_cptools.py +++ b/cherrypy/_cptools.py @@ -533,5 +533,6 @@ _d.json_in = Tool('before_request_body', jsontools.json_in, priority=30) _d.json_out = Tool('before_handler', jsontools.json_out, priority=30) _d.auth_basic = Tool('before_handler', auth_basic.basic_auth, priority=1) _d.auth_digest = Tool('before_handler', auth_digest.digest_auth, priority=1) +_d.params = Tool('before_handler', cptools.convert_params) del _d, cptools, encoding, auth, static diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py index fbed0e23..073216e0 100644 --- a/cherrypy/lib/cptools.py +++ b/cherrypy/lib/cptools.py @@ -630,3 +630,21 @@ def autovary(ignore=None, debug=False): v.sort() resp_h['Vary'] = ', '.join(v) request.hooks.attach('before_finalize', set_response_header, 95) + + +def convert_params(exception=ValueError, error=400): + """Convert request params based on function annotations, with error handling. + + exception + Exception class to catch. + + status + The HTTP error code to return to the client on failure. + """ + request = cherrypy.serving.request + types = request.handler.callable.__annotations__ + try: + for key in set(types).intersection(request.params): + request.params[key] = types[key](request.params[key]) + except exception as exc: + raise cherrypy.HTTPError(error, str(exc))
Convert request params based on function annotations. With the increasing focus on [type hints](https://docs.python.org/3.5/library/typing.html) in Python, having a tool which automatically converted query params (with exception handling) would be a nice feature. It's common for apps to have boilerplate code for [converting request params](http://stackoverflow.com/questions/32774024/), and returning 400-levels errors on failure. ``` @cherrypy.tools.params(exception=ValueError) def resource(self, limit: int): assert isinstance(limit, int) # a ValueError would have already raised a 400 ```
cherrypy/cherrypy
diff --git a/cherrypy/test/test_params.py b/cherrypy/test/test_params.py new file mode 100644 index 00000000..2d57c279 --- /dev/null +++ b/cherrypy/test/test_params.py @@ -0,0 +1,55 @@ +import sys +import cherrypy +from cherrypy.test import helper + + +class ParamsTest(helper.CPWebCase): + @staticmethod + def setup_server(): + class Root: + @cherrypy.expose + @cherrypy.tools.params() + def resource(self, limit=None, sort=None): + return type(limit).__name__ + # for testing on Py 2 + resource.__annotations__ = {'limit': int} + conf = {'/': {'tools.params.on': True}} + cherrypy.tree.mount(Root(), config=conf) + + def test_pass(self): + self.getPage('/resource') + self.assertStatus(200) + self.assertBody('NoneType') + + self.getPage('/resource?limit=0') + self.assertStatus(200) + self.assertBody('int') + + def test_error(self): + self.getPage('/resource?limit=') + self.assertStatus(400) + self.assertInBody('invalid literal for int') + + cherrypy.config['tools.params.error'] = 422 + self.getPage('/resource?limit=') + self.assertStatus(422) + self.assertInBody('invalid literal for int') + + cherrypy.config['tools.params.exception'] = TypeError + self.getPage('/resource?limit=') + self.assertStatus(500) + + def test_syntax(self): + if sys.version_info < (3,): + return self.skip("skipped (Python 3 only)") + exec("""class Root: + @cherrypy.expose + @cherrypy.tools.params() + def resource(self, limit: int): + return type(limit).__name__ +conf = {'/': {'tools.params.on': True}} +cherrypy.tree.mount(Root(), config=conf)""") + + self.getPage('/resource?limit=0') + self.assertStatus(200) + self.assertBody('int')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
6.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "mock", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 -e git+https://github.com/cherrypy/cherrypy.git@adb7ff5aa1f48506e2838a22176c43c6f3aa4fb5#egg=CherryPy importlib-metadata==4.8.3 iniconfig==1.1.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: cherrypy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/cherrypy
[ "cherrypy/test/test_params.py::ParamsTest::test_error", "cherrypy/test/test_params.py::ParamsTest::test_pass", "cherrypy/test/test_params.py::ParamsTest::test_syntax", "cherrypy/test/test_params.py::ParamsTest::test_gc" ]
[]
[]
[]
BSD 3-Clause "New" or "Revised" License
572
kytos__python-openflow-50
9b9c0c3e86c73aaebdcb57bda00feeefbdbcfe09
2016-06-06 16:10:00
9b9c0c3e86c73aaebdcb57bda00feeefbdbcfe09
diff --git a/pyof/v0x01/common/header.py b/pyof/v0x01/common/header.py index 7cb2684..2521ebe 100644 --- a/pyof/v0x01/common/header.py +++ b/pyof/v0x01/common/header.py @@ -67,7 +67,7 @@ class Header(base.GenericStruct): :param length: Length of the message, including the header itself """ version = basic_types.UBInt8() - message_type = basic_types.UBInt8() + message_type = basic_types.UBInt8(enum_ref=Type) length = basic_types.UBInt16() xid = basic_types.UBInt32() diff --git a/pyof/v0x01/common/phy_port.py b/pyof/v0x01/common/phy_port.py index df242a7..bdcc6dc 100644 --- a/pyof/v0x01/common/phy_port.py +++ b/pyof/v0x01/common/phy_port.py @@ -3,6 +3,8 @@ # System imports import enum +from collections import OrderedDict as _OD + # Third-party imports # Local source tree imports @@ -11,30 +13,39 @@ from pyof.v0x01.foundation import basic_types # Enums - -class PortConfig(enum.Enum): - """Flags to indicate behavior of the physical port. - - These flags are used in OFPPhyPort to describe the current configuration. - They are used in the OFPPortMod message to configure the port's behavior. - - Enums: - OFPPC_PORT_DOWN # Port is administratively down. - OFPPC_NO_STP # Disable 802.1D spanning tree on port. - OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree. - OFPPC_NO_RECV_STP # Drop received 802.1D STP packets. - OFPPC_NO_FLOOD # Do not include this port when flooding. - OFPPC_NO_FWD # Drop packets forwarded to port. - OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port. - """ - - OFPPC_PORT_DOWN = 1 << 0 - OFPPC_NO_STP = 1 << 1 - OFPPC_NO_RECV = 1 << 2 - OFPPC_NO_RECV_STP = 1 << 3 - OFPPC_FLOOD = 1 << 4 - OFPPC_NO_FWD = 1 << 5 - OFPPC_NO_PACKET_IN = 1 << 6 +class PortConfig(base.GenericBitMask): + _enum = _OD(OFPC_PORT_DOWN = 1 << 0, + OFPPC_NO_STP = 1 << 1, + OFPPC_NO_RECV = 1 << 2, + OFPPC_NO_RECV_STP = 1 << 3, + OFPPC_FLOOD = 1 << 4, + OFPPC_NO_FWD = 1 << 5, + OFPPC_NO_PACKET_IN = 1 << 6) + + +#class PortConfig(enum.Enum): +# """Flags to indicate behavior of the physical port. +# +# These flags are used in OFPPhyPort to describe the current configuration. +# They are used in the OFPPortMod message to configure the port's behavior. +# +# Enums: +# OFPPC_PORT_DOWN # Port is administratively down. +# OFPPC_NO_STP # Disable 802.1D spanning tree on port. +# OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree. +# OFPPC_NO_RECV_STP # Drop received 802.1D STP packets. +# OFPPC_NO_FLOOD # Do not include this port when flooding. +# OFPPC_NO_FWD # Drop packets forwarded to port. +# OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port. +# """ +# +# OFPPC_PORT_DOWN = 1 << 0 +# OFPPC_NO_STP = 1 << 1 +# OFPPC_NO_RECV = 1 << 2 +# OFPPC_NO_RECV_STP = 1 << 3 +# OFPPC_FLOOD = 1 << 4 +# OFPPC_NO_FWD = 1 << 5 +# OFPPC_NO_PACKET_IN = 1 << 6 class PortState(enum.Enum): @@ -130,7 +141,7 @@ class PortFeatures(enum.Enum): # Classes -class PhyPort(base.GenericMessage): +class PhyPort(base.GenericStruct): """ Description of a physical port. @@ -157,7 +168,7 @@ class PhyPort(base.GenericMessage): port_no = basic_types.UBInt16() hw_addr = basic_types.HWAddress() name = basic_types.Char(length=base.OFP_MAX_PORT_NAME_LEN) - config = basic_types.UBInt32() + config = basic_types.UBInt32(enum_ref=PortConfig) state = basic_types.UBInt32() curr = basic_types.UBInt32() advertised = basic_types.UBInt32() diff --git a/pyof/v0x01/controller2switch/flow_mod.py b/pyof/v0x01/controller2switch/flow_mod.py index d300e80..f8467c5 100644 --- a/pyof/v0x01/controller2switch/flow_mod.py +++ b/pyof/v0x01/controller2switch/flow_mod.py @@ -2,12 +2,13 @@ # System imports import enum - +from collections import OrderedDict as _OD # Third-party imports # Local source tree imports from pyof.v0x01.common import flow_match from pyof.v0x01.common import header as of_header +from pyof.v0x01.common import phy_port from pyof.v0x01.controller2switch import common from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types @@ -27,23 +28,23 @@ class FlowModCommand(enum.Enum): OFPFC_DELETE_STRICT # Strictly match wildcards and priority """ - OFPFC_ADD = 1 - OFPFC_MODIFY = 2 - OFPFC_MODIFY_STRICT = 3 - OFPFC_DELETE = 4 - OFPFC_DELETE_STRICT = 5 + OFPFC_ADD = 0 + OFPFC_MODIFY = 1 + OFPFC_MODIFY_STRICT = 2 + OFPFC_DELETE = 3 + OFPFC_DELETE_STRICT = 4 -class FlowModFlags(enum.Enum): +class FlowModFlags(base.GenericBitMask): """Types to be used in Flags field""" - - #: Send flow removed message when flow expires or is deleted - OFPFF_SEND_FLOW_REM = 1 << 0 - #: Check for overlapping entries first - OFPFF_CHECK_OVERLAP = 1 << 1 - #: Remark this is for emergency - OFPFF_EMERG = 1 << 2 - + _enum = _OD( + #: Send flow removed message when flow expires or is deleted + OFPFF_SEND_FLOW_REM = 1 << 0, + #: Check for overlapping entries first + OFPFF_CHECK_OVERLAP = 1 << 1, + #: Remark this is for emergency + OFPFF_EMERG = 1 << 2 + ) # Classes @@ -71,13 +72,13 @@ class FlowMod(base.GenericMessage): header = of_header.Header() match = flow_match.Match() cookie = basic_types.UBInt64() - command = basic_types.UBInt16() + command = basic_types.UBInt16(enum_ref=FlowModCommand) idle_timeout = basic_types.UBInt16() hard_timeout = basic_types.UBInt16() priority = basic_types.UBInt16() buffer_id = basic_types.UBInt32() - out_port = basic_types.UBInt16() - flags = basic_types.UBInt16() + out_port = basic_types.UBInt16(enum_ref=phy_port.Port) + flags = basic_types.UBInt16(enum_ref=FlowModFlags) actions = common.ListOfActions() def __init__(self, xid=None, match=None, cookie=None, command=None, diff --git a/pyof/v0x01/foundation/base.py b/pyof/v0x01/foundation/base.py index 3c4ac01..b1b9f65 100644 --- a/pyof/v0x01/foundation/base.py +++ b/pyof/v0x01/foundation/base.py @@ -59,14 +59,15 @@ class GenericType(object): Attributes like `UBInt8`, `UBInt16`, `HWAddress` amoung others uses this class as base. """ - def __init__(self, val=None): - self._value = val + def __init__(self, value=None, enum_ref=None): + self._value = value + self._enum_ref = enum_ref def __repr__(self): return "{}({})".format(self.__class__.__name__, self._value) def __str__(self): - return '{}: {}'.format(self.__class__.__name__, str(self._value)) + return '<{}: {}>'.format(self.__class__.__name__, str(self._value)) def __eq__(self, other): return self._value == other @@ -88,11 +89,15 @@ class GenericType(object): def pack(self): """Pack the valeu as a binary representation.""" - if type(self._value.__class__) is enum.EnumMeta: - # Gets the respective value from the Enum - value = self._value.value + if self.is_enum(): + if issubclass(type(self._value), GenericBitMask): + value = self._value.bitmask + else: + # Gets the respective value from the Enum + value = self._value.value else: value = self._value + try: return struct.pack(self._fmt, value) except struct.error as err: @@ -116,9 +121,11 @@ class GenericType(object): # the enum name/reference ? try: self._value = struct.unpack_from(self._fmt, buff, offset)[0] + if self._enum_ref: + self._value = self._enum_ref(self._value) except struct.error: - raise exceptions.Exception("Error while unpacking" - "data from buffer") + raise exceptions.UnpackException("Error while unpacking" + "data from buffer") def get_size(self): """Return the size in bytes of this attribute. """ @@ -136,8 +143,13 @@ class GenericType(object): raise def value(self): - #TODO: Review this value._value.value (For enums) - return self._value + if isinstance(self._value, enum.Enum): + return self._value.value + else: + return self._value + + def is_enum(self): + return self._enum_ref is not None class MetaStruct(type): @@ -155,7 +167,7 @@ class MetaStruct(type): return type.__new__(self, name, bases, classdict) -class GenericStruct(object): +class GenericStruct(object, metaclass=MetaStruct): """Class that will be used by all OpenFlow structs. So, if you need insert a method that will be used for all Structs, here is @@ -165,7 +177,6 @@ class GenericStruct(object): has a list of attributes and theses attributes can be of struct type too. """ - __metaclass__ = MetaStruct def __init__(self, *args, **kwargs): for _attr in self.__ordered__: @@ -199,8 +210,7 @@ class GenericStruct(object): return message def _attributes(self): - """ - turns an generator with each attribute from the current instance. + """Returns a generator with each attribute from the current instance. This attributes are coherced by the expected class for that attribute. """ @@ -218,7 +228,7 @@ class GenericStruct(object): # Verifications for classes derived from list type if not isinstance(attr, _class): attr = _class(attr) - yield attr + yield (_attr, attr) def _attr_fits_into_class(attr, _class): if not isinstance(attr, _class): @@ -259,8 +269,7 @@ class GenericStruct(object): raise Exception() else: size = 0 - for _attr in self.__ordered__: - _class = self.__ordered__[_attr] + for _attr, _class in self.__ordered__.items(): attr = getattr(self, _attr) if _class.__name__ is 'PAD': size += attr.get_size() @@ -289,15 +298,20 @@ class GenericStruct(object): raise exceptions.ValidationError(error_msg) else: message = b'' - for attr in self._attributes(): - try: + for attr_name, attr_class in self.__ordered__.items(): + attr = getattr(self, attr_name) + class_attr = getattr(self.__class__, attr_name) + if isinstance(attr, attr_class): message += attr.pack() - except: - raise exceptions.AttributeTypeError(attr, type(attr), - type(attr)) + elif class_attr.is_enum(): + message += attr_class(value = attr, + enum_ref= class_attr._enum_ref).pack() + else: + message += attr_class(attr).pack() + return message - def unpack(self, buff): + def unpack(self, buff, offset=0): """Unpack a binary struct into the object attributes. This method updated the object attributes based on the unpacked data @@ -308,12 +322,24 @@ class GenericStruct(object): """ #TODO: Remove any referency to header here, this is a struct, not a # message. - begin = 0 - for attr in self._attributes: - if attr.__class__.__name__ != "Header": + begin = offset + + # TODO: Refact, ugly code + for attr_name, attr_class in self.__ordered__.items(): + if attr_class.__name__ != "PAD": + class_attr = getattr(self.__class__, attr_name) + attr = attr_class() attr.unpack(buff, offset=begin) - setattr(self, attr.__name__, attr) - begin += attr.get_size() + + if issubclass(attr_class, GenericType) and class_attr.is_enum(): + #raise Exception(class_attr._enum_ref) + attr = class_attr._enum_ref(attr._value) + setattr(self, attr_name, attr) + + if issubclass(attr_class, GenericType): + attr = attr_class() + + begin += attr.get_size() def is_valid(self): """Checks if all attributes on struct is valid. @@ -341,6 +367,34 @@ class GenericMessage(GenericStruct): .. note:: A Message on this library context is like a Struct but has a also a `header` attribute. """ + def unpack(self, buff, offset=0): + """Unpack a binary message. + + This method updated the object attributes based on the unpacked + data from the buffer binary message. It is an inplace method, + and it receives the binary data of the message without the header. + There is no return on this method + + :param buff: binary data package to be unpacked + without the first 8 bytes (header) + """ + begin = offset + + for attr_name, attr_class in self.__ordered__.items(): + if attr_class.__name__ != "Header": + if attr_class.__name__ != "PAD": + class_attr = getattr(self.__class__, attr_name) + attr = attr_class() + attr.unpack(buff, offset=begin) + begin += attr.get_size() + + if issubclass(attr_class, GenericType) and \ + class_attr.is_enum(): + attr = class_attr._enum_ref(attr._value) + setattr(self, attr_name, attr) + else: + begin += attr.get_size() + def _validate_message_length(self): if not self.header.length == self.get_size(): return False @@ -393,3 +447,33 @@ class GenericMessage(GenericStruct): size. """ self.header.length = self.get_size() + + +class MetaBitMask(type): + def __getattr__(cls, name): + return cls._enum[name] + + def __dir__(cls): + res = dir(type(cls)) + list(cls.__dict__.keys()) + if cls is not GenericBitMask: + res.extend(cls._enum) + return res + + +class GenericBitMask(object, metaclass=MetaBitMask): + def __init__(self, bitmask=None): + self.bitmask = bitmask + + def __str__(self): + return "<%s: %s>" % (self.__class__.__name__, self.names) + + def __repr__(self): + return "<%s(%s)>" % (self.__class__.__name__, self.bitmask) + + @property + def names(self): + result = [] + for key, value in self._enum.items(): + if value & self.bitmask: + result.append(key) + return result diff --git a/pyof/v0x01/foundation/basic_types.py b/pyof/v0x01/foundation/basic_types.py index 74fbd58..2e49b13 100644 --- a/pyof/v0x01/foundation/basic_types.py +++ b/pyof/v0x01/foundation/basic_types.py @@ -120,13 +120,62 @@ class Char(base.GenericType): :param value: the character to be build. :param length: the character size. """ - if value: - self._value = value + super().__init__(value) self.length = length self._fmt = '!{}{}'.format(self.length, 's') -class FixedTypeList(list): +class HWAddress(base.GenericType): + """Defines a hardware address""" + + def __init__(self, hw_address=b'000000'): + super().__init__(hw_address) + + def pack(self): + # struct.pack('!6B', *[int(x, 16) for x in self._value.split(':')]) + value = self._value.split(':') + return struct.pack('!6B', *[int(x, 16) for x in value]) + + def unpack(self, buff, offset=0): + # value = ':'.join([hex(x)[2:] for x in struct.unpack('!6B', buff)]) + unpacked_data = struct.unpack('!6B', buff[offset:offset+6]) + transformed_data = ':'.join([hex(x)[2:] for x in unpacked_data]) + self._value = transformed_data + + def get_size(self): + return 6 + + +class BinaryData(base.GenericType): + """Class to create objects that represents binary data + + This will be used on the 'data' attribute from + packet_out and packet_in messages. + + Both the 'pack' and 'unpack' methods will return the binary data itself. + get_size method will return the size of the instance using python 'len' + """ + + def __init__(self, value=b''): + super().__init__(value) + + def pack(self): + if type(self._value) is bytes: + if len(self._value) > 0: + return self._value + else: + return b'' + else: + raise exceptions.NotBinarydata() + + def unpack(self, buff): + self._value = buff + + def get_size(self): + return len(self._value) + + +class FixedTypeList(list, base.GenericStruct): """Creates a List that will receive OFP Classes""" _pyof_class = None @@ -201,15 +250,15 @@ class FixedTypeList(list): offset: used if we need to shift the beginning of the data """ item_size = self._pyof_class().get_size() - binary_items = [buff[i:i+2] for i in range(offset, len(buff), - item_size)] + binary_items = [buff[i:i+item_size] for i in range(offset, len(buff), + item_size)] for binary_item in binary_items: item = self._pyof_class() item.unpack(binary_item) self.append(item) -class ConstantTypeList(list): +class ConstantTypeList(list, base.GenericStruct): """Creates a List that will only allow objects of the same type (class) to be inserted""" def __init__(self, items=[]): @@ -298,51 +347,3 @@ class ConstantTypeList(list): self.append(item) -class HWAddress(base.GenericType): - """Defines a hardware address""" - - def __init__(self, hw_address=None): - self._value = hw_address - - def pack(self): - # struct.pack('!6B', *[int(x, 16) for x in self._value.split(':')]) - value = self._value.split(':') - return struct.pack('!6B', *[int(x, 16) for x in value]) - - def unpack(self, buff, offset=0): - # value = ':'.join([hex(x)[2:] for x in struct.unpack('!6B', buff)]) - unpacked_data = struct.unpack('!6B', buff) - transformed_data = ':'.join([hex(x)[2:] for x in unpacked_data]) - self._value = transformed_data - - def get_size(self): - return 6 - - -class BinaryData(base.GenericType): - """Class to create objects that represents binary data - - This will be used on the 'data' attribute from - packet_out and packet_in messages. - - Both the 'pack' and 'unpack' methods will return the binary data itself. - get_size method will return the size of the instance using python 'len' - """ - - def __init__(self, value=b''): - super().__init__(value) - - def pack(self): - if type(self._value) is bytes: - if len(self._value) > 0: - return self._value - else: - return b'' - else: - raise exceptions.NotBinarydata() - - def unpack(self, buff): - self._value = buff - - def get_size(self): - return len(self._value) diff --git a/pyof/v0x01/foundation/exceptions.py b/pyof/v0x01/foundation/exceptions.py index 604f00a..8da17c0 100644 --- a/pyof/v0x01/foundation/exceptions.py +++ b/pyof/v0x01/foundation/exceptions.py @@ -65,3 +65,7 @@ class ValidationError(Exception): self.msg = msg def __str__(self): return self.msg + + +class UnpackException(Exception): + pass
Error on Descriptor utilization The way we are using Descriptors is incurring in a wrong behavior when instantiating two objects of the same class.
kytos/python-openflow
diff --git a/tests/v0x01/test_common/test_header.py b/tests/v0x01/test_common/test_header.py index 3827f84..8435aba 100644 --- a/tests/v0x01/test_common/test_header.py +++ b/tests/v0x01/test_common/test_header.py @@ -1,5 +1,6 @@ import unittest +import os from pyof.v0x01.common import header as of_header @@ -28,8 +29,16 @@ class TestHeader(unittest.TestCase): packed_header = b'\x01\x00\x00\x00\x00\x00\x00\x01' self.assertEqual(self.message.pack(), packed_header) - @unittest.skip('Not yet implemented') def test_unpack(self): """[Common/Header] - unpacking Hello""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_hello.dat') + f = open(filename,'rb') + self.message.unpack(f.read(8)) + + self.assertEqual(self.message.length, 8) + self.assertEqual(self.message.xid, 1) + self.assertEqual(self.message.message_type, of_header.Type.OFPT_HELLO) + self.assertEqual(self.message.version, 1) + + f.close() diff --git a/tests/v0x01/test_controller2switch/test_barrier_reply.py b/tests/v0x01/test_controller2switch/test_barrier_reply.py index bfe59da..d5679e3 100644 --- a/tests/v0x01/test_controller2switch/test_barrier_reply.py +++ b/tests/v0x01/test_controller2switch/test_barrier_reply.py @@ -1,25 +1,30 @@ import unittest +import os from pyof.v0x01.controller2switch import barrier_reply +from pyof.v0x01.common import header as of_header class TestBarrierReply(unittest.TestCase): def setUp(self): - self.message = barrier_reply.BarrierReply(xid=1) + self.message = barrier_reply.BarrierReply(xid=5) + self.head = of_header.Header() def test_get_size(self): """[Controller2Switch/BarrierReply] - size 8""" self.assertEqual(self.message.get_size(), 8) - @unittest.skip('Not yet implemented') + @unittest.skip('Need to implement length update') def test_pack(self): """[Controller2Switch/BarrierReply] - packing""" - # TODO - pass + packed_msg = b'\x01\x13\x00\x08\x00\x00\x00\x05' + self.assertEqual(self.message.pack(), packed_msg) - @unittest.skip('Not yet implemented') def test_unpack(self): """[Controller2Switch/BarrierReply] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_barrier_reply.dat') + with open(filename,'rb') as f: + self.head.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None) diff --git a/tests/v0x01/test_controller2switch/test_barrier_request.py b/tests/v0x01/test_controller2switch/test_barrier_request.py index d92fbc5..355d71e 100644 --- a/tests/v0x01/test_controller2switch/test_barrier_request.py +++ b/tests/v0x01/test_controller2switch/test_barrier_request.py @@ -1,12 +1,14 @@ import unittest +import os from pyof.v0x01.controller2switch import barrier_request - +from pyof.v0x01.common import header as of_header class TestBarrierRequest(unittest.TestCase): def setUp(self): self.message = barrier_request.BarrierRequest(xid=1) + self.head = of_header.Header(xid=5) def test_get_size(self): """[Controller2Switch/BarrierRequest] - size 8""" @@ -18,8 +20,10 @@ class TestBarrierRequest(unittest.TestCase): # TODO pass - @unittest.skip('Not yet implemented') def test_unpack(self): """[Controller2Switch/BarrierRequest] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_barrier_request.dat') + with open(filename, 'rb') as f: + self.head.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None) diff --git a/tests/v0x01/test_controller2switch/test_features_reply.py b/tests/v0x01/test_controller2switch/test_features_reply.py index b59f6b1..da020c6 100644 --- a/tests/v0x01/test_controller2switch/test_features_reply.py +++ b/tests/v0x01/test_controller2switch/test_features_reply.py @@ -1,12 +1,15 @@ import unittest +import os from pyof.v0x01.common import action from pyof.v0x01.controller2switch import features_reply +from pyof.v0x01.common import header as of_header class TestSwitchFeatures(unittest.TestCase): def setUp(self): + self.head = of_header.Header() self.message = features_reply.SwitchFeatures() self.message.header.xid = 1 self.message.datapath_id = 1 @@ -26,8 +29,10 @@ class TestSwitchFeatures(unittest.TestCase): # TODO pass - @unittest.skip('Not yet implemented') def test_unpack(self): """[Controller2Switch/FeaturesReply] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_features_reply.dat') + with open(filename, 'rb') as f: + self.head.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None) diff --git a/tests/v0x01/test_controller2switch/test_features_request.py b/tests/v0x01/test_controller2switch/test_features_request.py index 54d1121..5822823 100644 --- a/tests/v0x01/test_controller2switch/test_features_request.py +++ b/tests/v0x01/test_controller2switch/test_features_request.py @@ -1,11 +1,14 @@ import unittest +import os from pyof.v0x01.controller2switch import features_request +from pyof.v0x01.common import header as of_header class TestFeaturesRequest(unittest.TestCase): def setUp(self): self.message = features_request.FeaturesRequest(1) + self.head = of_header.Header() def test_get_size(self): """[Controller2Switch/FeaturesRequest] - size 8""" @@ -17,8 +20,11 @@ class TestFeaturesRequest(unittest.TestCase): # TODO pass - @unittest.skip('Not yet implemented') def test_unpack(self): """[Controller2Switch/FeaturesRequest] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_features_request.dat') + f = open(filename, 'rb') + self.head.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None) + f.close() diff --git a/tests/v0x01/test_controller2switch/test_flow_mod.py b/tests/v0x01/test_controller2switch/test_flow_mod.py index 7e69470..8d6eff2 100644 --- a/tests/v0x01/test_controller2switch/test_flow_mod.py +++ b/tests/v0x01/test_controller2switch/test_flow_mod.py @@ -1,13 +1,17 @@ import unittest +import os from pyof.v0x01.common import flow_match from pyof.v0x01.common import phy_port from pyof.v0x01.controller2switch import flow_mod +from pyof.v0x01.common import header as of_header class TestFlowMod(unittest.TestCase): def setUp(self): + self.head = of_header.Header() + self.message = flow_mod.FlowMod() self.message.header.xid = 1 self.message.command = flow_mod.FlowModCommand.OFPFC_ADD @@ -20,8 +24,8 @@ class TestFlowMod(unittest.TestCase): self.message.out_port = phy_port.Port.OFPP_NONE self.message.flags = flow_mod.FlowModFlags.OFPFF_EMERG self.message.match.in_port = 80 - self.message.match.dl_src = [1, 2, 3, 4, 5, 6] - self.message.match.dl_dst = [1, 2, 3, 4, 5, 6] + self.message.match.dl_src = '1a:2b:3c:4d:5e:6f' + self.message.match.dl_dst = '6a:5b:4c:43:2e:1f' self.message.match.dl_vlan = 1 self.message.match.dl_vlan_pcp = 1 self.message.match.dl_type = 1 @@ -42,8 +46,24 @@ class TestFlowMod(unittest.TestCase): # TODO pass - @unittest.skip('Not yet implemented') - def test_unpack(self): + def test_unpack_add(self): """[Controller2Switch/FlowMod] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_flow_add.dat') + with open(filename,'rb') as f: + self.head.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None) + + self.assertEqual(self.message.command, + flow_mod.FlowModCommand.OFPFC_ADD) + + def test_unpack_delete(self): + """[Controller2Switch/FlowMod] - unpacking""" + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_flow_delete.dat') + with open(filename,'rb') as f: + self.head.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None) + + self.assertEqual(self.message.command, + flow_mod.FlowModCommand.OFPFC_DELETE) diff --git a/tests/v0x01/test_symmetric/test_echo_reply.py b/tests/v0x01/test_symmetric/test_echo_reply.py index e9ccaa3..347bfc6 100644 --- a/tests/v0x01/test_symmetric/test_echo_reply.py +++ b/tests/v0x01/test_symmetric/test_echo_reply.py @@ -2,17 +2,20 @@ import os import unittest from pyof.v0x01.symmetric import echo_reply +from pyof.v0x01.common import header as of_header class TestEchoReply(unittest.TestCase): def setUp(self): self.message = echo_reply.EchoReply(xid=0) + self.header = of_header.Header() def test_get_size(self): """[Symmetric/EchoReply] - size 8""" self.assertEqual(self.message.get_size(), 8) + @unittest.skip('Need to implement length update') def test_pack(self): """[Symmetric/EchoReply] - packing""" filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), @@ -22,8 +25,11 @@ class TestEchoReply(unittest.TestCase): packed_msg = b'\x01\x03\x00\x08\x00\x00\x00\x00' self.assertEqual(self.message.pack(), packed_msg) - @unittest.skip('Not yet implemented') def test_unpack(self): """[Symmetric/Reply] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_echo_reply.dat') + with open(filename,'rb') as f: + self.header.unpack(f.read(8)) + msg_size = self.header.length._value + self.assertEqual(self.message.unpack(f.read()), None) diff --git a/tests/v0x01/test_symmetric/test_echo_request.py b/tests/v0x01/test_symmetric/test_echo_request.py index a69a0ea..3259ccd 100644 --- a/tests/v0x01/test_symmetric/test_echo_request.py +++ b/tests/v0x01/test_symmetric/test_echo_request.py @@ -2,17 +2,20 @@ import os import unittest from pyof.v0x01.symmetric import echo_request +from pyof.v0x01.common import header as of_header class TestEchoRequest(unittest.TestCase): def setUp(self): self.message = echo_request.EchoRequest(xid=0) + self.header = of_header.Header() def test_get_size(self): """[Symmetric/EchoRequest] - size 8""" self.assertEqual(self.message.get_size(), 8) + @unittest.skip('Need to implement length update') def test_pack(self): """[Symmetric/EchoRequest] - packing""" filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), @@ -22,8 +25,10 @@ class TestEchoRequest(unittest.TestCase): packed_msg = b'\x01\x02\x00\x08\x00\x00\x00\x00' self.assertEqual(self.message.pack(), packed_msg) - @unittest.skip('Not yet implemented') def test_unpack(self): """[Symmetric/EchoRequest] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_echo_request.dat') + with open(filename,'rb') as f: + self.header.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None) diff --git a/tests/v0x01/test_symmetric/test_hello.py b/tests/v0x01/test_symmetric/test_hello.py index 2ed022f..d4bbd1d 100644 --- a/tests/v0x01/test_symmetric/test_hello.py +++ b/tests/v0x01/test_symmetric/test_hello.py @@ -2,17 +2,19 @@ import os import unittest from pyof.v0x01.symmetric import hello - +from pyof.v0x01.common import header as of_header class TestHello(unittest.TestCase): def setUp(self): self.message = hello.Hello(xid=1) + self.header = of_header.Header() def test_get_size(self): """[Symmetric/Hello] - size 8""" self.assertEqual(self.message.get_size(), 8) + @unittest.skip('Need to implement length update') def test_pack(self): """[Symmetric/Hello] - packing""" filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), @@ -22,8 +24,10 @@ class TestHello(unittest.TestCase): packed_hello = b'\x01\x00\x00\x08\x00\x00\x00\x01' self.assertEqual(self.message.pack(), packed_hello) - @unittest.skip('Not yet implemented') def test_unpack(self): """[Symmetric/Hello] - unpacking""" - # TODO - pass + filename = os.path.join(os.path.dirname(os.path.realpath('__file__')), + 'raw/v0x01/ofpt_hello.dat') + with open(filename, 'rb') as f: + self.header.unpack(f.read(8)) + self.assertEqual(self.message.unpack(f.read()), None)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 6 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "coverage" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/kytos/python-openflow.git@9b9c0c3e86c73aaebdcb57bda00feeefbdbcfe09#egg=Kytos_OpenFlow_Parser_library packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: python-openflow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 prefix: /opt/conda/envs/python-openflow
[ "tests/v0x01/test_common/test_header.py::TestHeader::test_pack", "tests/v0x01/test_common/test_header.py::TestHeader::test_size", "tests/v0x01/test_common/test_header.py::TestHeader::test_unpack", "tests/v0x01/test_controller2switch/test_barrier_reply.py::TestBarrierReply::test_get_size", "tests/v0x01/test_controller2switch/test_barrier_reply.py::TestBarrierReply::test_unpack", "tests/v0x01/test_controller2switch/test_barrier_request.py::TestBarrierRequest::test_get_size", "tests/v0x01/test_controller2switch/test_barrier_request.py::TestBarrierRequest::test_unpack", "tests/v0x01/test_controller2switch/test_features_reply.py::TestSwitchFeatures::test_get_size", "tests/v0x01/test_controller2switch/test_features_request.py::TestFeaturesRequest::test_get_size", "tests/v0x01/test_controller2switch/test_features_request.py::TestFeaturesRequest::test_unpack", "tests/v0x01/test_controller2switch/test_flow_mod.py::TestFlowMod::test_get_size", "tests/v0x01/test_controller2switch/test_flow_mod.py::TestFlowMod::test_unpack_add", "tests/v0x01/test_controller2switch/test_flow_mod.py::TestFlowMod::test_unpack_delete", "tests/v0x01/test_symmetric/test_echo_reply.py::TestEchoReply::test_get_size", "tests/v0x01/test_symmetric/test_echo_reply.py::TestEchoReply::test_unpack", "tests/v0x01/test_symmetric/test_echo_request.py::TestEchoRequest::test_get_size", "tests/v0x01/test_symmetric/test_echo_request.py::TestEchoRequest::test_unpack", "tests/v0x01/test_symmetric/test_hello.py::TestHello::test_get_size", "tests/v0x01/test_symmetric/test_hello.py::TestHello::test_unpack" ]
[ "tests/v0x01/test_controller2switch/test_features_reply.py::TestSwitchFeatures::test_unpack" ]
[]
[]
MIT License
573
FundersClub__bai-lockbox-2
c7e4fbc207b21953e4741ba55f787eaa108e55fb
2016-06-06 23:19:28
c7e4fbc207b21953e4741ba55f787eaa108e55fb
diff --git a/.gitignore b/.gitignore index 9bec050..87bf718 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ __pycache__/ *.py[cod] *$py.class +*.egg *.egg-info/ .eggs/ .tox/ diff --git a/LICENSE.txt b/LICENSE.txt index 65c5ca8..11b3d94 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,165 +1,201 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016 FundersClub Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/lockbox/exceptions.py b/lockbox/exceptions.py index c414d89..5d5c9db 100644 --- a/lockbox/exceptions.py +++ b/lockbox/exceptions.py @@ -1,19 +1,3 @@ -# This file is part of bai-lockbox. - -# bai-lockbox is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. - -# bai-lockbox is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. - -# You should have received a copy of the GNU Lesser General Public -# License along with bai-lockbox. If not, see -# <http://www.gnu.org/licenses/>. - class LockboxError(Exception): pass @@ -29,7 +13,7 @@ class LockboxParseError(LockboxError): '''Base exception for problems related to reading a BAI Lockbox record. ''' - raw_line = '' + pass class LockboxConsistencyError(LockboxError): diff --git a/lockbox/parser.py b/lockbox/parser.py index 9eb6120..43407fd 100644 --- a/lockbox/parser.py +++ b/lockbox/parser.py @@ -1,19 +1,3 @@ -# This file is part of bai-lockbox. - -# bai-lockbox is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. - -# bai-lockbox is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. - -# You should have received a copy of the GNU Lesser General Public -# License along with bai-lockbox. If not, see -# <http://www.gnu.org/licenses/>. - import six import sys @@ -42,6 +26,8 @@ class Check(object): self.number = detail.check_number self.amount = detail.check_amount self.memo = detail.memo + self.sender_routing_number=detail.transit_routing_number + self.sender_account_number=detail.dd_account_number class LockboxDetail(object): @@ -66,8 +52,8 @@ class LockboxDetail(object): def __getattr__(self, attr): if attr in dir(self.record): return getattr(self.record, attr) - - return self.get(attr) + else: + return super(LockboxDetail, self).__getattr__(attr) class LockboxBatch(object): @@ -78,13 +64,8 @@ class LockboxBatch(object): @property def checks(self): - checks = [] - - for detail in self.details: - checks.append(Check(detail)) + return [Check(d) for d in self.details] - return checks - def validate(self): if self.summary is None: raise LockboxParseError( @@ -201,7 +182,7 @@ class LockboxFile(object): self.destination_trailer_record = None self.cur_lockbox = None - + @property def checks(self): checks = [] @@ -210,7 +191,7 @@ class LockboxFile(object): checks.extend(lockbox.checks) return checks - + def validate(self): for lockbox in self.lockboxes: lockbox.validate() @@ -262,51 +243,49 @@ class LockboxFile(object): else: self.cur_lockbox.add_record(record) - -def read_lockbox_lines(lines): - lockbox_file = LockboxFile() - - for line, line_num in zip(lines, range(1, len(lines)+1)): - try: - if line[0] == str(LockboxBatchTotalRecord.RECORD_TYPE_NUM): - rec = LockboxBatchTotalRecord(line) - elif line[0] == str(LockboxDestinationTrailerRecord.RECORD_TYPE_NUM): - rec = LockboxDestinationTrailerRecord(line) - elif line[0] == str(LockboxDetailHeader.RECORD_TYPE_NUM): - rec = LockboxDetailHeader(line) - elif line[0] == str(LockboxDetailOverflowRecord.RECORD_TYPE_NUM): - rec = LockboxDetailOverflowRecord(line) - elif line[0] == str(LockboxDetailRecord.RECORD_TYPE_NUM): - rec = LockboxDetailRecord(line) - elif line[0] == str(LockboxImmediateAddressHeader.RECORD_TYPE_NUM): - rec = LockboxImmediateAddressHeader(line) - elif line[0] == str(LockboxServiceRecord.RECORD_TYPE_NUM): - rec = LockboxServiceRecord(line) - elif line[0] == str(LockboxServiceTotalRecord.RECORD_TYPE_NUM): - rec = LockboxServiceTotalRecord(line) - else: - raise LockboxParseError( - 'unknown record type {}'.format(line[0]) + @classmethod + def from_lines(cls, lines): + lines = [l.strip() for l in lines] + lockbox_file = cls() + + for line_num, line in enumerate(lines, start=1): + try: + rec_type = int(line[0]) + record_type_to_constructor = { + LockboxBatchTotalRecord.RECORD_TYPE_NUM: LockboxBatchTotalRecord, + LockboxDestinationTrailerRecord.RECORD_TYPE_NUM: LockboxDestinationTrailerRecord, + LockboxDetailHeader.RECORD_TYPE_NUM: LockboxDetailHeader, + LockboxDetailOverflowRecord.RECORD_TYPE_NUM: LockboxDetailOverflowRecord, + LockboxDetailRecord.RECORD_TYPE_NUM: LockboxDetailRecord, + LockboxImmediateAddressHeader.RECORD_TYPE_NUM: LockboxImmediateAddressHeader, + LockboxServiceRecord.RECORD_TYPE_NUM: LockboxServiceRecord, + LockboxServiceTotalRecord.RECORD_TYPE_NUM: LockboxServiceTotalRecord, + } + + if rec_type not in record_type_to_constructor: + raise LockboxParseError( + 'unknown record type {}'.format(rec_type) + ) + + rec = record_type_to_constructor[rec_type](line) + lockbox_file.add_record(rec) + except Exception as e: + if not isinstance(e, LockboxError): + raise + + # if this is some lockbox-related exception,create a new + # exception of the same kind we caught, bet prepend the + # current line number to it so we know where to look while + # troubleshooting + six.reraise( + type(e), + 'Line {}: {} ("{}")'.format(line_num, str(e), line), + sys.exc_info()[2] ) - lockbox_file.add_record(rec) - except Exception as e: - if not isinstance(e, LockboxError): - raise - - # if this is some lockbox-related exception,create a new - # exception of the same kind we caught, bet prepend the - # current line number to it so we know where to look while - # troubleshooting - six.reraise( - type(e), - 'Line {}: {} ("{}")'.format(line_num, str(e), line), - sys.exc_info()[2] - ) - - lockbox_file.validate() - return lockbox_file - + lockbox_file.validate() + return lockbox_file -def read_lockbox_file(inf): - return read_lockbox_lines([line.strip() for line in inf.readlines()]) + @classmethod + def from_file(cls, inf): + return LockboxFile.from_lines(inf.readlines()) diff --git a/lockbox/records.py b/lockbox/records.py index 71fd5c9..d491c87 100644 --- a/lockbox/records.py +++ b/lockbox/records.py @@ -1,25 +1,16 @@ -# This file is part of bai-lockbox. - -# bai-lockbox is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. - -# bai-lockbox is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. - -# You should have received a copy of the GNU Lesser General Public -# License along with bai-lockbox. If not, see -# <http://www.gnu.org/licenses/>. - import datetime import re +import six from .exceptions import LockboxDefinitionError, LockboxParseError +class LockboxFieldType(object): + Numeric = 'numeric' + Alphanumeric = 'alphanumeric' + Blank = 'blank' + + class LockboxBaseRecord(object): '''The format of the field 'fields' should be an array of dicts like this: @@ -30,11 +21,12 @@ class LockboxBaseRecord(object): ... } - Valid types: 'alphanumeric', 'numeric', 'blank' + Valid types are listed inside the LockboxFieldType class. Note: The record type which is determined by first character of a line is defined by setting MAX_RECORD_LENGTH in a derrived class rather than by adding it to the 'fields' field. + ''' MAX_RECORD_LENGTH = 104 @@ -56,7 +48,7 @@ class LockboxBaseRecord(object): # we can only parse if there are actually fields defined self.fields['record_type'] = { 'location': (0,1), - 'type': 'numeric', + 'type': LockboxFieldType.Numeric, } self._parse() @@ -67,7 +59,7 @@ class LockboxBaseRecord(object): # has already been performed by the regexps in _parse(), # so at this point we just create any missing fields by # doing self.my_field = self._my_field_raw - for field_name, field_def in self.fields.items(): + for field_name, field_def in six.iteritems(self.fields): if hasattr(self, field_name): continue @@ -75,14 +67,14 @@ class LockboxBaseRecord(object): raw_field_val = ( None - if field_def['type'] == 'blank' + if field_def['type'] == LockboxFieldType.Blank else getattr(self, raw_field_name, None) ) setattr(self, field_name, raw_field_val) def _parse(self): - for field_name, field_def in self.fields.items(): + for field_name, field_def in six.iteritems(self.fields): raw_field_name = '_{}_raw'.format(field_name) if hasattr(self, field_name): raise AttributeError( @@ -91,15 +83,14 @@ class LockboxBaseRecord(object): ) ) - start_col = field_def['location'][0] - end_col = field_def['location'][1] + start_col, end_col = field_def['location'] raw_field = self.raw_record_text[start_col:end_col] - if field_def['type'] == 'alphanumeric': + if field_def['type'] == LockboxFieldType.Alphanumeric: patt = re.compile(r'^[ A-Z0-9]+$') - elif field_def['type'] == 'numeric': + elif field_def['type'] == LockboxFieldType.Numeric: patt = re.compile(r'^[0-9]+$') - elif field_def['type'] == 'blank': + elif field_def['type'] == LockboxFieldType.Blank: patt = re.compile(r'^\s*$') else: raise LockboxDefinitionError( @@ -186,12 +177,12 @@ class LockboxImmediateAddressHeader(LockboxBaseRecord): RECORD_TYPE_NUM = 1 fields = { - 'priority_code': { 'location': (1, 3), 'type': 'numeric' }, - 'destination_id': { 'location': (3, 13), 'type': 'alphanumeric' }, - 'originating_trn': { 'location': (13, 23), 'type': 'numeric' }, - 'processing_date': { 'location': (23, 29), 'type': 'numeric' }, - 'processing_time': { 'location': (29, 33), 'type': 'numeric' }, - 'filler': {'location': (33, 104), 'type': 'blank' }, + 'priority_code': { 'location': (1, 3), 'type': LockboxFieldType.Numeric }, + 'destination_id': { 'location': (3, 13), 'type': LockboxFieldType.Alphanumeric }, + 'originating_trn': { 'location': (13, 23), 'type': LockboxFieldType.Numeric }, + 'processing_date': { 'location': (23, 29), 'type': LockboxFieldType.Numeric }, + 'processing_time': { 'location': (29, 33), 'type': LockboxFieldType.Numeric }, + 'filler': {'location': (33, 104), 'type': LockboxFieldType.Blank }, } def validate(self): @@ -205,14 +196,14 @@ class LockboxServiceRecord(LockboxBaseRecord): fields = { 'ultimate_dest_and_origin': { 'location': (1, 21), - 'type': 'alphanumeric', + 'type': LockboxFieldType.Alphanumeric, }, - 'ref_code': {'location': (21, 31), 'type': 'numeric'}, - 'service_type': {'location': (31, 34), 'type': 'numeric'}, - 'record_size': {'location': (34, 37), 'type': 'numeric'}, - 'blocking_factor': {'location': (37, 41), 'type': 'numeric'}, - 'format_code': {'location': (41,42), 'type': 'numeric'}, - 'filler': {'location': (42, 104), 'type': 'blank'}, + 'ref_code': {'location': (21, 31), 'type': LockboxFieldType.Numeric}, + 'service_type': {'location': (31, 34), 'type': LockboxFieldType.Numeric}, + 'record_size': {'location': (34, 37), 'type': LockboxFieldType.Numeric}, + 'blocking_factor': {'location': (37, 41), 'type': LockboxFieldType.Numeric}, + 'format_code': {'location': (41,42), 'type': LockboxFieldType.Numeric}, + 'filler': {'location': (42, 104), 'type': LockboxFieldType.Blank}, } @@ -220,15 +211,15 @@ class LockboxDetailHeader(LockboxBaseRecord): RECORD_TYPE_NUM = 5 fields = { - 'batch_number': { 'location': (1, 4), 'type': 'numeric' }, - 'ref_code': { 'location': (4, 7, ), 'type': 'numeric' }, - 'lockbox_number': { 'location': (7, 14), 'type': 'numeric' }, - 'deposit_date': { 'location': (14, 20), 'type': 'numeric' }, + 'batch_number': { 'location': (1, 4), 'type': LockboxFieldType.Numeric }, + 'ref_code': { 'location': (4, 7, ), 'type': LockboxFieldType.Numeric }, + 'lockbox_number': { 'location': (7, 14), 'type': LockboxFieldType.Numeric }, + 'deposit_date': { 'location': (14, 20), 'type': LockboxFieldType.Numeric }, 'ultimate_dest_and_origin': { 'location': (20, 40), - 'type': 'alphanumeric', + 'type': LockboxFieldType.Alphanumeric, }, - 'filler': {'location': (40, 104), 'type': 'blank' }, + 'filler': {'location': (40, 104), 'type': LockboxFieldType.Blank }, } def validate(self): @@ -239,16 +230,16 @@ class LockboxDetailRecord(LockboxBaseRecord): RECORD_TYPE_NUM = 6 fields = { - 'batch_number': { 'location': (1, 4), 'type': 'numeric' }, - 'item_number': { 'location': (4, 7), 'type': 'numeric' }, - 'check_amount': { 'location': (7, 17), 'type': 'numeric' }, - 'transit_routing_number': { 'location': (17, 26), 'type': 'numeric' }, - 'dd_account_number': { 'location': (26, 36), 'type': 'numeric' }, - 'check_number': { 'location': (36, 46), 'type': 'numeric' }, - 'check_date': { 'location': (46, 52), 'type': 'numeric' }, - 'remitter_name': { 'location': (52, 82), 'type': 'alphanumeric' }, - 'payee_name': { 'location': (82, 102), 'type': 'alphanumeric' }, - 'filler': {'location': (102, 104), 'type': 'blank' }, + 'batch_number': { 'location': (1, 4), 'type': LockboxFieldType.Numeric }, + 'item_number': { 'location': (4, 7), 'type': LockboxFieldType.Numeric }, + 'check_amount': { 'location': (7, 17), 'type': LockboxFieldType.Numeric }, + 'transit_routing_number': { 'location': (17, 26), 'type': LockboxFieldType.Numeric }, + 'dd_account_number': { 'location': (26, 36), 'type': LockboxFieldType.Numeric }, + 'check_number': { 'location': (36, 46), 'type': LockboxFieldType.Numeric }, + 'check_date': { 'location': (46, 52), 'type': LockboxFieldType.Numeric }, + 'remitter_name': { 'location': (52, 82), 'type': LockboxFieldType.Alphanumeric }, + 'payee_name': { 'location': (82, 102), 'type': LockboxFieldType.Alphanumeric }, + 'filler': {'location': (102, 104), 'type': LockboxFieldType.Blank }, } def validate(self): @@ -269,13 +260,13 @@ class LockboxDetailOverflowRecord(LockboxBaseRecord): RECORD_TYPE_NUM = 4 fields = { - 'batch_number': { 'location': (1, 4), 'type': 'numeric' }, - 'item_number': { 'location': (4, 7), 'type': 'numeric' }, - 'overflow_record_type': { 'location': (7, 8), 'type': 'numeric' }, - 'overflow_sequence_number': { 'location': (8, 10), 'type': 'numeric' }, - 'overflow_indicator': { 'location': (10, 11), 'type': 'numeric' }, - 'memo_line': { 'location': (11, 41), 'type': 'alphanumeric' }, - 'filler': {'location': (41, 104), 'type': 'blank' }, + 'batch_number': { 'location': (1, 4), 'type': LockboxFieldType.Numeric }, + 'item_number': { 'location': (4, 7), 'type': LockboxFieldType.Numeric }, + 'overflow_record_type': { 'location': (7, 8), 'type': LockboxFieldType.Numeric }, + 'overflow_sequence_number': { 'location': (8, 10), 'type': LockboxFieldType.Numeric }, + 'overflow_indicator': { 'location': (10, 11), 'type': LockboxFieldType.Numeric }, + 'memo_line': { 'location': (11, 41), 'type': LockboxFieldType.Alphanumeric }, + 'filler': {'location': (41, 104), 'type': LockboxFieldType.Blank }, } def validate(self): @@ -289,16 +280,16 @@ class LockboxBatchTotalRecord(LockboxBaseRecord): RECORD_TYPE_NUM = 7 fields = { - 'batch_number': { 'location': (1, 4), 'type': 'numeric' }, - 'item_number': { 'location': (4, 7), 'type': 'numeric' }, - 'lockbox_number': { 'location': (7, 14), 'type': 'numeric' }, - 'deposit_date': { 'location': (14, 20), 'type': 'numeric' }, + 'batch_number': { 'location': (1, 4), 'type': LockboxFieldType.Numeric }, + 'item_number': { 'location': (4, 7), 'type': LockboxFieldType.Numeric }, + 'lockbox_number': { 'location': (7, 14), 'type': LockboxFieldType.Numeric }, + 'deposit_date': { 'location': (14, 20), 'type': LockboxFieldType.Numeric }, 'total_number_remittances': { 'location': (20, 23), - 'type': 'numeric' + 'type': LockboxFieldType.Numeric }, - 'check_dollar_total': { 'location': (23, 33), 'type': 'numeric' }, - 'filler': {'location': (33, 104), 'type': 'blank' }, + 'check_dollar_total': { 'location': (23, 33), 'type': LockboxFieldType.Numeric }, + 'filler': {'location': (33, 104), 'type': LockboxFieldType.Blank }, } def validate(self): @@ -313,13 +304,13 @@ class LockboxServiceTotalRecord(LockboxBaseRecord): RECORD_TYPE_NUM = 8 fields = { - 'batch_number': { 'location': (1, 4), 'type': 'numeric' }, - 'item_number': { 'location': (4, 7), 'type': 'numeric' }, - 'lockbox_number': { 'location': (7, 14), 'type': 'numeric' }, - 'deposit_date': { 'location': (14, 20), 'type': 'numeric' }, - 'total_num_checks': { 'location': (20, 24), 'type': 'numeric' }, - 'check_dollar_total': { 'location': (24, 34), 'type': 'numeric' }, - 'filler': {'location': (34, 104), 'type': 'blank' }, + 'batch_number': { 'location': (1, 4), 'type': LockboxFieldType.Numeric }, + 'item_number': { 'location': (4, 7), 'type': LockboxFieldType.Numeric }, + 'lockbox_number': { 'location': (7, 14), 'type': LockboxFieldType.Numeric }, + 'deposit_date': { 'location': (14, 20), 'type': LockboxFieldType.Numeric }, + 'total_num_checks': { 'location': (20, 24), 'type': LockboxFieldType.Numeric }, + 'check_dollar_total': { 'location': (24, 34), 'type': LockboxFieldType.Numeric }, + 'filler': {'location': (34, 104), 'type': LockboxFieldType.Blank }, } def validate(self): @@ -333,8 +324,8 @@ class LockboxDestinationTrailerRecord(LockboxBaseRecord): RECORD_TYPE_NUM = 9 fields = { - 'total_num_records': { 'location': (1, 7), 'type': 'numeric' }, - 'filler': {'location': (7, 104), 'type': 'blank' }, + 'total_num_records': { 'location': (1, 7), 'type': LockboxFieldType.Numeric }, + 'filler': {'location': (7, 104), 'type': LockboxFieldType.Blank }, } def validate(self): diff --git a/setup.py b/setup.py index aebdbc4..4cbeca1 100644 --- a/setup.py +++ b/setup.py @@ -9,15 +9,13 @@ setup( version='0.0.1', packages=find_packages(exclude=['docs', 'tests']), install_requires=[ - 'django-jsonfield>=0.8.11', 'six', - 'django-apptemplates', ], test_suite='nose.collector', tests_require=['nose', 'coverage'], include_package_data=True, - license='LGPLv3', - description='An elegant solution for keeping a relational log of chronological events in a Django application.', + license='Apache License 2.0', + description='A library for parsing files in the BAI lockbox format.', url='https://www.github.com/FundersClub/bai-lockbox', author='Jon Friedman / FundersClub Inc.', author_email='[email protected]', @@ -27,8 +25,8 @@ setup( 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', - 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', + 'License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', - 'Intended Audience :: Financial and Insurance Industry' + 'Intended Audience :: Financial and Insurance Industry' ], ) diff --git a/tox.ini b/tox.ini index 4c556c8..892779a 100644 --- a/tox.ini +++ b/tox.ini @@ -2,8 +2,7 @@ envlist = py27 py34 - pypy [testenv] deps = -rrequirements.txt -commands = python setup.py nosetests \ No newline at end of file +commands = python setup.py nosetests
Code review * [x] https://github.com/FundersClub/bai-lockbox/blob/master/setup.py#L12 - are all of these used? * [x] https://github.com/FundersClub/bai-lockbox/blob/master/setup.py#L20 - incorrect * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/exceptions.py#L32 - what is this? * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/parser.py#L70 - Where is `.get()` defined? * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/parser.py#L81 - Why not something like `return map(Check, self.details)` (or good ol' list comprehension) * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/parser.py#L269 - Look up `enumerate()` * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/parser.py#L266 and https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/parser.py#L311 - I would make these `@classmethod`s in `LockboxFile` and call them something like `from_lines` and `from_file` * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/parser.py#L312 - I would make the `read_lockbox_lines` perform the `strip()` as it is always desired * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/parser.py#L271 - Instead of all those `str()` and repeating `line[0]` why not: 1) convert `int(line[0])` and store it in a local variable and then compare. 2) Create a dictionary that maps the record number to the class. (see *1 below) * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/records.py#L70 - Please use `iteritems`, no need to create an in-memory list * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/records.py#L85 - `iteritems()` * [x] https://github.com/FundersClub/bai-lockbox/blob/master/lockbox/records.py#L94 - `start_col, end_col = field_def['location']` * [x] I think we should make field types a constant and then use that. Reduces chances for unnoticed typos. (see *2 below) ---- *1 ``` class FieldType(object): Numeric = 'numeric' ... ``` ---- *2 ``` record_types = { LockboxBatchTotalRecord.RECORD_TYPE_NUM: LockboxBatchTotalRecord, .... } record_cls = record_types.get(int(line[0])) if not record_cls: ... rec = record_cls(line)
FundersClub/bai-lockbox
diff --git a/lockbox/tests/test_parser.py b/lockbox/tests/test_parser.py index 262f87d..1a2649a 100644 --- a/lockbox/tests/test_parser.py +++ b/lockbox/tests/test_parser.py @@ -1,25 +1,9 @@ -# This file is part of bai-lockbox. - -# bai-lockbox is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. - -# bai-lockbox is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. - -# You should have received a copy of the GNU Lesser General Public -# License along with bai-lockbox. If not, see -# <http://www.gnu.org/licenses/>. - import datetime import os from unittest import TestCase -from lockbox.parser import read_lockbox_file, read_lockbox_lines +from lockbox.parser import LockboxFile class TestLockboxParser(TestCase): @@ -42,7 +26,7 @@ class TestLockboxParser(TestCase): self.empty_lockbox_lines = [l.strip() for l in open(empty_lockbox_path, 'r').readlines()] def test_parsing_valid_file(self): - lockbox_file = read_lockbox_lines(self.valid_lockbox_lines) + lockbox_file = LockboxFile.from_lines(self.valid_lockbox_lines) self.assertEqual(len(lockbox_file.checks), 1) @@ -55,6 +39,6 @@ class TestLockboxParser(TestCase): self.assertEqual(check.memo, 'CE554') def test_parsing_file_with_no_checks(self): - lockbox_file = read_lockbox_lines(self.empty_lockbox_lines) + lockbox_file = LockboxFile.from_lines(self.empty_lockbox_lines) self.assertEqual(len(lockbox_file.checks), 0) diff --git a/lockbox/tests/test_records.py b/lockbox/tests/test_records.py index de5f1b3..19a52c5 100644 --- a/lockbox/tests/test_records.py +++ b/lockbox/tests/test_records.py @@ -1,19 +1,3 @@ -# This file is part of bai-lockbox. - -# bai-lockbox is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. - -# bai-lockbox is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. - -# You should have received a copy of the GNU Lesser General Public -# License along with bai-lockbox. If not, see -# <http://www.gnu.org/licenses/>. - import datetime from unittest import TestCase
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 7 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asgiref==3.8.1 -e git+https://github.com/FundersClub/bai-lockbox.git@c7e4fbc207b21953e4741ba55f787eaa108e55fb#egg=bai_lockbox Django==4.2.20 django-apptemplates==1.5 django-jsonfield==1.4.1 exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 six==1.17.0 sqlparse==0.5.3 tomli==2.2.1 typing_extensions==4.13.0
name: bai-lockbox channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asgiref==3.8.1 - django==4.2.20 - django-apptemplates==1.5 - django-jsonfield==1.4.1 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - sqlparse==0.5.3 - tomli==2.2.1 - typing-extensions==4.13.0 prefix: /opt/conda/envs/bai-lockbox
[ "lockbox/tests/test_parser.py::TestLockboxParser::test_parsing_file_with_no_checks", "lockbox/tests/test_parser.py::TestLockboxParser::test_parsing_valid_file" ]
[]
[ "lockbox/tests/test_records.py::TestRecordDefinitions::test_immediate_address_header", "lockbox/tests/test_records.py::TestRecordDefinitions::test_invalid_alphanumeric_field", "lockbox/tests/test_records.py::TestRecordDefinitions::test_invalid_numeric_field", "lockbox/tests/test_records.py::TestRecordDefinitions::test_lockbox_batch_total_record", "lockbox/tests/test_records.py::TestRecordDefinitions::test_lockbox_destination_trailer_record", "lockbox/tests/test_records.py::TestRecordDefinitions::test_lockbox_detail_header", "lockbox/tests/test_records.py::TestRecordDefinitions::test_lockbox_detail_overflow_record", "lockbox/tests/test_records.py::TestRecordDefinitions::test_lockbox_detail_record", "lockbox/tests/test_records.py::TestRecordDefinitions::test_lockbox_service_total_record", "lockbox/tests/test_records.py::TestRecordDefinitions::test_overlong_record", "lockbox/tests/test_records.py::TestRecordDefinitions::test_valid_lockbox_service_record" ]
[]
Apache License 2.0
574
peterbe__premailer-167
cc18022e334d5336e48f75bd4e0a73c98cc5942a
2016-06-07 12:37:52
cc18022e334d5336e48f75bd4e0a73c98cc5942a
graingert: I think it's such a trivial and unlikely to be used piece of code, that I'd rather just remove it and recommend people add their own: ```python # now we can delete all 'class' attributes for item in page.xpath('//@class'): parent = item.getparent() del parent.attrib['class'] ``` peterbe: @graingert But I want the library to be as easy as possible. Also, as lazy as possible :) graingert: It's your call, but imagine if this feature was not implemented, would it be worth adding? I don't see a use-case for it. coveralls: [![Coverage Status](https://coveralls.io/builds/6493685/badge)](https://coveralls.io/builds/6493685) Coverage decreased (-0.7%) to 99.299% when pulling **4e1762899aca476de755ada50c95ec02072e24db on keep-classes-by-default-fixes-33** into **cc18022e334d5336e48f75bd4e0a73c98cc5942a on master**. peterbe: One usecase is that it's not hard to keep and it's nice to have it there for people who needed it. Actually, if you don't have media queries. If you have some really simple CSS for your HTML emails, then having the `class` attributes still in means the email gets unnecessarily larger. I suggest we just keep the functionality around. On Tue, Jun 7, 2016 at 8:45 AM, Thomas Grainger <[email protected]> wrote: > It's your call, but imagine if this feature was not implemented, would it > be worth adding? > > I don't see a use-case for it. > > — > You are receiving this because you authored the thread. > Reply to this email directly, view it on GitHub > <https://github.com/peterbe/premailer/pull/167#issuecomment-224269061>, > or mute the thread > <https://github.com/notifications/unsubscribe/AABoc_2Fg2_REhvGVNqOZLI7Z5RBUWkLks5qJWfjgaJpZM4Iv3_H> > . > -- Peter Bengtsson Mozilla Tools & Services coveralls: [![Coverage Status](https://coveralls.io/builds/6493757/badge)](https://coveralls.io/builds/6493757) Coverage remained the same at 100.0% when pulling **6e9df1c5587d133851f2185c63cf79998ad679ec on keep-classes-by-default-fixes-33** into **cc18022e334d5336e48f75bd4e0a73c98cc5942a on master**.
diff --git a/premailer/__init__.py b/premailer/__init__.py index e831baa..570b55c 100644 --- a/premailer/__init__.py +++ b/premailer/__init__.py @@ -1,4 +1,4 @@ from __future__ import absolute_import, unicode_literals from .premailer import Premailer, transform -__version__ = '2.11.0' +__version__ = '3.0.0' diff --git a/premailer/premailer.py b/premailer/premailer.py index de9839d..fc157ee 100644 --- a/premailer/premailer.py +++ b/premailer/premailer.py @@ -121,7 +121,7 @@ class Premailer(object): exclude_pseudoclasses=True, keep_style_tags=False, include_star_selectors=False, - remove_classes=True, + remove_classes=False, capitalize_float_margin=False, strip_important=True, external_styles=None,
keep class attributes the transform() function replaces the "class" attribute with the appropriate styling, but it also removes the class from the html elements. I need the styling added inline, but the classes to be left within their elements so that my @media (!important) styling can be inserted in after and still have classes to point to within the dom. Im having a hard time changing your code to meet this needs, do you have any thoughts on how I could keep the classes within the html elements but still inject the inline styling?
peterbe/premailer
diff --git a/premailer/tests/test_premailer.py b/premailer/tests/test_premailer.py index 42213d8..5cdf6a7 100644 --- a/premailer/tests/test_premailer.py +++ b/premailer/tests/test_premailer.py @@ -170,6 +170,37 @@ class Tests(unittest.TestCase): compare_html(expect_html, result_html) + def test_remove_classes(self): + """test the simplest case""" + + html = """<html> + <head> + <title>Title</title> + <style type="text/css"> + .stuff { + color: red; + } + </style> + </head> + <body> + <p class="stuff"><strong>Yes!</strong></p> + </body> + </html>""" + + expect_html = """<html> + <head> + <title>Title</title> + </head> + <body> + <p style="color:red"><strong>Yes!</strong></p> + </body> + </html>""" + + p = Premailer(html, remove_classes=True) + result_html = p.transform() + + compare_html(expect_html, result_html) + def test_basic_html_shortcut_function(self): """test the plain transform function""" html = """<html> @@ -1088,7 +1119,7 @@ b <head> </head> <body> - <div style="color:red"></div> + <div class="example" style="color:red"></div> </body> </html>""" @@ -1118,7 +1149,7 @@ b <head> </head> <body> - <div style="color:green"></div> + <div class="example" style="color:green"></div> </body> </html>""" @@ -1148,7 +1179,7 @@ b <head> </head> <body> - <div style="color:green"></div> + <div class="example" style="color:green"></div> </body> </html>""" @@ -1178,7 +1209,7 @@ b <head> </head> <body> - <div id="identified" style="color:green"></div> + <div class="example" id="identified" style="color:green"></div> </body> </html>""" @@ -1195,7 +1226,7 @@ b color: blue !important; font-size: 12px; } - #identified { + #id { color: green; font-size: 22px; } @@ -1205,17 +1236,17 @@ b </style> </head> <body> - <div class="example makeblue" id="identified"></div> + <div class="example makeblue" id="id"></div> </body> </html>""" expect_html = """<html> - <head> - </head> - <body> - <div id="identified" style="font-size:22px; color:blue"></div> - </body> - </html>""" +<head> +</head> +<body> +<div class="example makeblue" id="id" style="font-size:22px; color:blue"></div> +</body> +</html>""" p = Premailer(html) result_html = p.transform() @@ -1285,7 +1316,7 @@ ration:none">Yes!</strong></p> <title>Title</title> </head> <body> - <h1 style="color:green">Hi!</h1> + <h1 class="foo" style="color:green">Hi!</h1> </body> </html>""" @@ -2395,7 +2426,7 @@ sheet" type="text/css"> <head> </head> <body> - <div style="color:green; font-size:10px"></div> + <div class="color example" style="color:green; font-size:10px"></div> </body> </html>""" @@ -2453,22 +2484,22 @@ sheet" type="text/css"> </head> <body> <p><img src="/images/left.jpg" style="float: left"> text - <img src="/images/right.png" class="floatright"> text + <img src="/r.png" class="floatright"> text <img src="/images/nofloat.gif"> text </body> </html>""" expect_html = """<html> - <head> - <title>Title</title> - </head> - <body> - <p><img src="/images/left.jpg" style="float: left" align="left"> text - <img src="/images/right.png" style="float:right" align="right"> text - <img src="/images/nofloat.gif"> text - </p> - </body> - </html>""" +<head> +<title>Title</title> +</head> +<body> +<p><img src="/images/left.jpg" style="float: left" align="left"> text + <img src="/r.png" class="floatright" style="float:right" align="right"> text + <img src="/images/nofloat.gif"> text +</p> +</body> +</html>""" p = Premailer(html, align_floating_images=True) result_html = p.transform() @@ -2498,7 +2529,8 @@ sheet" type="text/css"> <head> </head> <body> - <div style="color:green"><span></span></div> + <div class="color" style="color:green"><span class="nocolor"></span> + </div> </body> </html>"""
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "mock", "coverage", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 cssselect==1.1.0 cssutils==2.3.1 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 lxml==5.3.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pluggy==1.0.0 -e git+https://github.com/peterbe/premailer.git@cc18022e334d5336e48f75bd4e0a73c98cc5942a#egg=premailer py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: premailer channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - cssselect==1.1.0 - cssutils==2.3.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - lxml==5.3.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/premailer
[ "premailer/tests/test_premailer.py::Tests::test_align_float_images", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_class_over_generic", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_element_over_generic", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_id_over_others", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_important_over_others", "premailer/tests/test_premailer.py::Tests::test_prefer_inline_to_class", "premailer/tests/test_premailer.py::Tests::test_remove_unset_properties", "premailer/tests/test_premailer.py::Tests::test_style_attribute_specificity", "premailer/tests/test_premailer.py::Tests::test_turnoff_cache_works_as_expected" ]
[]
[ "premailer/tests/test_premailer.py::Tests::test_3_digit_color_expand", "premailer/tests/test_premailer.py::Tests::test_apple_newsletter_example", "premailer/tests/test_premailer.py::Tests::test_base_url_fixer", "premailer/tests/test_premailer.py::Tests::test_base_url_with_path", "premailer/tests/test_premailer.py::Tests::test_basic_html", "premailer/tests/test_premailer.py::Tests::test_basic_html_shortcut_function", "premailer/tests/test_premailer.py::Tests::test_basic_html_with_pseudo_selector", "premailer/tests/test_premailer.py::Tests::test_basic_xml", "premailer/tests/test_premailer.py::Tests::test_broken_xml", "premailer/tests/test_premailer.py::Tests::test_capture_cssutils_logging", "premailer/tests/test_premailer.py::Tests::test_child_selector", "premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_argument", "premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_stdin", "premailer/tests/test_premailer.py::Tests::test_command_line_preserve_style_tags", "premailer/tests/test_premailer.py::Tests::test_comments_in_media_queries", "premailer/tests/test_premailer.py::Tests::test_css_disable_basic_html_attributes", "premailer/tests/test_premailer.py::Tests::test_css_disable_leftover_css", "premailer/tests/test_premailer.py::Tests::test_css_text", "premailer/tests/test_premailer.py::Tests::test_css_text_with_only_body_present", "premailer/tests/test_premailer.py::Tests::test_css_with_html_attributes", "premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_excluded", "premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_included", "premailer/tests/test_premailer.py::Tests::test_disabled_validator", "premailer/tests/test_premailer.py::Tests::test_doctype", "premailer/tests/test_premailer.py::Tests::test_empty_style_tag", "premailer/tests/test_premailer.py::Tests::test_external_links", "premailer/tests/test_premailer.py::Tests::test_external_links_unfindable", "premailer/tests/test_premailer.py::Tests::test_external_styles_and_links", "premailer/tests/test_premailer.py::Tests::test_external_styles_on_http", "premailer/tests/test_premailer.py::Tests::test_external_styles_on_https", "premailer/tests/test_premailer.py::Tests::test_external_styles_with_base_url", "premailer/tests/test_premailer.py::Tests::test_fontface_selectors_with_no_selectortext", "premailer/tests/test_premailer.py::Tests::test_ignore_some_external_stylesheets", "premailer/tests/test_premailer.py::Tests::test_ignore_some_incorrectly", "premailer/tests/test_premailer.py::Tests::test_ignore_some_inline_stylesheets", "premailer/tests/test_premailer.py::Tests::test_ignore_style_elements_with_media_attribute", "premailer/tests/test_premailer.py::Tests::test_include_star_selector", "premailer/tests/test_premailer.py::Tests::test_inline_important", "premailer/tests/test_premailer.py::Tests::test_inline_wins_over_external", "premailer/tests/test_premailer.py::Tests::test_keyframe_selectors", "premailer/tests/test_premailer.py::Tests::test_last_child", "premailer/tests/test_premailer.py::Tests::test_last_child_exclude_pseudo", "premailer/tests/test_premailer.py::Tests::test_leftover_important", "premailer/tests/test_premailer.py::Tests::test_links_without_protocol", "premailer/tests/test_premailer.py::Tests::test_load_external_url", "premailer/tests/test_premailer.py::Tests::test_mailto_url", "premailer/tests/test_premailer.py::Tests::test_mediaquery", "premailer/tests/test_premailer.py::Tests::test_merge_styles_basic", "premailer/tests/test_premailer.py::Tests::test_merge_styles_non_trivial", "premailer/tests/test_premailer.py::Tests::test_merge_styles_with_class", "premailer/tests/test_premailer.py::Tests::test_merge_styles_with_unset", "premailer/tests/test_premailer.py::Tests::test_mixed_pseudo_selectors", "premailer/tests/test_premailer.py::Tests::test_multiple_style_elements", "premailer/tests/test_premailer.py::Tests::test_multithreading", "premailer/tests/test_premailer.py::Tests::test_parse_style_rules", "premailer/tests/test_premailer.py::Tests::test_precedence_comparison", "premailer/tests/test_premailer.py::Tests::test_remove_classes", "premailer/tests/test_premailer.py::Tests::test_shortcut_function", "premailer/tests/test_premailer.py::Tests::test_six_color", "premailer/tests/test_premailer.py::Tests::test_strip_important", "premailer/tests/test_premailer.py::Tests::test_style_block_with_external_urls", "premailer/tests/test_premailer.py::Tests::test_type_test", "premailer/tests/test_premailer.py::Tests::test_uppercase_margin", "premailer/tests/test_premailer.py::Tests::test_xml_cdata" ]
[]
BSD 3-Clause "New" or "Revised" License
575
kytos__python-openflow-56
275103dca4116b8911dc19ddad4b90121936d9f1
2016-06-07 17:59:27
275103dca4116b8911dc19ddad4b90121936d9f1
diff --git a/pyof/v0x01/common/flow_match.py b/pyof/v0x01/common/flow_match.py index a900b81..07d103e 100644 --- a/pyof/v0x01/common/flow_match.py +++ b/pyof/v0x01/common/flow_match.py @@ -1,6 +1,7 @@ """Defines flow statistics structures and related items""" # System imports +import enum # Third-party imports @@ -8,7 +9,10 @@ from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types -class FlowWildCards(base.GenericBitMask): +# Enums + + +class FlowWildCards(enum.Enum): """ Wildcards used to identify flows. diff --git a/pyof/v0x01/common/phy_port.py b/pyof/v0x01/common/phy_port.py index 7395fb6..b45777f 100644 --- a/pyof/v0x01/common/phy_port.py +++ b/pyof/v0x01/common/phy_port.py @@ -1,6 +1,7 @@ """Defines physical port classes and related items""" # System imports +import enum # Third-party imports @@ -8,20 +9,9 @@ from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types +# Enums + class PortConfig(base.GenericBitMask): - """Flags to indicate behavior of the physical port. - - These flags are used in OFPPhyPort to describe the current configuration. - They are used in the OFPPortMod message to configure the port's behavior. - - OFPPC_PORT_DOWN # Port is administratively down. - OFPPC_NO_STP # Disable 802.1D spanning tree on port. - OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree. - OFPPC_NO_RECV_STP # Drop received 802.1D STP packets. - OFPPC_NO_FLOOD # Do not include this port when flooding. - OFPPC_NO_FWD # Drop packets forwarded to port. - OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port. - """ OFPC_PORT_DOWN = 1 << 0 OFPPC_NO_STP = 1 << 1 OFPPC_NO_RECV = 1 << 2 @@ -31,9 +21,32 @@ class PortConfig(base.GenericBitMask): OFPPC_NO_PACKET_IN = 1 << 6 - - -class PortState(base.GenericBitMask): +#class PortConfig(enum.Enum): +# """Flags to indicate behavior of the physical port. +# +# These flags are used in OFPPhyPort to describe the current configuration. +# They are used in the OFPPortMod message to configure the port's behavior. +# +# Enums: +# OFPPC_PORT_DOWN # Port is administratively down. +# OFPPC_NO_STP # Disable 802.1D spanning tree on port. +# OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree. +# OFPPC_NO_RECV_STP # Drop received 802.1D STP packets. +# OFPPC_NO_FLOOD # Do not include this port when flooding. +# OFPPC_NO_FWD # Drop packets forwarded to port. +# OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port. +# """ +# +# OFPPC_PORT_DOWN = 1 << 0 +# OFPPC_NO_STP = 1 << 1 +# OFPPC_NO_RECV = 1 << 2 +# OFPPC_NO_RECV_STP = 1 << 3 +# OFPPC_FLOOD = 1 << 4 +# OFPPC_NO_FWD = 1 << 5 +# OFPPC_NO_PACKET_IN = 1 << 6 + + +class PortState(enum.Enum): """Current state of the physical port. These are not configurable from the controller. @@ -42,6 +55,7 @@ class PortState(base.GenericBitMask): must adjust OFPPC_NO_RECV, OFPPC_NO_FWD, and OFPPC_NO_PACKET_IN appropriately to fully implement an 802.1D spanning tree. + Enums: OFPPS_LINK_DOWN # Not learning or relaying frames. OFPPS_STP_LISTEN # Not learning or relaying frames. OFPPS_STP_LEARN # Learning but not relaying frames. @@ -58,7 +72,7 @@ class PortState(base.GenericBitMask): # OFPPS_STP_MASK = 3 << 8 - Refer to ISSUE #7 -class Port(base.GenericBitMask): +class Port(enum.Enum): """Port numbering. Physical ports are numbered starting from 1. Port number 0 is reserved by @@ -87,13 +101,14 @@ class Port(base.GenericBitMask): OFPP_NONE = 0xffff -class PortFeatures(base.GenericBitMask): +class PortFeatures(enum.Enum): """Physical ports features. The curr, advertised, supported, and peer fields indicate link modes (10M to 10G full and half-duplex), link type (copper/fiber) and link features (autone-gotiation and pause). + Enums: OFPPF_10MB_HD # 10 Mb half-duplex rate support. OFPPF_10MB_FD # 10 Mb full-duplex rate support. OFPPF_100MB_HD # 100 Mb half-duplex rate support. diff --git a/pyof/v0x01/controller2switch/aggregate_stats_reply.py b/pyof/v0x01/controller2switch/aggregate_stats_reply.py deleted file mode 100644 index 339127c..0000000 --- a/pyof/v0x01/controller2switch/aggregate_stats_reply.py +++ /dev/null @@ -1,31 +0,0 @@ -"""Body of the reply message""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - -# Classes - - -class AggregateStatsReply(base.GenericStruct): - """Body of reply to OFPST_AGGREGATE request. - - :param packet_count: Number of packets in flows - :param byte_count: Number of bytes in flows - :param flow_count: Number of flows - :param pad: Align to 64 bits - - """ - packet_count = basic_types.UBInt64() - byte_count = basic_types.UBInt64() - flow_count = basic_types.UBInt32() - pad = basic_types.PAD(4) - - def __init__(self, packet_count=None, byte_count=None, flow_count=None): - self.packet_count = packet_count - self.byte_count = byte_count - self.flow_count = flow_count diff --git a/pyof/v0x01/controller2switch/aggregate_stats_request.py b/pyof/v0x01/controller2switch/aggregate_stats_request.py deleted file mode 100644 index b45f923..0000000 --- a/pyof/v0x01/controller2switch/aggregate_stats_request.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Aggregate information about multiple flows is requested with the -OFPST_AGGREGATE stats request type""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.common import flow_match -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - -# Classes - - -class AggregateStatsRequest(base.GenericStruct): - """ - Body for ofp_stats_request of type OFPST_AGGREGATE. - - :param match: Fields to match - :param table_id: ID of table to read (from pyof_table_stats) 0xff - for all tables or 0xfe for emergency. - :param pad: Align to 32 bits - :param out_port: Require matching entries to include this as an - output port. A value of OFPP_NONE indicates - no restriction - - """ - match = flow_match.Match() - table_id = basic_types.UBInt8() - pad = basic_types.PAD(1) - out_port = basic_types.UBInt16() - - def __init__(self, match=None, table_id=None, out_port=None): - super().__init__() - self.match = match - self.table_id = table_id - self.out_port = out_port diff --git a/pyof/v0x01/controller2switch/common.py b/pyof/v0x01/controller2switch/common.py index c5490dd..bfb9cd3 100644 --- a/pyof/v0x01/controller2switch/common.py +++ b/pyof/v0x01/controller2switch/common.py @@ -8,6 +8,7 @@ import enum # Local source tree imports from pyof.v0x01.common import header as of_header from pyof.v0x01.common import action +from pyof.v0x01.common import flow_match from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types @@ -65,3 +66,313 @@ class ListOfActions(basic_types.FixedTypeList): """ def __init__(self, items=None): super().__init__(pyof_class=action.ActionHeader, items=items) + + +class AggregateStatsReply(base.GenericStruct): + """Body of reply to OFPST_AGGREGATE request. + + :param packet_count: Number of packets in flows + :param byte_count: Number of bytes in flows + :param flow_count: Number of flows + :param pad: Align to 64 bits + + """ + packet_count = basic_types.UBInt64() + byte_count = basic_types.UBInt64() + flow_count = basic_types.UBInt32() + pad = basic_types.PAD(4) + + def __init__(self, packet_count=None, byte_count=None, flow_count=None): + self.packet_count = packet_count + self.byte_count = byte_count + self.flow_count = flow_count + + +class AggregateStatsRequest(base.GenericStruct): + """ + Body for ofp_stats_request of type OFPST_AGGREGATE. + + :param match: Fields to match + :param table_id: ID of table to read (from pyof_table_stats) 0xff + for all tables or 0xfe for emergency. + :param pad: Align to 32 bits + :param out_port: Require matching entries to include this as an + output port. A value of OFPP_NONE indicates + no restriction + + """ + match = flow_match.Match() + table_id = basic_types.UBInt8() + pad = basic_types.PAD(1) + out_port = basic_types.UBInt16() + + def __init__(self, match=None, table_id=None, out_port=None): + super().__init__() + self.match = match + self.table_id = table_id + self.out_port = out_port + + +class DescStats(base.GenericStruct): + """ + Information about the switch manufacturer, hardware revision, software + revision, serial number, and a description field is avail- able from + the OFPST_DESC stats request. + + :param mfr_desc: Manufacturer description + :param hw_desc: Hardware description + :param sw_desc: Software description + :param serial_num: Serial number + :param dp_desc: Human readable description of datapath + + """ + mfr_desc = basic_types.Char(length=base.DESC_STR_LEN) + hw_desc = basic_types.Char(length=base.DESC_STR_LEN) + sw_desc = basic_types.Char(length=base.DESC_STR_LEN) + serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN) + dp_desc = basic_types.Char(length=base.DESC_STR_LEN) + + def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None, + serial_num=None, dp_desc=None): + self.mfr_desc = mfr_desc + self.hw_desc = hw_desc + self.sw_desc = sw_desc + self.serial_num = serial_num + self.dp_desc = dp_desc + + +class FlowStats(base.GenericStruct): + """ + Body of reply to OFPST_FLOW request. + + :param length: Length of this entry + :param table_id: ID of table flow came from + :param pad: Align to 32 bits + :param match: Description of fields + :param duration_sec: Time flow has been alive in seconds + :param duration_nsec: Time flow has been alive in nanoseconds beyond + duration_sec + :param priority: Priority of the entry. Only meaningful when this + is not an exact-match entry + :param idle_timeout: Number of seconds idle before expiration + :param hard_timeout: Number of seconds before expiration + :param pad2: Align to 64-bits + :param cookie: Opaque controller-issued identifier + :param packet_count: Number of packets in flow + :param byte_count: Number of bytes in flow + :param actions: Actions + """ + length = basic_types.UBInt16() + table_id = basic_types.UBInt8() + pad = basic_types.PAD(1) + match = flow_match.Match() + duration_sec = basic_types.UBInt32() + duration_nsec = basic_types.UBInt32() + priority = basic_types.UBInt16() + idle_timeout = basic_types.UBInt16() + hard_timeout = basic_types.UBInt16() + pad2 = basic_types.PAD(6) + cookie = basic_types.UBInt64() + packet_count = basic_types.UBInt64() + byte_count = basic_types.UBInt64() + actions = ListOfActions() + + def __init__(self, length=None, table_id=None, match=None, + duration_sec=None, duration_nsec=None, priority=None, + idle_timeout=None, hard_timeout=None, cookie=None, + packet_count=None, byte_count=None, actions=None): + self.length = length + self.table_id = table_id + self.match = match + self.duration_sec = duration_sec + self.duration_nsec = duration_nsec + self.prioriry = priority + self.idle_timeout = idle_timeout + self.hard_timeout = hard_timeout + self.cookie = cookie + self.packet_count = packet_count + self.byte_count = byte_count + self.actions = [] if actions is None else actions + + +class FlowStatsRequest(base.GenericStruct): + """ + Body for ofp_stats_request of type OFPST_FLOW. + + :param match: Fields to match + :param table_id: ID of table to read (from pyof_table_stats) + 0xff for all tables or 0xfe for emergency + :param pad: Align to 32 bits + :param out_port: Require matching entries to include this as an output + port. A value of OFPP_NONE indicates no restriction. + + """ + match = flow_match.Match() + table_id = basic_types.UBInt8() + pad = basic_types.PAD(1) + out_port = basic_types.UBInt16() + + def __init__(self, match=None, table_id=None, out_port=None): + self.match = match + self.table_id = table_id + self.out_port = out_port + + +class PortStats(base.GenericStruct): + """Body of reply to OFPST_PORT request. + + If a counter is unsupported, set the field to all ones. + + :param port_no: Port number + :param pad: Align to 64-bits + :param rx_packets: Number of received packets + :param tx_packets: Number of transmitted packets + :param rx_bytes: Number of received bytes + :param tx_bytes: Number of transmitted bytes + :param rx_dropped: Number of packets dropped by RX + :param tx_dropped: Number of packets dropped by TX + :param rx_errors: Number of receive errors. This is a super-set + of more specific receive errors and should be + greater than or equal to the sum of all + rx_*_err values + :param tx_errors: Number of transmit errors. This is a super-set + of more specific transmit errors and should be + greater than or equal to the sum of all + tx_*_err values (none currently defined.) + :param rx_frame_err: Number of frame alignment errors + :param rx_over_err: Number of packets with RX overrun + :param rx_crc_err: Number of CRC errors + :param collisions: Number of collisions + + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(6) + rx_packets = basic_types.UBInt64() + tx_packets = basic_types.UBInt64() + rx_bytes = basic_types.UBInt64() + tx_bytes = basic_types.UBInt64() + rx_dropped = basic_types.UBInt64() + tx_dropped = basic_types.UBInt64() + rx_errors = basic_types.UBInt64() + tx_errors = basic_types.UBInt64() + rx_frame_err = basic_types.UBInt64() + rx_over_err = basic_types.UBInt64() + rx_crc_err = basic_types.UBInt64() + collisions = basic_types.UBInt64() + + def __init__(self, port_no=None, rx_packets=None, + tx_packets=None, rx_bytes=None, tx_bytes=None, + rx_dropped=None, tx_dropped=None, rx_errors=None, + tx_errors=None, rx_frame_err=None, rx_over_err=None, + rx_crc_err=None, collisions=None): + self.port_no = port_no + self.rx_packets = rx_packets + self.tx_packets = tx_packets + self.rx_bytes = rx_bytes + self.tx_bytes = tx_bytes + self.rx_dropped = rx_dropped + self.tx_dropped = tx_dropped + self.rx_errors = rx_errors + self.tx_errors = tx_errors + self.rx_frame_err = rx_frame_err + self.rx_over_err = rx_over_err + self.rx_crc_err = rx_crc_err + self.collisions = collisions + + +class PortStatsRequest(base.GenericStruct): + """ + Body for ofp_stats_request of type OFPST_PORT + + :param port_no: OFPST_PORT message must request statistics either + for a single port (specified in port_no) or for + all ports (if port_no == OFPP_NONE). + :param pad: + + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(6) + + def __init__(self, port_no=None): + self.port_no = port_no + + +class QueueStats(base.GenericStruct): + """ + Implements the reply body of a port_no + + :param port_no: Port Number + :param pad: Align to 32-bits + :param queue_id: Queue ID + :param tx_bytes: Number of transmitted bytes + :param tx_packets: Number of transmitted packets + :param tx_errors: Number of packets dropped due to overrun + + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(2) + queue_id = basic_types.UBInt32() + tx_bytes = basic_types.UBInt64() + tx_packets = basic_types.UBInt64() + tx_errors = basic_types.UBInt64() + + def __init__(self, port_no=None, queue_id=None, tx_bytes=None, + tx_packets=None, tx_errors=None): + self.port_no = port_no + self.queue_id = queue_id + self.tx_bytes = tx_bytes + self.tx_packets = tx_packets + self.tx_errors = tx_errors + + +class QueueStatsRequest(base.GenericStruct): + """ + Implements the request body of a port_no + + :param port_no: All ports if OFPT_ALL + :param pad: Align to 32-bits + :param queue_id: All queues if OFPQ_ALL + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(2) + queue_id = basic_types.UBInt32() + + def __init__(self, port_no=None, queue_id=None): + self.port_no = port_no + self.queue_id = queue_id + + +class TableStats(base.GenericStruct): + """Body of reply to OFPST_TABLE request. + + :param table_id: Identifier of table. Lower numbered tables + are consulted first + :param pad: Align to 32-bits + :param name: Table name + :param wildcards: Bitmap of OFPFW_* wildcards that are supported + by the table + :param max_entries: Max number of entries supported + :param active_count: Number of active entries + :param count_lookup: Number of packets looked up in table + :param count_matched: Number of packets that hit table + + """ + table_id = basic_types.UBInt8() + pad = basic_types.PAD(3) + name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN) + wildcards = basic_types.UBInt32() + max_entries = basic_types.UBInt32() + active_count = basic_types.UBInt32() + count_lookup = basic_types.UBInt64() + count_matched = basic_types.UBInt64() + + def __init__(self, table_id=None, name=None, wildcards=None, + max_entries=None, active_count=None, count_lookup=None, + count_matched=None): + self.table_id = table_id + self.name = name + self.wildcards = wildcards + self.max_entries = max_entries + self.active_count = active_count + self.count_lookup = count_lookup + self.count_matched = count_matched diff --git a/pyof/v0x01/controller2switch/desc_stats.py b/pyof/v0x01/controller2switch/desc_stats.py deleted file mode 100644 index bceffb9..0000000 --- a/pyof/v0x01/controller2switch/desc_stats.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Information about the switch manufactures""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - -# Classes - - -class DescStats(base.GenericStruct): - """ - Information about the switch manufacturer, hardware revision, software - revision, serial number, and a description field is avail- able from - the OFPST_DESC stats request. - - :param mfr_desc: Manufacturer description - :param hw_desc: Hardware description - :param sw_desc: Software description - :param serial_num: Serial number - :param dp_desc: Human readable description of datapath - - """ - mfr_desc = basic_types.Char(length=base.DESC_STR_LEN) - hw_desc = basic_types.Char(length=base.DESC_STR_LEN) - sw_desc = basic_types.Char(length=base.DESC_STR_LEN) - serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN) - dp_desc = basic_types.Char(length=base.DESC_STR_LEN) - - def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None, - serial_num=None, dp_desc=None): - self.mfr_desc = mfr_desc - self.hw_desc = hw_desc - self.sw_desc = sw_desc - self.serial_num = serial_num - self.dp_desc = dp_desc diff --git a/pyof/v0x01/controller2switch/features_reply.py b/pyof/v0x01/controller2switch/features_reply.py index c5f3bca..e02f012 100644 --- a/pyof/v0x01/controller2switch/features_reply.py +++ b/pyof/v0x01/controller2switch/features_reply.py @@ -1,6 +1,7 @@ """Defines Features Reply classes and related items""" # System imports +import enum # Third-party imports @@ -11,9 +12,13 @@ from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types -class Capabilities(base.GenericBitMask): - """Capabilities supported by the datapath +# Enums + +class Capabilities(enum.Enum): + """Enumeration of Capabilities supported by the datapath + + Enums: OFPC_FLOW_STATS # Flow statistics OFPC_TABLE_STATS # Table statistics OFPC_PORT_STATS # Port statistics diff --git a/pyof/v0x01/controller2switch/flow_stats.py b/pyof/v0x01/controller2switch/flow_stats.py deleted file mode 100644 index efb5edd..0000000 --- a/pyof/v0x01/controller2switch/flow_stats.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Body of the reply to an OFPST_FLOW""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.common import flow_match -from pyof.v0x01.controller2switch import common -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - -# Classes - - -class FlowStats(base.GenericStruct): - """ - Body of reply to OFPST_FLOW request. - - :param length: Length of this entry - :param table_id: ID of table flow came from - :param pad: Align to 32 bits - :param match: Description of fields - :param duration_sec: Time flow has been alive in seconds - :param duration_nsec: Time flow has been alive in nanoseconds beyond - duration_sec - :param priority: Priority of the entry. Only meaningful when this - is not an exact-match entry - :param idle_timeout: Number of seconds idle before expiration - :param hard_timeout: Number of seconds before expiration - :param pad2: Align to 64-bits - :param cookie: Opaque controller-issued identifier - :param packet_count: Number of packets in flow - :param byte_count: Number of bytes in flow - :param actions: Actions - """ - length = basic_types.UBInt16() - table_id = basic_types.UBInt8() - pad = basic_types.PAD(1) - match = flow_match.Match() - duration_sec = basic_types.UBInt32() - duration_nsec = basic_types.UBInt32() - priority = basic_types.UBInt16() - idle_timeout = basic_types.UBInt16() - hard_timeout = basic_types.UBInt16() - pad2 = basic_types.PAD(6) - cookie = basic_types.UBInt64() - packet_count = basic_types.UBInt64() - byte_count = basic_types.UBInt64() - actions = common.ListOfActions() - - def __init__(self, length=None, table_id=None, match=None, - duration_sec=None, duration_nsec=None, priority=None, - idle_timeout=None, hard_timeout=None, cookie=None, - packet_count=None, byte_count=None, actions=None): - self.length = length - self.table_id = table_id - self.match = match - self.duration_sec = duration_sec - self.duration_nsec = duration_nsec - self.prioriry = priority - self.idle_timeout = idle_timeout - self.hard_timeout = hard_timeout - self.cookie = cookie - self.packet_count = packet_count - self.byte_count = byte_count - self.actions = [] if actions is None else actions diff --git a/pyof/v0x01/controller2switch/flow_stats_request.py b/pyof/v0x01/controller2switch/flow_stats_request.py deleted file mode 100644 index 1fc5794..0000000 --- a/pyof/v0x01/controller2switch/flow_stats_request.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Information about individual flows""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.common import flow_match -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - -# Classes - - -class FlowStatsRequest(base.GenericStruct): - """ - Body for ofp_stats_request of type OFPST_FLOW. - - :param match: Fields to match - :param table_id: ID of table to read (from pyof_table_stats) - 0xff for all tables or 0xfe for emergency - :param pad: Align to 32 bits - :param out_port: Require matching entries to include this as an output - port. A value of OFPP_NONE indicates no restriction. - - """ - match = flow_match.Match() - table_id = basic_types.UBInt8() - pad = basic_types.PAD(1) - out_port = basic_types.UBInt16() - - def __init__(self, match=None, table_id=None, out_port=None): - self.match = match - self.table_id = table_id - self.out_port = out_port diff --git a/pyof/v0x01/controller2switch/port_stats.py b/pyof/v0x01/controller2switch/port_stats.py deleted file mode 100644 index 474828d..0000000 --- a/pyof/v0x01/controller2switch/port_stats.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Body of the port stats reply""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - -# Classes - - -class PortStats(base.GenericStruct): - """Body of reply to OFPST_PORT request. - - If a counter is unsupported, set the field to all ones. - - :param port_no: Port number - :param pad: Align to 64-bits - :param rx_packets: Number of received packets - :param tx_packets: Number of transmitted packets - :param rx_bytes: Number of received bytes - :param tx_bytes: Number of transmitted bytes - :param rx_dropped: Number of packets dropped by RX - :param tx_dropped: Number of packets dropped by TX - :param rx_errors: Number of receive errors. This is a super-set - of more specific receive errors and should be - greater than or equal to the sum of all - rx_*_err values - :param tx_errors: Number of transmit errors. This is a super-set - of more specific transmit errors and should be - greater than or equal to the sum of all - tx_*_err values (none currently defined.) - :param rx_frame_err: Number of frame alignment errors - :param rx_over_err: Number of packets with RX overrun - :param rx_crc_err: Number of CRC errors - :param collisions: Number of collisions - - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(6) - rx_packets = basic_types.UBInt64() - tx_packets = basic_types.UBInt64() - rx_bytes = basic_types.UBInt64() - tx_bytes = basic_types.UBInt64() - rx_dropped = basic_types.UBInt64() - tx_dropped = basic_types.UBInt64() - rx_errors = basic_types.UBInt64() - tx_errors = basic_types.UBInt64() - rx_frame_err = basic_types.UBInt64() - rx_over_err = basic_types.UBInt64() - rx_crc_err = basic_types.UBInt64() - collisions = basic_types.UBInt64() - - def __init__(self, port_no=None, rx_packets=None, - tx_packets=None, rx_bytes=None, tx_bytes=None, - rx_dropped=None, tx_dropped=None, rx_errors=None, - tx_errors=None, rx_frame_err=None, rx_over_err=None, - rx_crc_err=None, collisions=None): - self.port_no = port_no - self.rx_packets = rx_packets - self.tx_packets = tx_packets - self.rx_bytes = rx_bytes - self.tx_bytes = tx_bytes - self.rx_dropped = rx_dropped - self.tx_dropped = tx_dropped - self.rx_errors = rx_errors - self.tx_errors = tx_errors - self.rx_frame_err = rx_frame_err - self.rx_over_err = rx_over_err - self.rx_crc_err = rx_crc_err - self.collisions = collisions diff --git a/pyof/v0x01/controller2switch/port_stats_request.py b/pyof/v0x01/controller2switch/port_stats_request.py deleted file mode 100644 index 8fa4049..0000000 --- a/pyof/v0x01/controller2switch/port_stats_request.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Information about physical ports is requested with OFPST_PORT""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - - -class PortStatsRequest(base.GenericStruct): - """ - Body for ofp_stats_request of type OFPST_PORT - - :param port_no: OFPST_PORT message must request statistics either - for a single port (specified in port_no) or for - all ports (if port_no == OFPP_NONE). - :param pad: - - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(6) - - def __init__(self, port_no=None): - self.port_no = port_no diff --git a/pyof/v0x01/controller2switch/queue_stats.py b/pyof/v0x01/controller2switch/queue_stats.py deleted file mode 100644 index d7df9b3..0000000 --- a/pyof/v0x01/controller2switch/queue_stats.py +++ /dev/null @@ -1,38 +0,0 @@ -"""The OFPST_QUEUE stats reply message provides queue statistics for one -or more ports.""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - - -class QueueStats(base.GenericStruct): - """ - Implements the reply body of a port_no - - :param port_no: Port Number - :param pad: Align to 32-bits - :param queue_id: Queue ID - :param tx_bytes: Number of transmitted bytes - :param tx_packets: Number of transmitted packets - :param tx_errors: Number of packets dropped due to overrun - - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(2) - queue_id = basic_types.UBInt32() - tx_bytes = basic_types.UBInt64() - tx_packets = basic_types.UBInt64() - tx_errors = basic_types.UBInt64() - - def __init__(self, port_no=None, queue_id=None, tx_bytes=None, - tx_packets=None, tx_errors=None): - self.port_no = port_no - self.queue_id = queue_id - self.tx_bytes = tx_bytes - self.tx_packets = tx_packets - self.tx_errors = tx_errors diff --git a/pyof/v0x01/controller2switch/queue_stats_request.py b/pyof/v0x01/controller2switch/queue_stats_request.py deleted file mode 100644 index c1b431b..0000000 --- a/pyof/v0x01/controller2switch/queue_stats_request.py +++ /dev/null @@ -1,27 +0,0 @@ -"""The OFPST_QUEUE stats request message provides queue statistics for one -or more ports.""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - - -class QueueStatsRequest(base.GenericStruct): - """ - Implements the request body of a port_no - - :param port_no: All ports if OFPT_ALL - :param pad: Align to 32-bits - :param queue_id: All queues if OFPQ_ALL - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(2) - queue_id = basic_types.UBInt32() - - def __init__(self, port_no=None, queue_id=None): - self.port_no = port_no - self.queue_id = queue_id diff --git a/pyof/v0x01/controller2switch/table_stats.py b/pyof/v0x01/controller2switch/table_stats.py deleted file mode 100644 index bf2e42f..0000000 --- a/pyof/v0x01/controller2switch/table_stats.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Information about tables is requested with OFPST_TABLE stats request type""" - -# System imports - -# Third-party imports - -# Local source tree imports -from pyof.v0x01.foundation import base -from pyof.v0x01.foundation import basic_types - - -class TableStats(base.GenericStruct): - """Body of reply to OFPST_TABLE request. - - :param table_id: Identifier of table. Lower numbered tables - are consulted first - :param pad: Align to 32-bits - :param name: Table name - :param wildcards: Bitmap of OFPFW_* wildcards that are supported - by the table - :param max_entries: Max number of entries supported - :param active_count: Number of active entries - :param count_lookup: Number of packets looked up in table - :param count_matched: Number of packets that hit table - - """ - table_id = basic_types.UBInt8() - pad = basic_types.PAD(3) - name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN) - wildcards = basic_types.UBInt32() - max_entries = basic_types.UBInt32() - active_count = basic_types.UBInt32() - count_lookup = basic_types.UBInt64() - count_matched = basic_types.UBInt64() - - def __init__(self, table_id=None, name=None, wildcards=None, - max_entries=None, active_count=None, count_lookup=None, - count_matched=None): - self.table_id = table_id - self.name = name - self.wildcards = wildcards - self.max_entries = max_entries - self.active_count = active_count - self.count_lookup = count_lookup - self.count_matched = count_matched
Move all non-messages classes to other files Some classes (structs) does not define messages, but only structures that will be used on messages (such as "desc_stats"). As defined, only "messages" will have a "file" (submodule) for itself. No, the files that does not hold a message should have its content splitted into other files.
kytos/python-openflow
diff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py index 3fc3326..1c699dd 100644 --- a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py +++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch import aggregate_stats_reply +from pyof.v0x01.controller2switch.common import AggregateStatsReply class TestAggregateStatsReply(unittest.TestCase): def setUp(self): - self.message = aggregate_stats_reply.AggregateStatsReply() + self.message = AggregateStatsReply() self.message.packet_count = 5 self.message.byte_count = 1 self.message.flow_count = 8 diff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py index ca563fe..8e4be10 100644 --- a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py @@ -2,13 +2,13 @@ import unittest from pyof.v0x01.common import flow_match from pyof.v0x01.common import phy_port -from pyof.v0x01.controller2switch import aggregate_stats_request +from pyof.v0x01.controller2switch.common import AggregateStatsRequest class TestAggregateStatsRequest(unittest.TestCase): def setUp(self): - self.message = aggregate_stats_request.AggregateStatsRequest() + self.message = AggregateStatsRequest() self.message.match = flow_match.Match() self.message.table_id = 1 self.message.out_port = phy_port.Port.OFPP_NONE diff --git a/tests/v0x01/test_controller2switch/test_desc_stats.py b/tests/v0x01/test_controller2switch/test_desc_stats.py index 5ea6422..4f13f97 100644 --- a/tests/v0x01/test_controller2switch/test_desc_stats.py +++ b/tests/v0x01/test_controller2switch/test_desc_stats.py @@ -1,6 +1,6 @@ import unittest -from pyof.v0x01.controller2switch import desc_stats +from pyof.v0x01.controller2switch.common import DescStats from pyof.v0x01.foundation import base @@ -8,7 +8,7 @@ class TestDescStats(unittest.TestCase): def setUp(self): content = bytes('A' * base.DESC_STR_LEN, 'utf-8') - self.message = desc_stats.DescStats() + self.message = DescStats() self.message.mfr_desc = content self.message.hw_desc = content self.message.sw_desc = content diff --git a/tests/v0x01/test_controller2switch/test_flow_stats.py b/tests/v0x01/test_controller2switch/test_flow_stats.py index 1de34ab..2a04c07 100644 --- a/tests/v0x01/test_controller2switch/test_flow_stats.py +++ b/tests/v0x01/test_controller2switch/test_flow_stats.py @@ -1,13 +1,13 @@ import unittest from pyof.v0x01.common import flow_match -from pyof.v0x01.controller2switch import flow_stats +from pyof.v0x01.controller2switch.common import FlowStats class TestFlowStats(unittest.TestCase): def setUp(self): - self.message = flow_stats.FlowStats() + self.message = FlowStats() self.message.length = 160 self.message.table_id = 1 self.message.match = flow_match.Match() diff --git a/tests/v0x01/test_controller2switch/test_flow_stats_request.py b/tests/v0x01/test_controller2switch/test_flow_stats_request.py index 85a33bb..2a6f3fb 100644 --- a/tests/v0x01/test_controller2switch/test_flow_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_flow_stats_request.py @@ -1,13 +1,13 @@ import unittest from pyof.v0x01.common import flow_match -from pyof.v0x01.controller2switch import flow_stats_request +from pyof.v0x01.controller2switch.common import FlowStatsRequest class TestFlowStatsRequest(unittest.TestCase): def setUp(self): - self.message = flow_stats_request.FlowStatsRequest() + self.message = FlowStatsRequest() self.message.match = flow_match.Match() self.message.table_id = 1 self.message.out_port = 80 diff --git a/tests/v0x01/test_controller2switch/test_port_stats.py b/tests/v0x01/test_controller2switch/test_port_stats.py index 7a58485..e6f4b55 100644 --- a/tests/v0x01/test_controller2switch/test_port_stats.py +++ b/tests/v0x01/test_controller2switch/test_port_stats.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch import port_stats +from pyof.v0x01.controller2switch.common import PortStats class TestPortStats(unittest.TestCase): def setUp(self): - self.message = port_stats.PortStats() + self.message = PortStats() self.message.port_no = 80 self.message.rx_packets = 5 self.message.tx_packets = 10 diff --git a/tests/v0x01/test_controller2switch/test_port_stats_request.py b/tests/v0x01/test_controller2switch/test_port_stats_request.py index e0454dc..8025055 100644 --- a/tests/v0x01/test_controller2switch/test_port_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_port_stats_request.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch import port_stats_request +from pyof.v0x01.controller2switch.common import PortStatsRequest class TestPortStatsRequest(unittest.TestCase): def setUp(self): - self.message = port_stats_request.PortStatsRequest() + self.message = PortStatsRequest() self.message.port_no = 80 def test_get_size(self): diff --git a/tests/v0x01/test_controller2switch/test_queue_stats.py b/tests/v0x01/test_controller2switch/test_queue_stats.py index fb03ee7..b1f1219 100644 --- a/tests/v0x01/test_controller2switch/test_queue_stats.py +++ b/tests/v0x01/test_controller2switch/test_queue_stats.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch import queue_stats +from pyof.v0x01.controller2switch.common import QueueStats class TestQueueStats(unittest.TestCase): def setUp(self): - self.message = queue_stats.QueueStats() + self.message = QueueStats() self.message.port_no = 80 self.message.queue_id = 5 self.message.tx_bytes = 1 diff --git a/tests/v0x01/test_controller2switch/test_queue_stats_request.py b/tests/v0x01/test_controller2switch/test_queue_stats_request.py index 80cad68..2f95381 100644 --- a/tests/v0x01/test_controller2switch/test_queue_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_queue_stats_request.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch import queue_stats_request +from pyof.v0x01.controller2switch.common import QueueStatsRequest class TestQueueStatsRequest(unittest.TestCase): def setUp(self): - self.message = queue_stats_request.QueueStatsRequest() + self.message = QueueStatsRequest() self.message.port_no = 80 self.message.queue_id = 5 diff --git a/tests/v0x01/test_controller2switch/test_table_stats.py b/tests/v0x01/test_controller2switch/test_table_stats.py index 353f6de..39888b5 100644 --- a/tests/v0x01/test_controller2switch/test_table_stats.py +++ b/tests/v0x01/test_controller2switch/test_table_stats.py @@ -1,14 +1,14 @@ import unittest from pyof.v0x01.common import flow_match -from pyof.v0x01.controller2switch import table_stats +from pyof.v0x01.controller2switch.common import TableStats from pyof.v0x01.foundation import base class TestTableStats(unittest.TestCase): def setUp(self): - self.message = table_stats.TableStats() + self.message = TableStats() self.message.table_id = 1 self.message.name = bytes('X' * base.OFP_MAX_TABLE_NAME_LEN, 'utf-8') self.message.wildcards = flow_match.FlowWildCards.OFPFW_TP_DST
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 4 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 iniconfig==2.1.0 -e git+https://github.com/kytos/python-openflow.git@275103dca4116b8911dc19ddad4b90121936d9f1#egg=Kytos_OpenFlow_Parser_library packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 tomli==2.2.1 typing_extensions==4.13.0
name: python-openflow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - tomli==2.2.1 - typing-extensions==4.13.0 prefix: /opt/conda/envs/python-openflow
[ "tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py::TestAggregateStatsReply::test_get_size", "tests/v0x01/test_controller2switch/test_aggregate_stats_request.py::TestAggregateStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_desc_stats.py::TestDescStats::test_get_size", "tests/v0x01/test_controller2switch/test_flow_stats.py::TestFlowStats::test_get_size", "tests/v0x01/test_controller2switch/test_flow_stats_request.py::TestFlowStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_port_stats.py::TestPortStats::test_get_size", "tests/v0x01/test_controller2switch/test_port_stats_request.py::TestPortStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_queue_stats.py::TestQueueStats::test_get_size", "tests/v0x01/test_controller2switch/test_queue_stats_request.py::TestQueueStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_table_stats.py::TestTableStats::test_get_size" ]
[]
[]
[]
MIT License
576
kytos__python-openflow-58
545ae8a73dcec2e67cf854b21c44e692692f71dc
2016-06-07 18:27:19
545ae8a73dcec2e67cf854b21c44e692692f71dc
diff --git a/pyof/v0x01/common/flow_match.py b/pyof/v0x01/common/flow_match.py index a900b81..07d103e 100644 --- a/pyof/v0x01/common/flow_match.py +++ b/pyof/v0x01/common/flow_match.py @@ -1,6 +1,7 @@ """Defines flow statistics structures and related items""" # System imports +import enum # Third-party imports @@ -8,7 +9,10 @@ from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types -class FlowWildCards(base.GenericBitMask): +# Enums + + +class FlowWildCards(enum.Enum): """ Wildcards used to identify flows. diff --git a/pyof/v0x01/common/phy_port.py b/pyof/v0x01/common/phy_port.py index 7395fb6..b45777f 100644 --- a/pyof/v0x01/common/phy_port.py +++ b/pyof/v0x01/common/phy_port.py @@ -1,6 +1,7 @@ """Defines physical port classes and related items""" # System imports +import enum # Third-party imports @@ -8,20 +9,9 @@ from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types +# Enums + class PortConfig(base.GenericBitMask): - """Flags to indicate behavior of the physical port. - - These flags are used in OFPPhyPort to describe the current configuration. - They are used in the OFPPortMod message to configure the port's behavior. - - OFPPC_PORT_DOWN # Port is administratively down. - OFPPC_NO_STP # Disable 802.1D spanning tree on port. - OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree. - OFPPC_NO_RECV_STP # Drop received 802.1D STP packets. - OFPPC_NO_FLOOD # Do not include this port when flooding. - OFPPC_NO_FWD # Drop packets forwarded to port. - OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port. - """ OFPC_PORT_DOWN = 1 << 0 OFPPC_NO_STP = 1 << 1 OFPPC_NO_RECV = 1 << 2 @@ -31,9 +21,32 @@ class PortConfig(base.GenericBitMask): OFPPC_NO_PACKET_IN = 1 << 6 - - -class PortState(base.GenericBitMask): +#class PortConfig(enum.Enum): +# """Flags to indicate behavior of the physical port. +# +# These flags are used in OFPPhyPort to describe the current configuration. +# They are used in the OFPPortMod message to configure the port's behavior. +# +# Enums: +# OFPPC_PORT_DOWN # Port is administratively down. +# OFPPC_NO_STP # Disable 802.1D spanning tree on port. +# OFPPC_NO_RECV # Drop all packets except 802.1D spanning tree. +# OFPPC_NO_RECV_STP # Drop received 802.1D STP packets. +# OFPPC_NO_FLOOD # Do not include this port when flooding. +# OFPPC_NO_FWD # Drop packets forwarded to port. +# OFPPC_NO_PACKET_IN # Do not send packet-in msgs for port. +# """ +# +# OFPPC_PORT_DOWN = 1 << 0 +# OFPPC_NO_STP = 1 << 1 +# OFPPC_NO_RECV = 1 << 2 +# OFPPC_NO_RECV_STP = 1 << 3 +# OFPPC_FLOOD = 1 << 4 +# OFPPC_NO_FWD = 1 << 5 +# OFPPC_NO_PACKET_IN = 1 << 6 + + +class PortState(enum.Enum): """Current state of the physical port. These are not configurable from the controller. @@ -42,6 +55,7 @@ class PortState(base.GenericBitMask): must adjust OFPPC_NO_RECV, OFPPC_NO_FWD, and OFPPC_NO_PACKET_IN appropriately to fully implement an 802.1D spanning tree. + Enums: OFPPS_LINK_DOWN # Not learning or relaying frames. OFPPS_STP_LISTEN # Not learning or relaying frames. OFPPS_STP_LEARN # Learning but not relaying frames. @@ -58,7 +72,7 @@ class PortState(base.GenericBitMask): # OFPPS_STP_MASK = 3 << 8 - Refer to ISSUE #7 -class Port(base.GenericBitMask): +class Port(enum.Enum): """Port numbering. Physical ports are numbered starting from 1. Port number 0 is reserved by @@ -87,13 +101,14 @@ class Port(base.GenericBitMask): OFPP_NONE = 0xffff -class PortFeatures(base.GenericBitMask): +class PortFeatures(enum.Enum): """Physical ports features. The curr, advertised, supported, and peer fields indicate link modes (10M to 10G full and half-duplex), link type (copper/fiber) and link features (autone-gotiation and pause). + Enums: OFPPF_10MB_HD # 10 Mb half-duplex rate support. OFPPF_10MB_FD # 10 Mb full-duplex rate support. OFPPF_100MB_HD # 100 Mb half-duplex rate support. diff --git a/pyof/v0x01/controller2switch/aggregate_stats_reply.py b/pyof/v0x01/controller2switch/aggregate_stats_reply.py new file mode 100644 index 0000000..339127c --- /dev/null +++ b/pyof/v0x01/controller2switch/aggregate_stats_reply.py @@ -0,0 +1,31 @@ +"""Body of the reply message""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + +# Classes + + +class AggregateStatsReply(base.GenericStruct): + """Body of reply to OFPST_AGGREGATE request. + + :param packet_count: Number of packets in flows + :param byte_count: Number of bytes in flows + :param flow_count: Number of flows + :param pad: Align to 64 bits + + """ + packet_count = basic_types.UBInt64() + byte_count = basic_types.UBInt64() + flow_count = basic_types.UBInt32() + pad = basic_types.PAD(4) + + def __init__(self, packet_count=None, byte_count=None, flow_count=None): + self.packet_count = packet_count + self.byte_count = byte_count + self.flow_count = flow_count diff --git a/pyof/v0x01/controller2switch/aggregate_stats_request.py b/pyof/v0x01/controller2switch/aggregate_stats_request.py new file mode 100644 index 0000000..b45f923 --- /dev/null +++ b/pyof/v0x01/controller2switch/aggregate_stats_request.py @@ -0,0 +1,38 @@ +"""Aggregate information about multiple flows is requested with the +OFPST_AGGREGATE stats request type""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.common import flow_match +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + +# Classes + + +class AggregateStatsRequest(base.GenericStruct): + """ + Body for ofp_stats_request of type OFPST_AGGREGATE. + + :param match: Fields to match + :param table_id: ID of table to read (from pyof_table_stats) 0xff + for all tables or 0xfe for emergency. + :param pad: Align to 32 bits + :param out_port: Require matching entries to include this as an + output port. A value of OFPP_NONE indicates + no restriction + + """ + match = flow_match.Match() + table_id = basic_types.UBInt8() + pad = basic_types.PAD(1) + out_port = basic_types.UBInt16() + + def __init__(self, match=None, table_id=None, out_port=None): + super().__init__() + self.match = match + self.table_id = table_id + self.out_port = out_port diff --git a/pyof/v0x01/controller2switch/common.py b/pyof/v0x01/controller2switch/common.py index bfb9cd3..c5490dd 100644 --- a/pyof/v0x01/controller2switch/common.py +++ b/pyof/v0x01/controller2switch/common.py @@ -8,7 +8,6 @@ import enum # Local source tree imports from pyof.v0x01.common import header as of_header from pyof.v0x01.common import action -from pyof.v0x01.common import flow_match from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types @@ -66,313 +65,3 @@ class ListOfActions(basic_types.FixedTypeList): """ def __init__(self, items=None): super().__init__(pyof_class=action.ActionHeader, items=items) - - -class AggregateStatsReply(base.GenericStruct): - """Body of reply to OFPST_AGGREGATE request. - - :param packet_count: Number of packets in flows - :param byte_count: Number of bytes in flows - :param flow_count: Number of flows - :param pad: Align to 64 bits - - """ - packet_count = basic_types.UBInt64() - byte_count = basic_types.UBInt64() - flow_count = basic_types.UBInt32() - pad = basic_types.PAD(4) - - def __init__(self, packet_count=None, byte_count=None, flow_count=None): - self.packet_count = packet_count - self.byte_count = byte_count - self.flow_count = flow_count - - -class AggregateStatsRequest(base.GenericStruct): - """ - Body for ofp_stats_request of type OFPST_AGGREGATE. - - :param match: Fields to match - :param table_id: ID of table to read (from pyof_table_stats) 0xff - for all tables or 0xfe for emergency. - :param pad: Align to 32 bits - :param out_port: Require matching entries to include this as an - output port. A value of OFPP_NONE indicates - no restriction - - """ - match = flow_match.Match() - table_id = basic_types.UBInt8() - pad = basic_types.PAD(1) - out_port = basic_types.UBInt16() - - def __init__(self, match=None, table_id=None, out_port=None): - super().__init__() - self.match = match - self.table_id = table_id - self.out_port = out_port - - -class DescStats(base.GenericStruct): - """ - Information about the switch manufacturer, hardware revision, software - revision, serial number, and a description field is avail- able from - the OFPST_DESC stats request. - - :param mfr_desc: Manufacturer description - :param hw_desc: Hardware description - :param sw_desc: Software description - :param serial_num: Serial number - :param dp_desc: Human readable description of datapath - - """ - mfr_desc = basic_types.Char(length=base.DESC_STR_LEN) - hw_desc = basic_types.Char(length=base.DESC_STR_LEN) - sw_desc = basic_types.Char(length=base.DESC_STR_LEN) - serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN) - dp_desc = basic_types.Char(length=base.DESC_STR_LEN) - - def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None, - serial_num=None, dp_desc=None): - self.mfr_desc = mfr_desc - self.hw_desc = hw_desc - self.sw_desc = sw_desc - self.serial_num = serial_num - self.dp_desc = dp_desc - - -class FlowStats(base.GenericStruct): - """ - Body of reply to OFPST_FLOW request. - - :param length: Length of this entry - :param table_id: ID of table flow came from - :param pad: Align to 32 bits - :param match: Description of fields - :param duration_sec: Time flow has been alive in seconds - :param duration_nsec: Time flow has been alive in nanoseconds beyond - duration_sec - :param priority: Priority of the entry. Only meaningful when this - is not an exact-match entry - :param idle_timeout: Number of seconds idle before expiration - :param hard_timeout: Number of seconds before expiration - :param pad2: Align to 64-bits - :param cookie: Opaque controller-issued identifier - :param packet_count: Number of packets in flow - :param byte_count: Number of bytes in flow - :param actions: Actions - """ - length = basic_types.UBInt16() - table_id = basic_types.UBInt8() - pad = basic_types.PAD(1) - match = flow_match.Match() - duration_sec = basic_types.UBInt32() - duration_nsec = basic_types.UBInt32() - priority = basic_types.UBInt16() - idle_timeout = basic_types.UBInt16() - hard_timeout = basic_types.UBInt16() - pad2 = basic_types.PAD(6) - cookie = basic_types.UBInt64() - packet_count = basic_types.UBInt64() - byte_count = basic_types.UBInt64() - actions = ListOfActions() - - def __init__(self, length=None, table_id=None, match=None, - duration_sec=None, duration_nsec=None, priority=None, - idle_timeout=None, hard_timeout=None, cookie=None, - packet_count=None, byte_count=None, actions=None): - self.length = length - self.table_id = table_id - self.match = match - self.duration_sec = duration_sec - self.duration_nsec = duration_nsec - self.prioriry = priority - self.idle_timeout = idle_timeout - self.hard_timeout = hard_timeout - self.cookie = cookie - self.packet_count = packet_count - self.byte_count = byte_count - self.actions = [] if actions is None else actions - - -class FlowStatsRequest(base.GenericStruct): - """ - Body for ofp_stats_request of type OFPST_FLOW. - - :param match: Fields to match - :param table_id: ID of table to read (from pyof_table_stats) - 0xff for all tables or 0xfe for emergency - :param pad: Align to 32 bits - :param out_port: Require matching entries to include this as an output - port. A value of OFPP_NONE indicates no restriction. - - """ - match = flow_match.Match() - table_id = basic_types.UBInt8() - pad = basic_types.PAD(1) - out_port = basic_types.UBInt16() - - def __init__(self, match=None, table_id=None, out_port=None): - self.match = match - self.table_id = table_id - self.out_port = out_port - - -class PortStats(base.GenericStruct): - """Body of reply to OFPST_PORT request. - - If a counter is unsupported, set the field to all ones. - - :param port_no: Port number - :param pad: Align to 64-bits - :param rx_packets: Number of received packets - :param tx_packets: Number of transmitted packets - :param rx_bytes: Number of received bytes - :param tx_bytes: Number of transmitted bytes - :param rx_dropped: Number of packets dropped by RX - :param tx_dropped: Number of packets dropped by TX - :param rx_errors: Number of receive errors. This is a super-set - of more specific receive errors and should be - greater than or equal to the sum of all - rx_*_err values - :param tx_errors: Number of transmit errors. This is a super-set - of more specific transmit errors and should be - greater than or equal to the sum of all - tx_*_err values (none currently defined.) - :param rx_frame_err: Number of frame alignment errors - :param rx_over_err: Number of packets with RX overrun - :param rx_crc_err: Number of CRC errors - :param collisions: Number of collisions - - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(6) - rx_packets = basic_types.UBInt64() - tx_packets = basic_types.UBInt64() - rx_bytes = basic_types.UBInt64() - tx_bytes = basic_types.UBInt64() - rx_dropped = basic_types.UBInt64() - tx_dropped = basic_types.UBInt64() - rx_errors = basic_types.UBInt64() - tx_errors = basic_types.UBInt64() - rx_frame_err = basic_types.UBInt64() - rx_over_err = basic_types.UBInt64() - rx_crc_err = basic_types.UBInt64() - collisions = basic_types.UBInt64() - - def __init__(self, port_no=None, rx_packets=None, - tx_packets=None, rx_bytes=None, tx_bytes=None, - rx_dropped=None, tx_dropped=None, rx_errors=None, - tx_errors=None, rx_frame_err=None, rx_over_err=None, - rx_crc_err=None, collisions=None): - self.port_no = port_no - self.rx_packets = rx_packets - self.tx_packets = tx_packets - self.rx_bytes = rx_bytes - self.tx_bytes = tx_bytes - self.rx_dropped = rx_dropped - self.tx_dropped = tx_dropped - self.rx_errors = rx_errors - self.tx_errors = tx_errors - self.rx_frame_err = rx_frame_err - self.rx_over_err = rx_over_err - self.rx_crc_err = rx_crc_err - self.collisions = collisions - - -class PortStatsRequest(base.GenericStruct): - """ - Body for ofp_stats_request of type OFPST_PORT - - :param port_no: OFPST_PORT message must request statistics either - for a single port (specified in port_no) or for - all ports (if port_no == OFPP_NONE). - :param pad: - - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(6) - - def __init__(self, port_no=None): - self.port_no = port_no - - -class QueueStats(base.GenericStruct): - """ - Implements the reply body of a port_no - - :param port_no: Port Number - :param pad: Align to 32-bits - :param queue_id: Queue ID - :param tx_bytes: Number of transmitted bytes - :param tx_packets: Number of transmitted packets - :param tx_errors: Number of packets dropped due to overrun - - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(2) - queue_id = basic_types.UBInt32() - tx_bytes = basic_types.UBInt64() - tx_packets = basic_types.UBInt64() - tx_errors = basic_types.UBInt64() - - def __init__(self, port_no=None, queue_id=None, tx_bytes=None, - tx_packets=None, tx_errors=None): - self.port_no = port_no - self.queue_id = queue_id - self.tx_bytes = tx_bytes - self.tx_packets = tx_packets - self.tx_errors = tx_errors - - -class QueueStatsRequest(base.GenericStruct): - """ - Implements the request body of a port_no - - :param port_no: All ports if OFPT_ALL - :param pad: Align to 32-bits - :param queue_id: All queues if OFPQ_ALL - """ - port_no = basic_types.UBInt16() - pad = basic_types.PAD(2) - queue_id = basic_types.UBInt32() - - def __init__(self, port_no=None, queue_id=None): - self.port_no = port_no - self.queue_id = queue_id - - -class TableStats(base.GenericStruct): - """Body of reply to OFPST_TABLE request. - - :param table_id: Identifier of table. Lower numbered tables - are consulted first - :param pad: Align to 32-bits - :param name: Table name - :param wildcards: Bitmap of OFPFW_* wildcards that are supported - by the table - :param max_entries: Max number of entries supported - :param active_count: Number of active entries - :param count_lookup: Number of packets looked up in table - :param count_matched: Number of packets that hit table - - """ - table_id = basic_types.UBInt8() - pad = basic_types.PAD(3) - name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN) - wildcards = basic_types.UBInt32() - max_entries = basic_types.UBInt32() - active_count = basic_types.UBInt32() - count_lookup = basic_types.UBInt64() - count_matched = basic_types.UBInt64() - - def __init__(self, table_id=None, name=None, wildcards=None, - max_entries=None, active_count=None, count_lookup=None, - count_matched=None): - self.table_id = table_id - self.name = name - self.wildcards = wildcards - self.max_entries = max_entries - self.active_count = active_count - self.count_lookup = count_lookup - self.count_matched = count_matched diff --git a/pyof/v0x01/controller2switch/desc_stats.py b/pyof/v0x01/controller2switch/desc_stats.py new file mode 100644 index 0000000..bceffb9 --- /dev/null +++ b/pyof/v0x01/controller2switch/desc_stats.py @@ -0,0 +1,39 @@ +"""Information about the switch manufactures""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + +# Classes + + +class DescStats(base.GenericStruct): + """ + Information about the switch manufacturer, hardware revision, software + revision, serial number, and a description field is avail- able from + the OFPST_DESC stats request. + + :param mfr_desc: Manufacturer description + :param hw_desc: Hardware description + :param sw_desc: Software description + :param serial_num: Serial number + :param dp_desc: Human readable description of datapath + + """ + mfr_desc = basic_types.Char(length=base.DESC_STR_LEN) + hw_desc = basic_types.Char(length=base.DESC_STR_LEN) + sw_desc = basic_types.Char(length=base.DESC_STR_LEN) + serial_num = basic_types.Char(length=base.SERIAL_NUM_LEN) + dp_desc = basic_types.Char(length=base.DESC_STR_LEN) + + def __init__(self, mfr_desc=None, hw_desc=None, sw_desc=None, + serial_num=None, dp_desc=None): + self.mfr_desc = mfr_desc + self.hw_desc = hw_desc + self.sw_desc = sw_desc + self.serial_num = serial_num + self.dp_desc = dp_desc diff --git a/pyof/v0x01/controller2switch/features_reply.py b/pyof/v0x01/controller2switch/features_reply.py index c5f3bca..e02f012 100644 --- a/pyof/v0x01/controller2switch/features_reply.py +++ b/pyof/v0x01/controller2switch/features_reply.py @@ -1,6 +1,7 @@ """Defines Features Reply classes and related items""" # System imports +import enum # Third-party imports @@ -11,9 +12,13 @@ from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types -class Capabilities(base.GenericBitMask): - """Capabilities supported by the datapath +# Enums + +class Capabilities(enum.Enum): + """Enumeration of Capabilities supported by the datapath + + Enums: OFPC_FLOW_STATS # Flow statistics OFPC_TABLE_STATS # Table statistics OFPC_PORT_STATS # Port statistics diff --git a/pyof/v0x01/controller2switch/flow_stats.py b/pyof/v0x01/controller2switch/flow_stats.py new file mode 100644 index 0000000..efb5edd --- /dev/null +++ b/pyof/v0x01/controller2switch/flow_stats.py @@ -0,0 +1,67 @@ +"""Body of the reply to an OFPST_FLOW""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.common import flow_match +from pyof.v0x01.controller2switch import common +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + +# Classes + + +class FlowStats(base.GenericStruct): + """ + Body of reply to OFPST_FLOW request. + + :param length: Length of this entry + :param table_id: ID of table flow came from + :param pad: Align to 32 bits + :param match: Description of fields + :param duration_sec: Time flow has been alive in seconds + :param duration_nsec: Time flow has been alive in nanoseconds beyond + duration_sec + :param priority: Priority of the entry. Only meaningful when this + is not an exact-match entry + :param idle_timeout: Number of seconds idle before expiration + :param hard_timeout: Number of seconds before expiration + :param pad2: Align to 64-bits + :param cookie: Opaque controller-issued identifier + :param packet_count: Number of packets in flow + :param byte_count: Number of bytes in flow + :param actions: Actions + """ + length = basic_types.UBInt16() + table_id = basic_types.UBInt8() + pad = basic_types.PAD(1) + match = flow_match.Match() + duration_sec = basic_types.UBInt32() + duration_nsec = basic_types.UBInt32() + priority = basic_types.UBInt16() + idle_timeout = basic_types.UBInt16() + hard_timeout = basic_types.UBInt16() + pad2 = basic_types.PAD(6) + cookie = basic_types.UBInt64() + packet_count = basic_types.UBInt64() + byte_count = basic_types.UBInt64() + actions = common.ListOfActions() + + def __init__(self, length=None, table_id=None, match=None, + duration_sec=None, duration_nsec=None, priority=None, + idle_timeout=None, hard_timeout=None, cookie=None, + packet_count=None, byte_count=None, actions=None): + self.length = length + self.table_id = table_id + self.match = match + self.duration_sec = duration_sec + self.duration_nsec = duration_nsec + self.prioriry = priority + self.idle_timeout = idle_timeout + self.hard_timeout = hard_timeout + self.cookie = cookie + self.packet_count = packet_count + self.byte_count = byte_count + self.actions = [] if actions is None else actions diff --git a/pyof/v0x01/controller2switch/flow_stats_request.py b/pyof/v0x01/controller2switch/flow_stats_request.py new file mode 100644 index 0000000..1fc5794 --- /dev/null +++ b/pyof/v0x01/controller2switch/flow_stats_request.py @@ -0,0 +1,35 @@ +"""Information about individual flows""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.common import flow_match +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + +# Classes + + +class FlowStatsRequest(base.GenericStruct): + """ + Body for ofp_stats_request of type OFPST_FLOW. + + :param match: Fields to match + :param table_id: ID of table to read (from pyof_table_stats) + 0xff for all tables or 0xfe for emergency + :param pad: Align to 32 bits + :param out_port: Require matching entries to include this as an output + port. A value of OFPP_NONE indicates no restriction. + + """ + match = flow_match.Match() + table_id = basic_types.UBInt8() + pad = basic_types.PAD(1) + out_port = basic_types.UBInt16() + + def __init__(self, match=None, table_id=None, out_port=None): + self.match = match + self.table_id = table_id + self.out_port = out_port diff --git a/pyof/v0x01/controller2switch/port_stats.py b/pyof/v0x01/controller2switch/port_stats.py new file mode 100644 index 0000000..474828d --- /dev/null +++ b/pyof/v0x01/controller2switch/port_stats.py @@ -0,0 +1,73 @@ +"""Body of the port stats reply""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + +# Classes + + +class PortStats(base.GenericStruct): + """Body of reply to OFPST_PORT request. + + If a counter is unsupported, set the field to all ones. + + :param port_no: Port number + :param pad: Align to 64-bits + :param rx_packets: Number of received packets + :param tx_packets: Number of transmitted packets + :param rx_bytes: Number of received bytes + :param tx_bytes: Number of transmitted bytes + :param rx_dropped: Number of packets dropped by RX + :param tx_dropped: Number of packets dropped by TX + :param rx_errors: Number of receive errors. This is a super-set + of more specific receive errors and should be + greater than or equal to the sum of all + rx_*_err values + :param tx_errors: Number of transmit errors. This is a super-set + of more specific transmit errors and should be + greater than or equal to the sum of all + tx_*_err values (none currently defined.) + :param rx_frame_err: Number of frame alignment errors + :param rx_over_err: Number of packets with RX overrun + :param rx_crc_err: Number of CRC errors + :param collisions: Number of collisions + + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(6) + rx_packets = basic_types.UBInt64() + tx_packets = basic_types.UBInt64() + rx_bytes = basic_types.UBInt64() + tx_bytes = basic_types.UBInt64() + rx_dropped = basic_types.UBInt64() + tx_dropped = basic_types.UBInt64() + rx_errors = basic_types.UBInt64() + tx_errors = basic_types.UBInt64() + rx_frame_err = basic_types.UBInt64() + rx_over_err = basic_types.UBInt64() + rx_crc_err = basic_types.UBInt64() + collisions = basic_types.UBInt64() + + def __init__(self, port_no=None, rx_packets=None, + tx_packets=None, rx_bytes=None, tx_bytes=None, + rx_dropped=None, tx_dropped=None, rx_errors=None, + tx_errors=None, rx_frame_err=None, rx_over_err=None, + rx_crc_err=None, collisions=None): + self.port_no = port_no + self.rx_packets = rx_packets + self.tx_packets = tx_packets + self.rx_bytes = rx_bytes + self.tx_bytes = tx_bytes + self.rx_dropped = rx_dropped + self.tx_dropped = tx_dropped + self.rx_errors = rx_errors + self.tx_errors = tx_errors + self.rx_frame_err = rx_frame_err + self.rx_over_err = rx_over_err + self.rx_crc_err = rx_crc_err + self.collisions = collisions diff --git a/pyof/v0x01/controller2switch/port_stats_request.py b/pyof/v0x01/controller2switch/port_stats_request.py new file mode 100644 index 0000000..8fa4049 --- /dev/null +++ b/pyof/v0x01/controller2switch/port_stats_request.py @@ -0,0 +1,26 @@ +"""Information about physical ports is requested with OFPST_PORT""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + + +class PortStatsRequest(base.GenericStruct): + """ + Body for ofp_stats_request of type OFPST_PORT + + :param port_no: OFPST_PORT message must request statistics either + for a single port (specified in port_no) or for + all ports (if port_no == OFPP_NONE). + :param pad: + + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(6) + + def __init__(self, port_no=None): + self.port_no = port_no diff --git a/pyof/v0x01/controller2switch/queue_stats.py b/pyof/v0x01/controller2switch/queue_stats.py new file mode 100644 index 0000000..d7df9b3 --- /dev/null +++ b/pyof/v0x01/controller2switch/queue_stats.py @@ -0,0 +1,38 @@ +"""The OFPST_QUEUE stats reply message provides queue statistics for one +or more ports.""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + + +class QueueStats(base.GenericStruct): + """ + Implements the reply body of a port_no + + :param port_no: Port Number + :param pad: Align to 32-bits + :param queue_id: Queue ID + :param tx_bytes: Number of transmitted bytes + :param tx_packets: Number of transmitted packets + :param tx_errors: Number of packets dropped due to overrun + + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(2) + queue_id = basic_types.UBInt32() + tx_bytes = basic_types.UBInt64() + tx_packets = basic_types.UBInt64() + tx_errors = basic_types.UBInt64() + + def __init__(self, port_no=None, queue_id=None, tx_bytes=None, + tx_packets=None, tx_errors=None): + self.port_no = port_no + self.queue_id = queue_id + self.tx_bytes = tx_bytes + self.tx_packets = tx_packets + self.tx_errors = tx_errors diff --git a/pyof/v0x01/controller2switch/queue_stats_request.py b/pyof/v0x01/controller2switch/queue_stats_request.py new file mode 100644 index 0000000..c1b431b --- /dev/null +++ b/pyof/v0x01/controller2switch/queue_stats_request.py @@ -0,0 +1,27 @@ +"""The OFPST_QUEUE stats request message provides queue statistics for one +or more ports.""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + + +class QueueStatsRequest(base.GenericStruct): + """ + Implements the request body of a port_no + + :param port_no: All ports if OFPT_ALL + :param pad: Align to 32-bits + :param queue_id: All queues if OFPQ_ALL + """ + port_no = basic_types.UBInt16() + pad = basic_types.PAD(2) + queue_id = basic_types.UBInt32() + + def __init__(self, port_no=None, queue_id=None): + self.port_no = port_no + self.queue_id = queue_id diff --git a/pyof/v0x01/controller2switch/table_stats.py b/pyof/v0x01/controller2switch/table_stats.py new file mode 100644 index 0000000..bf2e42f --- /dev/null +++ b/pyof/v0x01/controller2switch/table_stats.py @@ -0,0 +1,45 @@ +"""Information about tables is requested with OFPST_TABLE stats request type""" + +# System imports + +# Third-party imports + +# Local source tree imports +from pyof.v0x01.foundation import base +from pyof.v0x01.foundation import basic_types + + +class TableStats(base.GenericStruct): + """Body of reply to OFPST_TABLE request. + + :param table_id: Identifier of table. Lower numbered tables + are consulted first + :param pad: Align to 32-bits + :param name: Table name + :param wildcards: Bitmap of OFPFW_* wildcards that are supported + by the table + :param max_entries: Max number of entries supported + :param active_count: Number of active entries + :param count_lookup: Number of packets looked up in table + :param count_matched: Number of packets that hit table + + """ + table_id = basic_types.UBInt8() + pad = basic_types.PAD(3) + name = basic_types.Char(length=base.OFP_MAX_TABLE_NAME_LEN) + wildcards = basic_types.UBInt32() + max_entries = basic_types.UBInt32() + active_count = basic_types.UBInt32() + count_lookup = basic_types.UBInt64() + count_matched = basic_types.UBInt64() + + def __init__(self, table_id=None, name=None, wildcards=None, + max_entries=None, active_count=None, count_lookup=None, + count_matched=None): + self.table_id = table_id + self.name = name + self.wildcards = wildcards + self.max_entries = max_entries + self.active_count = active_count + self.count_lookup = count_lookup + self.count_matched = count_matched diff --git a/pyof/v0x01/foundation/base.py b/pyof/v0x01/foundation/base.py index 7c07b3e..a146a48 100644 --- a/pyof/v0x01/foundation/base.py +++ b/pyof/v0x01/foundation/base.py @@ -60,17 +60,16 @@ class GenericType(object): """This is a foundation class for all custom attributes. Attributes like `UBInt8`, `UBInt16`, `HWAddress` amoung others uses this - class as base. - """ + class as base.""" def __init__(self, value=None, enum_ref=None): self._value = value self._enum_ref = enum_ref def __repr__(self): - return "{}({})".format(self.__class__.__name__, self._value) + return "{}({})".format(type(self).__name__, self._value) def __str__(self): - return '<{}: {}>'.format(self.__class__.__name__, str(self._value)) + return '{}'.format(str(self._value)) def __eq__(self, other): return self._value == other @@ -105,7 +104,7 @@ class GenericType(object): return struct.pack(self._fmt, value) except struct.error as err: message = "Value out of the possible range to basic type " - message = message + self.__class__.__name__ + ". " + message = message + type(self).__name__ + ". " message = message + str(err) raise exceptions.BadValueException(message) @@ -154,7 +153,6 @@ class GenericType(object): class MetaStruct(type): """MetaClass used to force ordered attributes.""" - @classmethod def __prepare__(self, name, bases): return _OD() @@ -177,7 +175,6 @@ class GenericStruct(object, metaclass=MetaStruct): has a list of attributes and theses attributes can be of struct type too. """ - def __init__(self, *args, **kwargs): for _attr in self.__ordered__: if not callable(getattr(self, _attr)): @@ -186,29 +183,6 @@ class GenericStruct(object, metaclass=MetaStruct): except KeyError: pass - def __repr__(self): - message = self.__class__.__name__ - message += '(' - for _attr in self.__ordered__: - message += repr(getattr(self, _attr)) - message += ", " - # Removing a comma and a space from the end of the string - message = message[:-2] - message += ')' - return message - - def __str__(self): - message = "{}:\n".format(self.__class__.__name__) - for _attr in self.__ordered__: - attr = getattr(self, _attr) - if not hasattr(attr, '_fmt'): - message += " {}".format(str(attr).replace('\n', '\n ')) - else: - message += " {}: {}\n".format(_attr, str(attr)) - message.rstrip('\r') - message.rstrip('\n') - return message - def _attributes(self): """Returns a generator with each attribute from the current instance. @@ -282,7 +256,7 @@ class GenericStruct(object, metaclass=MetaStruct): if _class.__name__ is 'PAD': size += attr.get_size() elif _class.__name__ is 'Char': - size += getattr(self.__class__, _attr).get_size() + size += getattr(type(self), _attr).get_size() elif issubclass(_class, GenericType): size += _class().get_size() elif isinstance(attr, _class): @@ -302,13 +276,13 @@ class GenericStruct(object, metaclass=MetaStruct): """ if not self.is_valid(): error_msg = "Erro on validation prior to pack() on class " - error_msg += "{}.".format(self.__class__.__name__) + error_msg += "{}.".format(type(self).__name__) raise exceptions.ValidationError(error_msg) else: message = b'' for attr_name, attr_class in self.__ordered__.items(): attr = getattr(self, attr_name) - class_attr = getattr(self.__class__, attr_name) + class_attr = getattr(type(self), attr_name) if isinstance(attr, attr_class): message += attr.pack() elif class_attr.is_enum(): @@ -469,10 +443,10 @@ class GenericBitMask(object, metaclass=MetaBitMask): self.bitmask = bitmask def __str__(self): - return "<%s: %s>" % (self.__class__.__name__, self.names) + return "{}".format(self.bitmask) def __repr__(self): - return "<%s(%s)>" % (self.__class__.__name__, self.bitmask) + return "{}({})".format(type(self).__name__, self.bitmask) @property def names(self): diff --git a/pyof/v0x01/foundation/basic_types.py b/pyof/v0x01/foundation/basic_types.py index 417d7f1..ba26316 100644 --- a/pyof/v0x01/foundation/basic_types.py +++ b/pyof/v0x01/foundation/basic_types.py @@ -27,10 +27,10 @@ class PAD(base.GenericType): self._length = length def __repr__(self): - return "{}({})".format(self.__class__.__name__, self._length) + return "{}({})".format(type(self).__name__, self._length) def __str__(self): - return str(self._length) + return self.pack() def get_size(self): """ Return the size of type in bytes. """ @@ -131,7 +131,6 @@ class BinaryData(base.GenericType): Both the 'pack' and 'unpack' methods will return the binary data itself. get_size method will return the size of the instance using python 'len' """ - def __init__(self, value=b''): super().__init__(value) @@ -144,7 +143,7 @@ class BinaryData(base.GenericType): else: raise exceptions.NotBinarydata() - def unpack(self, buff): + def unpack(self, buff, offset): self._value = buff def get_size(self): @@ -163,18 +162,9 @@ class FixedTypeList(list, base.GenericStruct): elif items: self.append(items) - def __repr__(self): - """Unique representantion of the object. - - This can be used to generate an object that has the - same content of the current object""" - return "{}({},{})".format(self.__class__.__name__, - self._pyof_class, - self) - def __str__(self): """Human-readable object representantion""" - return "{}".format([item for item in self]) + return "{}".format([str(item) for item in self]) def append(self, item): if type(item) is list: @@ -243,17 +233,9 @@ class ConstantTypeList(list, base.GenericStruct): elif items: self.append(items) - def __repr__(self): - """Unique representantion of the object. - - This can be used to generate an object that has the - same content of the current object""" - return "{}({})".format(self.__class__.__name__, - self) - def __str__(self): """Human-readable object representantion""" - return "{}".format([item for item in self]) + return "{}".format([str(item) for item in self]) def append(self, item): if type(item) is list:
Review all __str__ and __repr__ methods We need to make sure that all `__str__` and `__repr__` are correct. For instance, look how strange is `common.phy_port.PhyPort`: ``` PhyPort(None, None, None, None, None) ```
kytos/python-openflow
diff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py index 1c699dd..3fc3326 100644 --- a/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py +++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch.common import AggregateStatsReply +from pyof.v0x01.controller2switch import aggregate_stats_reply class TestAggregateStatsReply(unittest.TestCase): def setUp(self): - self.message = AggregateStatsReply() + self.message = aggregate_stats_reply.AggregateStatsReply() self.message.packet_count = 5 self.message.byte_count = 1 self.message.flow_count = 8 diff --git a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py index 8e4be10..ca563fe 100644 --- a/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_aggregate_stats_request.py @@ -2,13 +2,13 @@ import unittest from pyof.v0x01.common import flow_match from pyof.v0x01.common import phy_port -from pyof.v0x01.controller2switch.common import AggregateStatsRequest +from pyof.v0x01.controller2switch import aggregate_stats_request class TestAggregateStatsRequest(unittest.TestCase): def setUp(self): - self.message = AggregateStatsRequest() + self.message = aggregate_stats_request.AggregateStatsRequest() self.message.match = flow_match.Match() self.message.table_id = 1 self.message.out_port = phy_port.Port.OFPP_NONE diff --git a/tests/v0x01/test_controller2switch/test_desc_stats.py b/tests/v0x01/test_controller2switch/test_desc_stats.py index 4f13f97..5ea6422 100644 --- a/tests/v0x01/test_controller2switch/test_desc_stats.py +++ b/tests/v0x01/test_controller2switch/test_desc_stats.py @@ -1,6 +1,6 @@ import unittest -from pyof.v0x01.controller2switch.common import DescStats +from pyof.v0x01.controller2switch import desc_stats from pyof.v0x01.foundation import base @@ -8,7 +8,7 @@ class TestDescStats(unittest.TestCase): def setUp(self): content = bytes('A' * base.DESC_STR_LEN, 'utf-8') - self.message = DescStats() + self.message = desc_stats.DescStats() self.message.mfr_desc = content self.message.hw_desc = content self.message.sw_desc = content diff --git a/tests/v0x01/test_controller2switch/test_flow_stats.py b/tests/v0x01/test_controller2switch/test_flow_stats.py index 2a04c07..1de34ab 100644 --- a/tests/v0x01/test_controller2switch/test_flow_stats.py +++ b/tests/v0x01/test_controller2switch/test_flow_stats.py @@ -1,13 +1,13 @@ import unittest from pyof.v0x01.common import flow_match -from pyof.v0x01.controller2switch.common import FlowStats +from pyof.v0x01.controller2switch import flow_stats class TestFlowStats(unittest.TestCase): def setUp(self): - self.message = FlowStats() + self.message = flow_stats.FlowStats() self.message.length = 160 self.message.table_id = 1 self.message.match = flow_match.Match() diff --git a/tests/v0x01/test_controller2switch/test_flow_stats_request.py b/tests/v0x01/test_controller2switch/test_flow_stats_request.py index 2a6f3fb..85a33bb 100644 --- a/tests/v0x01/test_controller2switch/test_flow_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_flow_stats_request.py @@ -1,13 +1,13 @@ import unittest from pyof.v0x01.common import flow_match -from pyof.v0x01.controller2switch.common import FlowStatsRequest +from pyof.v0x01.controller2switch import flow_stats_request class TestFlowStatsRequest(unittest.TestCase): def setUp(self): - self.message = FlowStatsRequest() + self.message = flow_stats_request.FlowStatsRequest() self.message.match = flow_match.Match() self.message.table_id = 1 self.message.out_port = 80 diff --git a/tests/v0x01/test_controller2switch/test_port_stats.py b/tests/v0x01/test_controller2switch/test_port_stats.py index e6f4b55..7a58485 100644 --- a/tests/v0x01/test_controller2switch/test_port_stats.py +++ b/tests/v0x01/test_controller2switch/test_port_stats.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch.common import PortStats +from pyof.v0x01.controller2switch import port_stats class TestPortStats(unittest.TestCase): def setUp(self): - self.message = PortStats() + self.message = port_stats.PortStats() self.message.port_no = 80 self.message.rx_packets = 5 self.message.tx_packets = 10 diff --git a/tests/v0x01/test_controller2switch/test_port_stats_request.py b/tests/v0x01/test_controller2switch/test_port_stats_request.py index 8025055..e0454dc 100644 --- a/tests/v0x01/test_controller2switch/test_port_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_port_stats_request.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch.common import PortStatsRequest +from pyof.v0x01.controller2switch import port_stats_request class TestPortStatsRequest(unittest.TestCase): def setUp(self): - self.message = PortStatsRequest() + self.message = port_stats_request.PortStatsRequest() self.message.port_no = 80 def test_get_size(self): diff --git a/tests/v0x01/test_controller2switch/test_queue_stats.py b/tests/v0x01/test_controller2switch/test_queue_stats.py index b1f1219..fb03ee7 100644 --- a/tests/v0x01/test_controller2switch/test_queue_stats.py +++ b/tests/v0x01/test_controller2switch/test_queue_stats.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch.common import QueueStats +from pyof.v0x01.controller2switch import queue_stats class TestQueueStats(unittest.TestCase): def setUp(self): - self.message = QueueStats() + self.message = queue_stats.QueueStats() self.message.port_no = 80 self.message.queue_id = 5 self.message.tx_bytes = 1 diff --git a/tests/v0x01/test_controller2switch/test_queue_stats_request.py b/tests/v0x01/test_controller2switch/test_queue_stats_request.py index 2f95381..80cad68 100644 --- a/tests/v0x01/test_controller2switch/test_queue_stats_request.py +++ b/tests/v0x01/test_controller2switch/test_queue_stats_request.py @@ -1,12 +1,12 @@ import unittest -from pyof.v0x01.controller2switch.common import QueueStatsRequest +from pyof.v0x01.controller2switch import queue_stats_request class TestQueueStatsRequest(unittest.TestCase): def setUp(self): - self.message = QueueStatsRequest() + self.message = queue_stats_request.QueueStatsRequest() self.message.port_no = 80 self.message.queue_id = 5 diff --git a/tests/v0x01/test_controller2switch/test_table_stats.py b/tests/v0x01/test_controller2switch/test_table_stats.py index 39888b5..353f6de 100644 --- a/tests/v0x01/test_controller2switch/test_table_stats.py +++ b/tests/v0x01/test_controller2switch/test_table_stats.py @@ -1,14 +1,14 @@ import unittest from pyof.v0x01.common import flow_match -from pyof.v0x01.controller2switch.common import TableStats +from pyof.v0x01.controller2switch import table_stats from pyof.v0x01.foundation import base class TestTableStats(unittest.TestCase): def setUp(self): - self.message = TableStats() + self.message = table_stats.TableStats() self.message.table_id = 1 self.message.name = bytes('X' * base.OFP_MAX_TABLE_NAME_LEN, 'utf-8') self.message.wildcards = flow_match.FlowWildCards.OFPFW_TP_DST
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 6 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "coverage", "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work execnet==2.1.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/kytos/python-openflow.git@545ae8a73dcec2e67cf854b21c44e692692f71dc#egg=Kytos_OpenFlow_Parser_library packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions==4.13.0
name: python-openflow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - execnet==2.1.1 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - typing-extensions==4.13.0 prefix: /opt/conda/envs/python-openflow
[ "tests/v0x01/test_controller2switch/test_aggregate_stats_reply.py::TestAggregateStatsReply::test_get_size", "tests/v0x01/test_controller2switch/test_aggregate_stats_request.py::TestAggregateStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_desc_stats.py::TestDescStats::test_get_size", "tests/v0x01/test_controller2switch/test_flow_stats.py::TestFlowStats::test_get_size", "tests/v0x01/test_controller2switch/test_flow_stats_request.py::TestFlowStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_port_stats.py::TestPortStats::test_get_size", "tests/v0x01/test_controller2switch/test_port_stats_request.py::TestPortStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_queue_stats.py::TestQueueStats::test_get_size", "tests/v0x01/test_controller2switch/test_queue_stats_request.py::TestQueueStatsRequest::test_get_size", "tests/v0x01/test_controller2switch/test_table_stats.py::TestTableStats::test_get_size" ]
[]
[]
[]
MIT License
577
falconry__falcon-820
50b1759ee7f7b54a872c01c85152f8648e350399
2016-06-07 21:07:32
67d61029847cbf59e4053c8a424df4f9f87ad36f
kgriffs: Looks like we accidentally had some overlap in effort between #729 and #811. I attempted to combine the two into a new PR with a few tweeks to param naming and docstrings. Everyone please take a look and provide feedback. Thanks! codecov-io: ## [Current coverage][cc-pull] is **100%** > Merging [#820][cc-pull] into [master][cc-base-branch] will not change coverage ```diff @@ master #820 diff @@ ========================================== Files 29 29 Lines 1789 1799 +10 Methods 0 0 Messages 0 0 Branches 299 303 +4 ========================================== + Hits 1789 1799 +10 Misses 0 0 Partials 0 0 ``` > Powered by [Codecov](https://codecov.io?src=pr). Last updated by [cf3cb50...d4e630a][cc-compare] [cc-base-branch]: https://codecov.io/gh/falconry/falcon/branch/master?src=pr [cc-compare]: https://codecov.io/gh/falconry/falcon/compare/cf3cb5029a51d4b7c980c7851328a02046db9b3e...d4e630a70cd1774519851a78a1d1fb80a83e8b7e [cc-pull]: https://codecov.io/gh/falconry/falcon/pull/820?src=pr orcsly: Looks good, thanks! jmvrbanac: :+1: qwesda: The parameter name `csv` for the `parse_query_string` could have a more descriptive name. `parse_qs_csv` sounds logical to me, since the option general option is called `auto_parse_qs_csv`. One evaluation in `parse_query_string` can be short-circuited: [https://github.com/falconry/falcon/pull/820/files#diff-7d2a078ae72702ba816f18a9aa1c48b9R319](https://github.com/falconry/falcon/pull/820/files#diff-7d2a078ae72702ba816f18a9aa1c48b9R319) Otherwise it looks good. kgriffs: @qwesda since the method name already implies we are working with parsing query strings, is it necessary to also include that in the name of the kwarg? qwesda: @kgriffs: I just thought something more explicit would be more in line with `keep_blank_qs_values`, which is pretty verbose. Having one verbose param and one very non-verbose seemed weird. kgriffs: @qwesda, ah, good point! I'll switch to `parse_qs_csv` and we can see how that looks. kgriffs: @qwesda @jmvrbanac @orcsly I think this is ready for final review. qwesda: @kgriffs looks ok orcsly: Yup looks good. Thanks!
diff --git a/falcon/request.py b/falcon/request.py index 597ac80..7359991 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -284,6 +284,7 @@ class Request(object): self._params = parse_query_string( self.query_string, keep_blank_qs_values=self.options.keep_blank_qs_values, + parse_qs_csv=self.options.auto_parse_qs_csv, ) else: @@ -1153,6 +1154,7 @@ class Request(object): extra_params = parse_query_string( body, keep_blank_qs_values=self.options.keep_blank_qs_values, + parse_qs_csv=self.options.auto_parse_qs_csv, ) self._params.update(extra_params) @@ -1190,8 +1192,11 @@ class RequestOptions(object): """This class is a container for ``Request`` options. Attributes: - keep_blank_qs_values (bool): Set to ``True`` in order to retain - blank values in query string parameters (default ``False``). + keep_blank_qs_values (bool): Set to ``True`` to keep query string + fields even if they do not have a value (default ``False``). + For comma-separated values, this option also determines + whether or not empty elements in the parsed list are + retained. auto_parse_form_urlencoded: Set to ``True`` in order to automatically consume the request stream and merge the results into the request's query string params when the @@ -1202,18 +1207,29 @@ class RequestOptions(object): Note: The character encoding for fields, before percent-encoding non-ASCII bytes, is assumed to be - UTF-8. The special `_charset_` field is ignored if present. + UTF-8. The special `_charset_` field is ignored if + present. Falcon expects form-encoded request bodies to be encoded according to the standard W3C algorithm (see also http://goo.gl/6rlcux). + auto_parse_qs_csv: Set to ``False`` to treat commas in a query + string value as literal characters, rather than as a comma- + separated list (default ``True``). When this option is + enabled, the value will be split on any non-percent-encoded + commas. Disable this option when encoding lists as multiple + occurrences of the same parameter, and when values may be + encoded in alternative formats in which the comma character + is significant. """ __slots__ = ( 'keep_blank_qs_values', 'auto_parse_form_urlencoded', + 'auto_parse_qs_csv', ) def __init__(self): self.keep_blank_qs_values = False self.auto_parse_form_urlencoded = False + self.auto_parse_qs_csv = True diff --git a/falcon/util/misc.py b/falcon/util/misc.py index 5b02f05..12eb481 100644 --- a/falcon/util/misc.py +++ b/falcon/util/misc.py @@ -148,7 +148,7 @@ def http_date_to_dt(http_date, obs_date=False): raise ValueError('time data %r does not match known formats' % http_date) -def to_query_str(params): +def to_query_str(params, comma_delimited_lists=True): """Converts a dictionary of params to a query string. Args: @@ -157,6 +157,10 @@ def to_query_str(params): something that can be converted into a ``str``. If `params` is a ``list``, it will be converted to a comma-delimited string of values (e.g., 'thing=1,2,3') + comma_delimited_lists (bool, default ``True``): + If set to ``False`` encode lists by specifying multiple instances + of the parameter (e.g., 'thing=1&thing=2&thing=3') + Returns: str: A URI query string including the '?' prefix, or an empty string @@ -175,7 +179,20 @@ def to_query_str(params): elif v is False: v = 'false' elif isinstance(v, list): - v = ','.join(map(str, v)) + if comma_delimited_lists: + v = ','.join(map(str, v)) + else: + for list_value in v: + if list_value is True: + list_value = 'true' + elif list_value is False: + list_value = 'false' + else: + list_value = str(list_value) + + query_str += k + '=' + list_value + '&' + + continue else: v = str(v) diff --git a/falcon/util/uri.py b/falcon/util/uri.py index 2f68ec9..63ca45e 100644 --- a/falcon/util/uri.py +++ b/falcon/util/uri.py @@ -246,11 +246,12 @@ else: return decoded_uri.decode('utf-8', 'replace') -def parse_query_string(query_string, keep_blank_qs_values=False): +def parse_query_string(query_string, keep_blank_qs_values=False, + parse_qs_csv=True): """Parse a query string into a dict. Query string parameters are assumed to use standard form-encoding. Only - parameters with values are parsed. for example, given 'foo=bar&flag', + parameters with values are returned. For example, given 'foo=bar&flag', this function would ignore 'flag' unless the `keep_blank_qs_values` option is set. @@ -269,8 +270,16 @@ def parse_query_string(query_string, keep_blank_qs_values=False): Args: query_string (str): The query string to parse. - keep_blank_qs_values (bool): If set to ``True``, preserves boolean - fields and fields with no content as blank strings. + keep_blank_qs_values (bool): Set to ``True`` to return fields even if + they do not have a value (default ``False``). For comma-separated + values, this option also determines whether or not empty elements + in the parsed list are retained. + parse_qs_csv: Set to ``False`` in order to disable splitting query + parameters on ``,`` (default ``True``). Depending on the user agent, + encoding lists as multiple occurrences of the same parameter might + be preferable. In this case, setting `parse_qs_csv` to ``False`` + will cause the framework to treat commas as literal characters in + each occurring parameter value. Returns: dict: A dictionary of (*name*, *value*) pairs, one per query @@ -309,7 +318,7 @@ def parse_query_string(query_string, keep_blank_qs_values=False): params[k] = [old_value, decode(v)] else: - if ',' in v: + if parse_qs_csv and ',' in v: # NOTE(kgriffs): Falcon supports a more compact form of # lists, in which the elements are comma-separated and # assigned to a single param instance. If it turns out that
Add option to opt-out from comma separated value parsing I'm porting a project to Falcon and I stumbled upon an issue regarding its parsing of CSV values inside URIs. Let's say I have filtering engine that accepts queries such as this: http://great.dude/api/cars?query=added:yesterday,today+spoilers:red I obviously want to make `req.get_param('query')` return `'added:yesterday,today spoilers:red'`, and not `['added:yesterday', 'today spoilers:red']`. Right now this [isn't really configurable](https://github.com/falconry/falcon/blob/35987b2be85456f431bbda509e884a8b0b20ed11/falcon/util/uri.py#L312-L328) and I need to check if `get_param()` returns a `list` and then join it back if needed, which looks sort of silly. Fortunately, the ability to use custom request classes alleviates the issue to some extent. I see a few ways to improve things upstream: 1. Offer explicit `get_param_as_string` that will possibly do `','.join(...)` under the hood. 2. Add an option to disable this mechanism as an additional option to `Api`. 3. Add an option to disable this mechanism as an additional option to `add_route()`. 4. Change `get_param` to always return string. Option 4 makes the most sense to me, but it breaks BC. If option 4 is not feasible, I'd went with option 1.
falconry/falcon
diff --git a/tests/test_options.py b/tests/test_options.py index b3d9812..a3b8b72 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -1,16 +1,32 @@ +import ddt + from falcon.request import RequestOptions import falcon.testing as testing [email protected] class TestRequestOptions(testing.TestBase): - def test_correct_options(self): + def test_option_defaults(self): options = RequestOptions() + self.assertFalse(options.keep_blank_qs_values) - options.keep_blank_qs_values = True - self.assertTrue(options.keep_blank_qs_values) - options.keep_blank_qs_values = False - self.assertFalse(options.keep_blank_qs_values) + self.assertFalse(options.auto_parse_form_urlencoded) + self.assertTrue(options.auto_parse_qs_csv) + + @ddt.data( + 'keep_blank_qs_values', + 'auto_parse_form_urlencoded', + 'auto_parse_qs_csv', + ) + def test_options_toggle(self, option_name): + options = RequestOptions() + + setattr(options, option_name, True) + self.assertTrue(getattr(options, option_name)) + + setattr(options, option_name, False) + self.assertFalse(getattr(options, option_name)) def test_incorrect_options(self): options = RequestOptions() diff --git a/tests/test_query_params.py b/tests/test_query_params.py index c588f23..62c906d 100644 --- a/tests/test_query_params.py +++ b/tests/test_query_params.py @@ -65,6 +65,60 @@ class _TestQueryParams(testing.TestBase): self.assertEqual(req.get_param_as_list('id', int), [23, 42]) self.assertEqual(req.get_param('q'), u'\u8c46 \u74e3') + def test_option_auto_parse_qs_csv_simple_false(self): + self.api.req_options.auto_parse_qs_csv = False + + query_string = 'id=23,42,,&id=2' + self.simulate_request('/', query_string=query_string) + + req = self.resource.req + + self.assertEqual(req.params['id'], [u'23,42,,', u'2']) + self.assertIn(req.get_param('id'), [u'23,42,,', u'2']) + self.assertEqual(req.get_param_as_list('id'), [u'23,42,,', u'2']) + + def test_option_auto_parse_qs_csv_simple_true(self): + self.api.req_options.auto_parse_qs_csv = True + + query_string = 'id=23,42,,&id=2' + self.simulate_request('/', query_string=query_string) + + req = self.resource.req + + self.assertEqual(req.params['id'], [u'23', u'42', u'2']) + self.assertIn(req.get_param('id'), [u'23', u'42', u'2']) + self.assertEqual(req.get_param_as_list('id', int), [23, 42, 2]) + + def test_option_auto_parse_qs_csv_complex_false(self): + self.api.req_options.auto_parse_qs_csv = False + + encoded_json = '%7B%22msg%22:%22Testing%201,2,3...%22,%22code%22:857%7D' + decoded_json = '{"msg":"Testing 1,2,3...","code":857}' + + query_string = ('colors=red,green,blue&limit=1' + '&list-ish1=f,,x&list-ish2=,0&list-ish3=a,,,b' + '&empty1=&empty2=,&empty3=,,' + '&thing=' + encoded_json) + + self.simulate_request('/', query_string=query_string) + + req = self.resource.req + + self.assertIn(req.get_param('colors'), 'red,green,blue') + self.assertEqual(req.get_param_as_list('colors'), [u'red,green,blue']) + + self.assertEqual(req.get_param_as_list('limit'), ['1']) + + self.assertEqual(req.get_param_as_list('empty1'), None) + self.assertEqual(req.get_param_as_list('empty2'), [u',']) + self.assertEqual(req.get_param_as_list('empty3'), [u',,']) + + self.assertEqual(req.get_param_as_list('list-ish1'), [u'f,,x']) + self.assertEqual(req.get_param_as_list('list-ish2'), [u',0']) + self.assertEqual(req.get_param_as_list('list-ish3'), [u'a,,,b']) + + self.assertEqual(req.get_param('thing'), decoded_json) + def test_bad_percentage(self): query_string = 'x=%%20%+%&y=peregrine&z=%a%z%zz%1%20e' self.simulate_request('/', query_string=query_string) diff --git a/tests/test_utils.py b/tests/test_utils.py index 957a959..6b5f75d 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -128,6 +128,16 @@ class TestFalconUtils(testtools.TestCase): falcon.to_query_str({'things': ['a', 'b']}), '?things=a,b') + expected = ('?things=a&things=b&things=&things=None' + '&things=true&things=false&things=0') + + actual = falcon.to_query_str( + {'things': ['a', 'b', '', None, True, False, 0]}, + comma_delimited_lists=False + ) + + self.assertEqual(actual, expected) + def test_pack_query_params_several(self): garbage_in = { 'limit': 17,
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 3 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "ddt", "testtools", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "tools/test-requires" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 ddt==1.7.2 -e git+https://github.com/falconry/falcon.git@50b1759ee7f7b54a872c01c85152f8648e350399#egg=falcon fixtures==4.0.1 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 nose==1.3.7 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-mimeparse==1.6.0 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 testtools==2.6.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - ddt==1.7.2 - fixtures==4.0.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-mimeparse==1.6.0 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - testtools==2.6.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/falcon
[ "tests/test_options.py::TestRequestOptions::test_option_defaults", "tests/test_options.py::TestRequestOptions::test_options_toggle_3_auto_parse_qs_csv", "tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_complex_false", "tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_simple_false", "tests/test_query_params.py::_TestQueryParams::test_option_auto_parse_qs_csv_simple_true", "tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_complex_false", "tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_simple_false", "tests/test_query_params.py::PostQueryParams::test_option_auto_parse_qs_csv_simple_true", "tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_complex_false", "tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_simple_false", "tests/test_query_params.py::GetQueryParams::test_option_auto_parse_qs_csv_simple_true", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_one" ]
[ "tests/test_utils.py::TestFalconUtils::test_deprecated_decorator" ]
[ "tests/test_options.py::TestRequestOptions::test_incorrect_options", "tests/test_options.py::TestRequestOptions::test_options_toggle_1_keep_blank_qs_values", "tests/test_options.py::TestRequestOptions::test_options_toggle_2_auto_parse_form_urlencoded", "tests/test_query_params.py::_TestQueryParams::test_allowed_names", "tests/test_query_params.py::_TestQueryParams::test_bad_percentage", "tests/test_query_params.py::_TestQueryParams::test_blank", "tests/test_query_params.py::_TestQueryParams::test_boolean", "tests/test_query_params.py::_TestQueryParams::test_boolean_blank", "tests/test_query_params.py::_TestQueryParams::test_get_date_invalid", "tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param", "tests/test_query_params.py::_TestQueryParams::test_get_date_store", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::_TestQueryParams::test_get_dict_invalid", "tests/test_query_params.py::_TestQueryParams::test_get_dict_missing_param", "tests/test_query_params.py::_TestQueryParams::test_get_dict_store", "tests/test_query_params.py::_TestQueryParams::test_get_dict_valid", "tests/test_query_params.py::_TestQueryParams::test_int", "tests/test_query_params.py::_TestQueryParams::test_int_neg", "tests/test_query_params.py::_TestQueryParams::test_list_transformer", "tests/test_query_params.py::_TestQueryParams::test_list_type", "tests/test_query_params.py::_TestQueryParams::test_list_type_blank", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::_TestQueryParams::test_none", "tests/test_query_params.py::_TestQueryParams::test_param_property", "tests/test_query_params.py::_TestQueryParams::test_percent_encoded", "tests/test_query_params.py::_TestQueryParams::test_required_1_get_param", "tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::_TestQueryParams::test_simple", "tests/test_query_params.py::PostQueryParams::test_allowed_names", "tests/test_query_params.py::PostQueryParams::test_bad_percentage", "tests/test_query_params.py::PostQueryParams::test_blank", "tests/test_query_params.py::PostQueryParams::test_boolean", "tests/test_query_params.py::PostQueryParams::test_boolean_blank", "tests/test_query_params.py::PostQueryParams::test_explicitly_disable_auto_parse", "tests/test_query_params.py::PostQueryParams::test_get_date_invalid", "tests/test_query_params.py::PostQueryParams::test_get_date_missing_param", "tests/test_query_params.py::PostQueryParams::test_get_date_store", "tests/test_query_params.py::PostQueryParams::test_get_date_valid", "tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::PostQueryParams::test_get_dict_invalid", "tests/test_query_params.py::PostQueryParams::test_get_dict_missing_param", "tests/test_query_params.py::PostQueryParams::test_get_dict_store", "tests/test_query_params.py::PostQueryParams::test_get_dict_valid", "tests/test_query_params.py::PostQueryParams::test_int", "tests/test_query_params.py::PostQueryParams::test_int_neg", "tests/test_query_params.py::PostQueryParams::test_list_transformer", "tests/test_query_params.py::PostQueryParams::test_list_type", "tests/test_query_params.py::PostQueryParams::test_list_type_blank", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::PostQueryParams::test_non_ascii", "tests/test_query_params.py::PostQueryParams::test_none", "tests/test_query_params.py::PostQueryParams::test_param_property", "tests/test_query_params.py::PostQueryParams::test_percent_encoded", "tests/test_query_params.py::PostQueryParams::test_required_1_get_param", "tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::PostQueryParams::test_simple", "tests/test_query_params.py::GetQueryParams::test_allowed_names", "tests/test_query_params.py::GetQueryParams::test_bad_percentage", "tests/test_query_params.py::GetQueryParams::test_blank", "tests/test_query_params.py::GetQueryParams::test_boolean", "tests/test_query_params.py::GetQueryParams::test_boolean_blank", "tests/test_query_params.py::GetQueryParams::test_get_date_invalid", "tests/test_query_params.py::GetQueryParams::test_get_date_missing_param", "tests/test_query_params.py::GetQueryParams::test_get_date_store", "tests/test_query_params.py::GetQueryParams::test_get_date_valid", "tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::GetQueryParams::test_get_dict_invalid", "tests/test_query_params.py::GetQueryParams::test_get_dict_missing_param", "tests/test_query_params.py::GetQueryParams::test_get_dict_store", "tests/test_query_params.py::GetQueryParams::test_get_dict_valid", "tests/test_query_params.py::GetQueryParams::test_int", "tests/test_query_params.py::GetQueryParams::test_int_neg", "tests/test_query_params.py::GetQueryParams::test_list_transformer", "tests/test_query_params.py::GetQueryParams::test_list_type", "tests/test_query_params.py::GetQueryParams::test_list_type_blank", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::GetQueryParams::test_none", "tests/test_query_params.py::GetQueryParams::test_param_property", "tests/test_query_params.py::GetQueryParams::test_percent_encoded", "tests/test_query_params.py::GetQueryParams::test_required_1_get_param", "tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::GetQueryParams::test_simple", "tests/test_query_params.py::PostQueryParamsDefaultBehavior::test_dont_auto_parse_by_default", "tests/test_utils.py::TestFalconUtils::test_dt_to_http", "tests/test_utils.py::TestFalconUtils::test_get_http_status", "tests/test_utils.py::TestFalconUtils::test_http_date_to_dt", "tests/test_utils.py::TestFalconUtils::test_http_now", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_none", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_several", "tests/test_utils.py::TestFalconUtils::test_parse_host", "tests/test_utils.py::TestFalconUtils::test_parse_query_string", "tests/test_utils.py::TestFalconUtils::test_prop_uri_decode_models_stdlib_unquote_plus", "tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_models_stdlib_quote", "tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_value_models_stdlib_quote_safe_tilde", "tests/test_utils.py::TestFalconUtils::test_uri_decode", "tests/test_utils.py::TestFalconUtils::test_uri_encode", "tests/test_utils.py::TestFalconUtils::test_uri_encode_value", "tests/test_utils.py::TestFalconTesting::test_decode_empty_result", "tests/test_utils.py::TestFalconTesting::test_httpnow_alias_for_backwards_compat", "tests/test_utils.py::TestFalconTesting::test_none_header_value_in_create_environ", "tests/test_utils.py::TestFalconTesting::test_path_escape_chars_in_create_environ", "tests/test_utils.py::TestFalconTestCase::test_cached_text_in_result", "tests/test_utils.py::TestFalconTestCase::test_path_must_start_with_slash", "tests/test_utils.py::TestFalconTestCase::test_query_string", "tests/test_utils.py::TestFalconTestCase::test_query_string_in_path", "tests/test_utils.py::TestFalconTestCase::test_query_string_no_question", "tests/test_utils.py::TestFalconTestCase::test_simple_resource_body_json_xor", "tests/test_utils.py::TestFalconTestCase::test_status", "tests/test_utils.py::TestFalconTestCase::test_wsgi_iterable_not_closeable", "tests/test_utils.py::FancyTestCase::test_something" ]
[]
Apache License 2.0
578
scrapy__scrapy-2038
b7925e42202d79d2ba9d00b6aded3a451c92fe81
2016-06-08 14:57:23
a975a50558cd78a1573bee2e957afcb419fd1bd6
diff --git a/scrapy/utils/url.py b/scrapy/utils/url.py index c80fc6e70..406eb5843 100644 --- a/scrapy/utils/url.py +++ b/scrapy/utils/url.py @@ -41,9 +41,16 @@ def url_has_any_extension(url, extensions): def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'): + # IDNA encoding can fail for too long labels (>63 characters) + # or missing labels (e.g. http://.example.com) + try: + netloc = parts.netloc.encode('idna') + except UnicodeError: + netloc = parts.netloc + return ( to_native_str(parts.scheme), - to_native_str(parts.netloc.encode('idna')), + to_native_str(netloc), # default encoding for path component SHOULD be UTF-8 quote(to_bytes(parts.path, path_encoding), _safe_chars),
Unicode Link Extractor When using the following to extract all of the links from a response: ``` self.link_extractor = LinkExtractor() ... links = self.link_extractor.extract_links(response) ``` On rare occasions, the following error is thrown: ``` 2016-05-25 12:13:55,432 [root] [ERROR] Error on http://detroit.curbed.com/2016/5/5/11605132/tiny-house-designer-show, traceback: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/twisted/internet/base.py", line 1203, in mainLoop self.runUntilCurrent() File "/usr/local/lib/python2.7/site-packages/twisted/internet/base.py", line 825, in runUntilCurrent call.func(*call.args, **call.kw) File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 393, in callback self._startRunCallbacks(result) File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 501, in _startRunCallbacks self._runCallbacks() --- <exception caught here> --- File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/var/www/html/DomainCrawler/DomainCrawler/spiders/hybrid_spider.py", line 223, in parse items.extend(self._extract_requests(response)) File "/var/www/html/DomainCrawler/DomainCrawler/spiders/hybrid_spider.py", line 477, in _extract_requests links = self.link_extractor.extract_links(response) File "/usr/local/lib/python2.7/site-packages/scrapy/linkextractors/lxmlhtml.py", line 111, in extract_links all_links.extend(self._process_links(links)) File "/usr/local/lib/python2.7/site-packages/scrapy/linkextractors/__init__.py", line 103, in _process_links link.url = canonicalize_url(urlparse(link.url)) File "/usr/local/lib/python2.7/site-packages/scrapy/utils/url.py", line 85, in canonicalize_url parse_url(url), encoding=encoding) File "/usr/local/lib/python2.7/site-packages/scrapy/utils/url.py", line 46, in _safe_ParseResult to_native_str(parts.netloc.encode('idna')), File "/usr/local/lib/python2.7/encodings/idna.py", line 164, in encode result.append(ToASCII(label)) File "/usr/local/lib/python2.7/encodings/idna.py", line 73, in ToASCII raise UnicodeError("label empty or too long") exceptions.UnicodeError: label empty or too long ``` I was able to find some information concerning the error from [here](http://stackoverflow.com/questions/25103126/label-empty-or-too-long-python-urllib2). My question is: What is the best way to handle this? Even if there is one bad link in the response, I'd want all of the other good links to be extracted.
scrapy/scrapy
diff --git a/tests/test_utils_url.py b/tests/test_utils_url.py index 1fc3a3510..b4819874d 100644 --- a/tests/test_utils_url.py +++ b/tests/test_utils_url.py @@ -265,6 +265,20 @@ class CanonicalizeUrlTest(unittest.TestCase): # without encoding, already canonicalized URL is canonicalized identically self.assertEqual(canonicalize_url(canonicalized), canonicalized) + def test_canonicalize_url_idna_exceptions(self): + # missing DNS label + self.assertEqual( + canonicalize_url(u"http://.example.com/résumé?q=résumé"), + "http://.example.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9") + + # DNS label too long + self.assertEqual( + canonicalize_url( + u"http://www.{label}.com/résumé?q=résumé".format( + label=u"example"*11)), + "http://www.{label}.com/r%C3%A9sum%C3%A9?q=r%C3%A9sum%C3%A9".format( + label=u"example"*11)) + class AddHttpIfNoScheme(unittest.TestCase):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev" ], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 Automat==22.10.0 certifi==2021.5.30 cffi==1.15.1 constantly==15.1.0 cryptography==40.0.2 cssselect==1.1.0 hyperlink==21.0.0 idna==3.10 importlib-metadata==4.8.3 incremental==22.10.0 iniconfig==1.1.1 lxml==5.3.1 packaging==21.3 parsel==1.6.0 pluggy==1.0.0 py==1.11.0 pyasn1==0.5.1 pyasn1-modules==0.3.0 pycparser==2.21 PyDispatcher==2.0.7 pyOpenSSL==23.2.0 pyparsing==3.1.4 pytest==7.0.1 queuelib==1.6.2 -e git+https://github.com/scrapy/scrapy.git@b7925e42202d79d2ba9d00b6aded3a451c92fe81#egg=Scrapy service-identity==21.1.0 six==1.17.0 tomli==1.2.3 Twisted==22.4.0 typing_extensions==4.1.1 w3lib==2.0.1 zipp==3.6.0 zope.interface==5.5.2
name: scrapy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - automat==22.10.0 - cffi==1.15.1 - constantly==15.1.0 - cryptography==40.0.2 - cssselect==1.1.0 - hyperlink==21.0.0 - idna==3.10 - importlib-metadata==4.8.3 - incremental==22.10.0 - iniconfig==1.1.1 - lxml==5.3.1 - packaging==21.3 - parsel==1.6.0 - pluggy==1.0.0 - py==1.11.0 - pyasn1==0.5.1 - pyasn1-modules==0.3.0 - pycparser==2.21 - pydispatcher==2.0.7 - pyopenssl==23.2.0 - pyparsing==3.1.4 - pytest==7.0.1 - queuelib==1.6.2 - service-identity==21.1.0 - six==1.17.0 - tomli==1.2.3 - twisted==22.4.0 - typing-extensions==4.1.1 - w3lib==2.0.1 - zipp==3.6.0 - zope-interface==5.5.2 prefix: /opt/conda/envs/scrapy
[ "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idna_exceptions" ]
[]
[ "tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_any_domain", "tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider", "tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_class_attributes", "tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains", "tests/test_utils_url.py::UrlUtilsTest::test_url_is_from_spider_with_allowed_domains_class_attributes", "tests/test_utils_url.py::CanonicalizeUrlTest::test_append_missing_path", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_idns", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_parse_url", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_idempotence", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_path", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_url_unicode_query_string_wrong_encoding", "tests/test_utils_url.py::CanonicalizeUrlTest::test_canonicalize_urlparsed", "tests/test_utils_url.py::CanonicalizeUrlTest::test_domains_are_case_insensitive", "tests/test_utils_url.py::CanonicalizeUrlTest::test_dont_convert_safe_characters", "tests/test_utils_url.py::CanonicalizeUrlTest::test_keep_blank_values", "tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_paths", "tests/test_utils_url.py::CanonicalizeUrlTest::test_non_ascii_percent_encoding_in_query_arguments", "tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_paths", "tests/test_utils_url.py::CanonicalizeUrlTest::test_normalize_percent_encoding_in_query_arguments", "tests/test_utils_url.py::CanonicalizeUrlTest::test_quoted_slash_and_question_sign", "tests/test_utils_url.py::CanonicalizeUrlTest::test_remove_fragments", "tests/test_utils_url.py::CanonicalizeUrlTest::test_return_str", "tests/test_utils_url.py::CanonicalizeUrlTest::test_safe_characters_unicode", "tests/test_utils_url.py::CanonicalizeUrlTest::test_sorting", "tests/test_utils_url.py::CanonicalizeUrlTest::test_spaces", "tests/test_utils_url.py::CanonicalizeUrlTest::test_typical_usage", "tests/test_utils_url.py::CanonicalizeUrlTest::test_urls_with_auth_and_ports", "tests/test_utils_url.py::AddHttpIfNoScheme::test_add_scheme", "tests/test_utils_url.py::AddHttpIfNoScheme::test_complete_url", "tests/test_utils_url.py::AddHttpIfNoScheme::test_fragment", "tests/test_utils_url.py::AddHttpIfNoScheme::test_path", "tests/test_utils_url.py::AddHttpIfNoScheme::test_port", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_ftp", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_complete_url", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_fragment", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_path", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_port", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_query", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_username_password", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_http_without_subdomain", "tests/test_utils_url.py::AddHttpIfNoScheme::test_preserve_https", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_complete_url", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_fragment", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_path", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_port", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_query", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_username_password", "tests/test_utils_url.py::AddHttpIfNoScheme::test_protocol_relative_without_subdomain", "tests/test_utils_url.py::AddHttpIfNoScheme::test_query", "tests/test_utils_url.py::AddHttpIfNoScheme::test_username_password", "tests/test_utils_url.py::AddHttpIfNoScheme::test_without_subdomain", "tests/test_utils_url.py::GuessSchemeTest::test_uri_001", "tests/test_utils_url.py::GuessSchemeTest::test_uri_002", "tests/test_utils_url.py::GuessSchemeTest::test_uri_003", "tests/test_utils_url.py::GuessSchemeTest::test_uri_004", "tests/test_utils_url.py::GuessSchemeTest::test_uri_005", "tests/test_utils_url.py::GuessSchemeTest::test_uri_006", "tests/test_utils_url.py::GuessSchemeTest::test_uri_007", "tests/test_utils_url.py::GuessSchemeTest::test_uri_008", "tests/test_utils_url.py::GuessSchemeTest::test_uri_009", "tests/test_utils_url.py::GuessSchemeTest::test_uri_010", "tests/test_utils_url.py::GuessSchemeTest::test_uri_011", "tests/test_utils_url.py::GuessSchemeTest::test_uri_012", "tests/test_utils_url.py::GuessSchemeTest::test_uri_013", "tests/test_utils_url.py::GuessSchemeTest::test_uri_014", "tests/test_utils_url.py::GuessSchemeTest::test_uri_015", "tests/test_utils_url.py::GuessSchemeTest::test_uri_016", "tests/test_utils_url.py::GuessSchemeTest::test_uri_017", "tests/test_utils_url.py::GuessSchemeTest::test_uri_018", "tests/test_utils_url.py::GuessSchemeTest::test_uri_019", "tests/test_utils_url.py::GuessSchemeTest::test_uri_020" ]
[]
BSD 3-Clause "New" or "Revised" License
579
mapbox__mapbox-sdk-py-128
2c11fdee6eee83ea82398cc0756ac7f35aada801
2016-06-09 18:19:51
2c11fdee6eee83ea82398cc0756ac7f35aada801
diff --git a/docs/surface.md b/docs/surface.md index 8fcbb77..c6e9676 100644 --- a/docs/surface.md +++ b/docs/surface.md @@ -86,7 +86,7 @@ contours). ... polyline=True, zoom=12, interpolate=False) >>> points = response.geojson() >>> [f['properties']['ele'] for f in points['features']] -[None, None, None] +[2190, 2190, 2160] ``` diff --git a/mapbox/encoding.py b/mapbox/encoding.py index 0674d51..6190ea6 100644 --- a/mapbox/encoding.py +++ b/mapbox/encoding.py @@ -68,12 +68,13 @@ def encode_waypoints(features, min_limit=None, max_limit=None, precision=6): return ';'.join(coords) -def encode_polyline(features, zoom_level=18): +def encode_polyline(features): """Encode and iterable of features as a polyline """ points = list(read_points(features)) + latlon_points = [(x[1], x[0]) for x in points] codec = PolylineCodec() - return codec.encode(points) + return codec.encode(latlon_points) def encode_coordinates_json(features):
Encoded polylines in wrong coordinate order Currently, we take the geojson point array and encode the point directly in [lon, lat] order. Polylines should be [lat, lon].
mapbox/mapbox-sdk-py
diff --git a/tests/test_encoding.py b/tests/test_encoding.py index fa15f14..9326ae6 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -113,7 +113,7 @@ def test_unknown_object(): def test_encode_polyline(): - expected = "vdatOwp_~EhupD{xiA" + expected = "wp_~EvdatO{xiAhupD" assert expected == encode_polyline(gj_point_features) assert expected == encode_polyline(gj_multipoint_features) assert expected == encode_polyline(gj_line_features) diff --git a/tests/test_surface.py b/tests/test_surface.py index 05bd2c7..2ba08cd 100644 --- a/tests/test_surface.py +++ b/tests/test_surface.py @@ -55,7 +55,7 @@ def test_surface_geojson(): @responses.activate def test_surface_params(): - params = "&encoded_polyline=~kbkTss%60%7BEQeAHu%40&zoom=16&interpolate=false" + params = "&encoded_polyline=ss%60%7BE~kbkTeAQu%40H&zoom=16&interpolate=false" responses.add( responses.GET, 'https://api.mapbox.com/v4/surface/mapbox.mapbox-terrain-v1.json?access_token=pk.test&fields=ele&layer=contour&geojson=true' + params,
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 2 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "pip install -U pip" ], "python": "3.5", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 boto3==1.23.10 botocore==1.26.10 CacheControl==0.12.14 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 click-plugins==1.1.1 cligj==0.7.2 coverage==6.2 coveralls==3.3.1 distlib==0.3.9 docopt==0.6.2 filelock==3.4.1 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 iso3166==2.1.1 jmespath==0.10.0 -e git+https://github.com/mapbox/mapbox-sdk-py.git@2c11fdee6eee83ea82398cc0756ac7f35aada801#egg=mapbox msgpack==1.0.5 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 requests==2.27.1 responses==0.17.0 s3transfer==0.5.2 six==1.17.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 uritemplate==4.1.1 uritemplate.py==3.0.2 urllib3==1.26.20 virtualenv==20.17.1 zipp==3.6.0
name: mapbox-sdk-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - boto3==1.23.10 - botocore==1.26.10 - cachecontrol==0.12.14 - charset-normalizer==2.0.12 - click==8.0.4 - click-plugins==1.1.1 - cligj==0.7.2 - coverage==6.2 - coveralls==3.3.1 - distlib==0.3.9 - docopt==0.6.2 - filelock==3.4.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - iso3166==2.1.1 - jmespath==0.10.0 - msgpack==1.0.5 - packaging==21.3 - pip==21.3.1 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - requests==2.27.1 - responses==0.17.0 - s3transfer==0.5.2 - six==1.17.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - uritemplate==4.1.1 - uritemplate-py==3.0.2 - urllib3==1.26.20 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/mapbox-sdk-py
[ "tests/test_encoding.py::test_encode_polyline", "tests/test_surface.py::test_surface_params" ]
[]
[ "tests/test_encoding.py::test_read_geojson_features", "tests/test_encoding.py::test_geo_interface", "tests/test_encoding.py::test_encode_waypoints", "tests/test_encoding.py::test_encode_limits", "tests/test_encoding.py::test_unsupported_geometry", "tests/test_encoding.py::test_unknown_object", "tests/test_encoding.py::test_encode_coordinates_json", "tests/test_surface.py::test_surface", "tests/test_surface.py::test_surface_geojson" ]
[]
MIT License
580
bigchaindb__cryptoconditions-15
c3156a947ca32e8d1d9c5f7ec8fa0a049f2ba0a6
2016-06-10 12:14:28
c3156a947ca32e8d1d9c5f7ec8fa0a049f2ba0a6
diff --git a/README.md b/README.md index 4387e6e..6c963c8 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ generic authenticated event handlers. ## Usage ```python +import json import binascii import cryptoconditions as cc @@ -64,7 +65,7 @@ parsed_fulfillment = cc.Fulfillment.from_uri(example_fulfillment_uri) print(isinstance(parsed_fulfillment, cc.PreimageSha256Fulfillment)) # prints True -# Retrieve the condition of the fulfillment +# Retrieve the condition of the fulfillment print(parsed_fulfillment.condition_uri) # prints 'cc:0:3:47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU:0' @@ -72,14 +73,13 @@ print(parsed_fulfillment.condition_uri) parsed_fulfillment.validate() # prints True -# Export to JSON -json_data = parsed_fulfillment.serialize_json() +# Serialize fulfillment to JSON +json_data = json.dumps(parsed_fulfillment.to_dict()) print(json_data) # prints '{"bitmask": 3, "type_id": 0, "type": "fulfillment", "preimage": ""}' # Parse fulfillment from JSON -import json -json_fulfillment = cc.Fulfillment.from_json(json.loads(json_data)) +json_fulfillment = cc.Fulfillment.from_dict(json.loads(json_data)) print(json_fulfillment.serialize_uri()) # prints 'cf:0:' ``` @@ -270,6 +270,7 @@ FULFILLMENT_PAYLOAD = ### Usage ```python +import json import cryptoconditions as cc # Parse some fulfillments @@ -315,7 +316,7 @@ threshold_fulfillment.threshold = 3 # AND gate print(threshold_fulfillment.serialize_uri()) # prints 'cf:2:AQMBAwEBAwAAAAABAWMABGDsFyuTrV5WO_STLHDhJFA0w1Rn7y79TWTr-BloNGfiv7YikfrZQy-PKYucSkiV2-KT9v_aGmja3wzN719HoMchKl_qPNqXo_TAPqny6Kwc7IalHUUhJ6vboJ0bbzMcBwoAAQGBmgACgZYBAQECAQEAJwAEASAg7Bcrk61eVjv0kyxw4SRQNMNUZ-8u_U1k6_gZaDRn4r8BYAEBYwAEYOwXK5OtXlY79JMscOEkUDTDVGfvLv1NZOv4GWg0Z-K_tiKR-tlDL48pi5xKSJXb4pP2_9oaaNrfDM3vX0egxyEqX-o82pej9MA-qfLorBzshqUdRSEnq9ugnRtvMxwHCgAA' -threshold_fulfillment.serialize_json() +threshold_fulfillment.to_dict() ``` ```python @@ -416,4 +417,4 @@ timeout_fulfillment valid: False (0s to timeout) timeout_fulfillment valid: False (-1s to timeout) timeout_fulfillment valid: False (-2s to timeout) timeout_fulfillment valid: False (-3s to timeout) -``` \ No newline at end of file +``` diff --git a/cryptoconditions/condition.py b/cryptoconditions/condition.py index 4ae9d75..d00427a 100644 --- a/cryptoconditions/condition.py +++ b/cryptoconditions/condition.py @@ -1,4 +1,3 @@ -import json import base58 import base64 import re @@ -117,18 +116,18 @@ class Condition(metaclass=ABCMeta): return condition @staticmethod - def from_json(json_data): + def from_dict(data): """ - Create a Condition object from a json dict. + Create a Condition object from a dict. Args: - json_data (dict): Dictionary containing the condition payload + data (dict): Dictionary containing the condition payload Returns: Condition: Resulting object """ condition = Condition() - condition.parse_json(json_data) + condition.parse_dict(data) return condition @@ -262,30 +261,34 @@ class Condition(metaclass=ABCMeta): self.hash = reader.read_var_octet_string() self.max_fulfillment_length = reader.read_var_uint() - def serialize_json(self): - return json.dumps( - { - 'type': 'condition', - 'type_id': self.type_id, - 'bitmask': self.bitmask, - 'hash': base58.b58encode(self.hash), - 'max_fulfillment_length': self.max_fulfillment_length - } - ) + def to_dict(self): + """ + Generate a dict of the condition - def parse_json(self, json_data): + Returns: + dict: representing the condition + """ + return { + 'type': 'condition', + 'type_id': self.type_id, + 'bitmask': self.bitmask, + 'hash': base58.b58encode(self.hash), + 'max_fulfillment_length': self.max_fulfillment_length + } + + def parse_dict(self, data): """ Args: - json_data (dict): + data (dict): Returns: Condition with payload """ - self.type_id = json_data['type_id'] - self.bitmask = json_data['bitmask'] + self.type_id = data['type_id'] + self.bitmask = data['bitmask'] - self.hash = base58.b58decode(json_data['hash']) - self.max_fulfillment_length = json_data['max_fulfillment_length'] + self.hash = base58.b58decode(data['hash']) + self.max_fulfillment_length = data['max_fulfillment_length'] def validate(self): """ diff --git a/cryptoconditions/fulfillment.py b/cryptoconditions/fulfillment.py index c07a281..f78e5af 100644 --- a/cryptoconditions/fulfillment.py +++ b/cryptoconditions/fulfillment.py @@ -78,12 +78,12 @@ class Fulfillment(metaclass=ABCMeta): return fulfillment @staticmethod - def from_json(json_data): - cls_type = json_data['type_id'] + def from_dict(data): + cls_type = data['type_id'] cls = TypeRegistry.get_class_from_type_id(cls_type) fulfillment = cls() - fulfillment.parse_json(json_data) + fulfillment.parse_dict(data) return fulfillment @@ -249,20 +249,20 @@ class Fulfillment(metaclass=ABCMeta): """ @abstractmethod - def serialize_json(self): + def to_dict(self): """ - Generate a JSON object of the fulfillment + Generate a dict of the fulfillment Returns: """ @abstractmethod - def parse_json(self, json_data): + def parse_dict(self, data): """ - Generate fulfillment payload from a json + Generate fulfillment payload from a dict Args: - json_data: json description of the fulfillment + data: dict description of the fulfillment Returns: Fulfillment diff --git a/cryptoconditions/types/ed25519.py b/cryptoconditions/types/ed25519.py index fb8fd32..ddcf8fa 100644 --- a/cryptoconditions/types/ed25519.py +++ b/cryptoconditions/types/ed25519.py @@ -1,5 +1,3 @@ -import json - import base58 from cryptoconditions.crypto import Ed25519VerifyingKey as VerifyingKey @@ -113,34 +111,33 @@ class Ed25519Fulfillment(Fulfillment): def calculate_max_fulfillment_length(self): return Ed25519Fulfillment.FULFILLMENT_LENGTH - def serialize_json(self): + def to_dict(self): """ - Generate a JSON object of the fulfillment + Generate a dict of the fulfillment Returns: + dict: representing the fulfillment """ - return json.dumps( - { - 'type': 'fulfillment', - 'type_id': self.TYPE_ID, - 'bitmask': self.bitmask, - 'public_key': self.public_key.to_ascii(encoding='base58').decode(), - 'signature': base58.b58encode(self.signature) if self.signature else None - } - ) + return { + 'type': 'fulfillment', + 'type_id': self.TYPE_ID, + 'bitmask': self.bitmask, + 'public_key': self.public_key.to_ascii(encoding='base58').decode(), + 'signature': base58.b58encode(self.signature) if self.signature else None + } - def parse_json(self, json_data): + def parse_dict(self, data): """ - Generate fulfillment payload from a json + Generate fulfillment payload from a dict Args: - json_data: json description of the fulfillment + data (dict): description of the fulfillment Returns: Fulfillment """ - self.public_key = VerifyingKey(json_data['public_key']) - self.signature = base58.b58decode(json_data['signature']) if json_data['signature'] else None + self.public_key = VerifyingKey(data['public_key']) + self.signature = base58.b58decode(data['signature']) if data['signature'] else None def validate(self, message=None, **kwargs): """ diff --git a/cryptoconditions/types/sha256.py b/cryptoconditions/types/sha256.py index daa2e00..f36e96a 100644 --- a/cryptoconditions/types/sha256.py +++ b/cryptoconditions/types/sha256.py @@ -1,5 +1,3 @@ -import json - from cryptoconditions.types.base_sha256 import BaseSha256Fulfillment from cryptoconditions.lib import Hasher, Reader, Writer, Predictor @@ -93,32 +91,31 @@ class PreimageSha256Fulfillment(BaseSha256Fulfillment): writer.write(self.preimage) return writer - def serialize_json(self): + def to_dict(self): """ - Generate a JSON object of the fulfillment + Generate a dict of the fulfillment Returns: + dict: representing the fulfillment """ - return json.dumps( - { - 'type': 'fulfillment', - 'type_id': self.TYPE_ID, - 'bitmask': self.bitmask, - 'preimage': self.preimage.decode() - } - ) - - def parse_json(self, json_data): + return { + 'type': 'fulfillment', + 'type_id': self.TYPE_ID, + 'bitmask': self.bitmask, + 'preimage': self.preimage.decode() + } + + def parse_dict(self, data): """ - Generate fulfillment payload from a json + Generate fulfillment payload from a dict Args: - json_data: json description of the fulfillment + data (dict): description of the fulfillment Returns: Fulfillment """ - self.preimage = json_data['preimage'].encode() + self.preimage = data['preimage'].encode() def validate(self, *args, **kwargs): """ diff --git a/cryptoconditions/types/threshold_sha256.py b/cryptoconditions/types/threshold_sha256.py index 068e9b2..aae4e02 100644 --- a/cryptoconditions/types/threshold_sha256.py +++ b/cryptoconditions/types/threshold_sha256.py @@ -1,5 +1,3 @@ -import json - import copy from cryptoconditions.condition import Condition from cryptoconditions.fulfillment import Fulfillment @@ -109,6 +107,7 @@ class ThresholdSha256Fulfillment(BaseSha256Fulfillment): elif not isinstance(subfulfillment, Fulfillment): raise TypeError('Subfulfillments must be URIs or objects of type Fulfillment') if not isinstance(weight, int) or weight < 1: + # TODO: Add a more helpful error message. raise ValueError('Invalid weight: {}'.format(weight)) self.subconditions.append( { @@ -277,7 +276,7 @@ class ThresholdSha256Fulfillment(BaseSha256Fulfillment): predictor = Predictor() predictor.write_uint16(None) # type - predictor.write_var_octet_string(b'0'*fulfillment_len) # payload + predictor.write_var_octet_string(b'0' * fulfillment_len) # payload return predictor.size @@ -486,49 +485,48 @@ class ThresholdSha256Fulfillment(BaseSha256Fulfillment): buffers_copy.sort(key=lambda item: (len(item), item)) return buffers_copy - def serialize_json(self): + def to_dict(self): """ - Generate a JSON object of the fulfillment + Generate a dict of the fulfillment Returns: + dict: representing the fulfillment """ - subfulfillments_json = [] + subfulfillments = [] for c in self.subconditions: - subcondition = json.loads(c['body'].serialize_json()) + subcondition = c['body'].to_dict() subcondition.update({'weight': c['weight']}) - subfulfillments_json.append(subcondition) + subfulfillments.append(subcondition) - return json.dumps( - { - 'type': 'fulfillment', - 'type_id': self.TYPE_ID, - 'bitmask': self.bitmask, - 'threshold': self.threshold, - 'subfulfillments': subfulfillments_json - } - ) + return { + 'type': 'fulfillment', + 'type_id': self.TYPE_ID, + 'bitmask': self.bitmask, + 'threshold': self.threshold, + 'subfulfillments': subfulfillments + } - def parse_json(self, json_data): + def parse_dict(self, data): """ - Generate fulfillment payload from a json + Generate fulfillment payload from a dict Args: - json_data: json description of the fulfillment + data (dict): description of the fulfillment Returns: Fulfillment """ - if not isinstance(json_data, dict): + if not isinstance(data, dict): raise TypeError('reader must be a dict instance') - self.threshold = json_data['threshold'] + self.threshold = data['threshold'] - for subfulfillments_json in json_data['subfulfillments']: - weight = subfulfillments_json['weight'] + for subfulfillments in data['subfulfillments']: + weight = subfulfillments['weight'] - if subfulfillments_json['type'] == FULFILLMENT: - self.add_subfulfillment(Fulfillment.from_json(subfulfillments_json), weight) - elif subfulfillments_json['type'] == CONDITION: - self.add_subcondition(Condition.from_json(subfulfillments_json), weight) + if subfulfillments['type'] == FULFILLMENT: + self.add_subfulfillment(Fulfillment.from_dict(subfulfillments), weight) + elif subfulfillments['type'] == CONDITION: + self.add_subcondition(Condition.from_dict(subfulfillments), weight) else: raise TypeError('Subconditions must provide either subcondition or fulfillment.') diff --git a/cryptoconditions/types/timeout.py b/cryptoconditions/types/timeout.py index 6b9d2fc..0007c6f 100644 --- a/cryptoconditions/types/timeout.py +++ b/cryptoconditions/types/timeout.py @@ -1,4 +1,3 @@ -import json import re import time @@ -32,32 +31,31 @@ class TimeoutFulfillment(PreimageSha256Fulfillment): """ return self.preimage - def serialize_json(self): + def to_dict(self): """ - Generate a JSON object of the fulfillment + Generate a dict of the fulfillment Returns: + dict: representing the fulfillment """ - return json.dumps( - { - 'type': 'fulfillment', - 'type_id': self.TYPE_ID, - 'bitmask': self.bitmask, - 'expire_time': self.expire_time.decode() - } - ) - - def parse_json(self, json_data): + return { + 'type': 'fulfillment', + 'type_id': self.TYPE_ID, + 'bitmask': self.bitmask, + 'expire_time': self.expire_time.decode() + } + + def parse_dict(self, data): """ - Generate fulfillment payload from a json + Generate fulfillment payload from a dict Args: - json_data: json description of the fulfillment + data (dict): description of the fulfillment Returns: Fulfillment """ - self.preimage = json_data['expire_time'].encode() + self.preimage = data['expire_time'].encode() def validate(self, message=None, now=None, **kwargs): """ diff --git a/setup.py b/setup.py index c467ce2..d4da1b4 100644 --- a/setup.py +++ b/setup.py @@ -69,8 +69,7 @@ setup( tests_require=tests_require, extras_require={ 'test': tests_require, - 'dev': dev_require + tests_require + docs_require, - 'docs': docs_require, + 'dev': dev_require + tests_require + docs_require, + 'docs': docs_require, }, ) -
Remove json serialization from cryptoconditions Just provide functions for serialization to dicts. Users should be able to serialize from there on to dicts themselves.
bigchaindb/cryptoconditions
diff --git a/tests/test_fulfillment.py b/tests/test_fulfillment.py index 225c85c..10d75dc 100644 --- a/tests/test_fulfillment.py +++ b/tests/test_fulfillment.py @@ -1,5 +1,4 @@ import binascii -import json from time import sleep from math import ceil @@ -45,20 +44,13 @@ class TestSha256Fulfillment: assert fulfillment.condition.serialize_uri() == fulfillment_sha256['condition_uri'] assert fulfillment.validate() - def test_serialize_json(self, fulfillment_sha256): + def test_fulfillment_serialize_to_dict(self, fulfillment_sha256): fulfillment = Fulfillment.from_uri(fulfillment_sha256['fulfillment_uri']) - - assert json.loads(fulfillment.serialize_json()) == \ - {'bitmask': 3, 'preimage': '', 'type': 'fulfillment', 'type_id': 0} - - def test_deserialize_json(self, fulfillment_sha256): - fulfillment = Fulfillment.from_uri(fulfillment_sha256['fulfillment_uri']) - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri() assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri() - assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json() + assert parsed_fulfillment.to_dict() == fulfillment.to_dict() def test_deserialize_condition_and_validate_fulfillment(self, fulfillment_sha256): condition = Condition.from_uri(fulfillment_sha256['condition_uri']) @@ -123,10 +115,10 @@ class TestEd25519Sha256Fulfillment: assert deserialized_condition.serialize_uri() == fulfillment_ed25519['condition_uri'] assert binascii.hexlify(deserialized_condition.hash) == fulfillment_ed25519['condition_hash'] - def test_serialize_json_signed(self, fulfillment_ed25519): + def test_serialize_signed_dict_to_fulfillment(self, fulfillment_ed25519): fulfillment = Fulfillment.from_uri(fulfillment_ed25519['fulfillment_uri']) - assert json.loads(fulfillment.serialize_json()) == \ + assert fulfillment.to_dict()== \ {'bitmask': 32, 'public_key': 'Gtbi6WQDB6wUePiZm8aYs5XZ5pUqx9jMMLvRVHPESTjU', 'signature': '4eCt6SFPCzLQSAoQGW7CTu3MHdLj6FezSpjktE7tHsYGJ4pNSUnpHtV9XgdHF2XYd62M9fTJ4WYdhTVck27qNoHj', @@ -135,10 +127,10 @@ class TestEd25519Sha256Fulfillment: assert fulfillment.validate(MESSAGE) == True - def test_serialize_json_unsigned(self, vk_ilp): + def test_serialize_unsigned_dict_to_fulfillment(self, vk_ilp): fulfillment = Ed25519Fulfillment(public_key=vk_ilp['b58']) - assert json.loads(fulfillment.serialize_json()) == \ + assert fulfillment.to_dict() == \ {'bitmask': 32, 'public_key': 'Gtbi6WQDB6wUePiZm8aYs5XZ5pUqx9jMMLvRVHPESTjU', 'signature': None, @@ -146,23 +138,20 @@ class TestEd25519Sha256Fulfillment: 'type_id': 4} assert fulfillment.validate(MESSAGE) == False - def test_deserialize_json_signed(self, fulfillment_ed25519): + def test_deserialize_signed_dict_to_fulfillment(self, fulfillment_ed25519): fulfillment = Fulfillment.from_uri(fulfillment_ed25519['fulfillment_uri']) - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.serialize_uri() == fulfillment_ed25519['fulfillment_uri'] assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri() - assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json() + assert parsed_fulfillment.to_dict() == fulfillment.to_dict() - def test_deserialize_json_unsigned(self, vk_ilp): + def test_deserialize_unsigned_dict_to_fulfillment(self, vk_ilp): fulfillment = Ed25519Fulfillment(public_key=vk_ilp['b58']) - - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri() - assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json() + assert parsed_fulfillment.to_dict() == fulfillment.to_dict() def test_serialize_deserialize_condition(self, vk_ilp): vk = VerifyingKey(vk_ilp['b58']) @@ -262,10 +251,10 @@ class TestThresholdSha256Fulfillment: assert len(fulfillment.subconditions) == num_fulfillments assert fulfillment.validate(MESSAGE) - def test_serialize_json_signed(self, fulfillment_threshold): + def test_serialize_signed_dict_to_fulfillment(self, fulfillment_threshold): fulfillment = Fulfillment.from_uri(fulfillment_threshold['fulfillment_uri']) - assert json.loads(fulfillment.serialize_json()) == \ + assert fulfillment.to_dict() == \ {'bitmask': 43, 'subfulfillments': [{'bitmask': 3, 'preimage': '', @@ -282,12 +271,12 @@ class TestThresholdSha256Fulfillment: 'type': 'fulfillment', 'type_id': 2} - def test_serialize_json_unsigned(self, vk_ilp): + def test_serialize_unsigned_dict_to_fulfillment(self, vk_ilp): fulfillment = ThresholdSha256Fulfillment(threshold=1) fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58']))) fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58']))) - assert json.loads(fulfillment.serialize_json()) == \ + assert fulfillment.to_dict() == \ {'bitmask': 41, 'subfulfillments': [{'bitmask': 32, 'public_key': 'Gtbi6WQDB6wUePiZm8aYs5XZ5pUqx9jMMLvRVHPESTjU', @@ -305,50 +294,45 @@ class TestThresholdSha256Fulfillment: 'type': 'fulfillment', 'type_id': 2} - def test_deserialize_json_signed(self, fulfillment_threshold): + def test_deserialize_signed_dict_to_fulfillment(self, fulfillment_threshold): fulfillment = Fulfillment.from_uri(fulfillment_threshold['fulfillment_uri']) - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.serialize_uri() == fulfillment_threshold['fulfillment_uri'] assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri() - assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json() + assert parsed_fulfillment.to_dict() == fulfillment.to_dict() - def test_deserialize_json_unsigned(self, vk_ilp): + def test_deserialize_unsigned_dict_to_fulfillment(self, vk_ilp): fulfillment = ThresholdSha256Fulfillment(threshold=1) fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58']))) fulfillment.add_subfulfillment(Ed25519Fulfillment(public_key=VerifyingKey(vk_ilp['b58']))) - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.condition.serialize_uri() == fulfillment.condition.serialize_uri() - assert parsed_fulfillment.serialize_json() == fulfillment.serialize_json() + assert parsed_fulfillment.to_dict() == fulfillment.to_dict() def test_weights(self, fulfillment_ed25519): ilp_fulfillment = Fulfillment.from_uri(fulfillment_ed25519['fulfillment_uri']) fulfillment1 = ThresholdSha256Fulfillment(threshold=2) fulfillment1.add_subfulfillment(ilp_fulfillment, weight=2) - fulfillment_json = json.loads(fulfillment1.serialize_json()) - parsed_fulfillment1 = fulfillment1.from_json(fulfillment_json) + parsed_fulfillment1 = fulfillment1.from_dict(fulfillment1.to_dict()) assert parsed_fulfillment1.condition.serialize_uri() == fulfillment1.condition.serialize_uri() - assert parsed_fulfillment1.serialize_json() == fulfillment1.serialize_json() + assert parsed_fulfillment1.to_dict() == fulfillment1.to_dict() assert parsed_fulfillment1.subconditions[0]['weight'] == 2 assert parsed_fulfillment1.validate(MESSAGE) is True fulfillment2 = ThresholdSha256Fulfillment(threshold=3) fulfillment2.add_subfulfillment(ilp_fulfillment, weight=2) - fulfillment_json = json.loads(fulfillment2.serialize_json()) - parsed_fulfillment2 = fulfillment1.from_json(fulfillment_json) + parsed_fulfillment2 = fulfillment1.from_dict(fulfillment2.to_dict()) assert parsed_fulfillment2.subconditions[0]['weight'] == 2 assert parsed_fulfillment2.validate(MESSAGE) is False fulfillment3 = ThresholdSha256Fulfillment(threshold=3) fulfillment3.add_subfulfillment(ilp_fulfillment, weight=3) - fulfillment_json = json.loads(fulfillment3.serialize_json()) - parsed_fulfillment3 = fulfillment1.from_json(fulfillment_json) + parsed_fulfillment3 = fulfillment1.from_dict(fulfillment3.to_dict()) assert parsed_fulfillment3.condition.serialize_uri() == fulfillment3.condition.serialize_uri() assert not (fulfillment3.condition.serialize_uri() == fulfillment1.condition.serialize_uri()) @@ -506,8 +490,7 @@ class TestInvertedThresholdSha256Fulfillment: fulfillment = InvertedThresholdSha256Fulfillment(threshold=1) fulfillment.add_subfulfillment(ilp_fulfillment_ed) - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.condition_uri == fulfillment.condition_uri assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri() @@ -521,16 +504,14 @@ class TestTimeoutFulfillment: def test_serialize_condition_and_validate_fulfillment(self): fulfillment = TimeoutFulfillment(expire_time=timestamp()) - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.condition_uri == fulfillment.condition_uri assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri() assert parsed_fulfillment.validate(now=timestamp()) is False - fulfillment = TimeoutFulfillment(expire_time=str(float(timestamp())+1000)) - fulfillment_json = json.loads(fulfillment.serialize_json()) - parsed_fulfillment = fulfillment.from_json(fulfillment_json) + fulfillment = TimeoutFulfillment(expire_time=str(float(timestamp()) + 1000)) + parsed_fulfillment = fulfillment.from_dict(fulfillment.to_dict()) assert parsed_fulfillment.condition_uri == fulfillment.condition_uri assert parsed_fulfillment.serialize_uri() == fulfillment.serialize_uri() @@ -573,8 +554,7 @@ class TestEscrow: fulfillment_escrow.add_subfulfillment(fulfillment_and_execute) fulfillment_escrow.add_subfulfillment(fulfillment_and_abort) - fulfillment_json = json.loads(fulfillment_escrow.serialize_json()) - parsed_fulfillment = fulfillment_escrow.from_json(fulfillment_json) + parsed_fulfillment = fulfillment_escrow.from_dict(fulfillment_escrow.to_dict()) assert parsed_fulfillment.condition_uri == fulfillment_escrow.condition_uri assert parsed_fulfillment.serialize_uri() == fulfillment_escrow.serialize_uri()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 8 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.5", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 astroid==2.11.7 attrs==22.2.0 Babel==2.11.0 backcall==0.2.0 base58==0.2.2 certifi==2021.5.30 charset-normalizer==2.0.12 commonmark==0.9.1 coverage==6.2 -e git+https://github.com/bigchaindb/cryptoconditions.git@c3156a947ca32e8d1d9c5f7ec8fa0a049f2ba0a6#egg=cryptoconditions decorator==5.1.1 dill==0.3.4 docutils==0.18.1 ed25519==1.5 execnet==1.9.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 ipdb==0.13.13 ipython==7.16.3 ipython-genutils==0.2.0 isort==5.10.1 jedi==0.17.2 Jinja2==3.0.3 lazy-object-proxy==1.7.1 MarkupSafe==2.0.1 mccabe==0.7.0 packaging==21.3 parso==0.7.1 pep8==1.7.1 pexpect==4.9.0 pickleshare==0.7.5 platformdirs==2.4.0 pluggy==1.0.0 pockets==0.9.1 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pyflakes==3.0.1 Pygments==2.14.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-xdist==3.0.2 pytz==2025.2 recommonmark==0.7.1 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-napoleon==0.7 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 traitlets==4.3.3 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 wcwidth==0.2.13 wrapt==1.16.0 zipp==3.6.0
name: cryptoconditions channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - astroid==2.11.7 - attrs==22.2.0 - babel==2.11.0 - backcall==0.2.0 - base58==0.2.2 - charset-normalizer==2.0.12 - commonmark==0.9.1 - coverage==6.2 - decorator==5.1.1 - dill==0.3.4 - docutils==0.18.1 - ed25519==1.5 - execnet==1.9.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipdb==0.13.13 - ipython==7.16.3 - ipython-genutils==0.2.0 - isort==5.10.1 - jedi==0.17.2 - jinja2==3.0.3 - lazy-object-proxy==1.7.1 - markupsafe==2.0.1 - mccabe==0.7.0 - packaging==21.3 - parso==0.7.1 - pep8==1.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - platformdirs==2.4.0 - pluggy==1.0.0 - pockets==0.9.1 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pyflakes==3.0.1 - pygments==2.14.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-xdist==3.0.2 - pytz==2025.2 - recommonmark==0.7.1 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-napoleon==0.7 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - traitlets==4.3.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - wcwidth==0.2.13 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/cryptoconditions
[ "tests/test_fulfillment.py::TestSha256Fulfillment::test_fulfillment_serialize_to_dict", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_signed_dict_to_fulfillment", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_unsigned_dict_to_fulfillment", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_signed_dict_to_fulfillment", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_unsigned_dict_to_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_signed_dict_to_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_unsigned_dict_to_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_signed_dict_to_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_unsigned_dict_to_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_weights", "tests/test_fulfillment.py::TestInvertedThresholdSha256Fulfillment::test_serialize_condition_and_validate_fulfillment", "tests/test_fulfillment.py::TestTimeoutFulfillment::test_serialize_condition_and_validate_fulfillment", "tests/test_fulfillment.py::TestEscrow::test_serialize_condition_and_validate_fulfillment" ]
[]
[ "tests/test_fulfillment.py::TestSha256Condition::test_deserialize_condition", "tests/test_fulfillment.py::TestSha256Condition::test_create_condition", "tests/test_fulfillment.py::TestSha256Fulfillment::test_deserialize_and_validate_fulfillment", "tests/test_fulfillment.py::TestSha256Fulfillment::test_deserialize_condition_and_validate_fulfillment", "tests/test_fulfillment.py::TestSha256Fulfillment::test_condition_from_fulfillment", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_ilp_keys", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_create", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_condition_and_validate_fulfillment", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_condition", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_deserialize_condition", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_fulfillment", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_deserialize_fulfillment_2", "tests/test_fulfillment.py::TestEd25519Sha256Fulfillment::test_serialize_deserialize_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_condition_and_validate_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_deserialize_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_serialize_deserialize_fulfillment", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_didnt_reach_threshold", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_nested_and_or", "tests/test_fulfillment.py::TestThresholdSha256Fulfillment::test_fulfillment_nested", "tests/test_fulfillment.py::TestEscrow::test_escrow_execute", "tests/test_fulfillment.py::TestEscrow::test_escrow_abort", "tests/test_fulfillment.py::TestEscrow::test_escrow_execute_abort" ]
[]
MIT License
581
cdent__gabbi-153
0a8a3b8faf9a900fd132d9b147f67a851d52f178
2016-06-12 20:11:11
0a8a3b8faf9a900fd132d9b147f67a851d52f178
cdent: @jd and @EmilienM, this good for you guys? EmilienM: :+1:
diff --git a/gabbi/driver.py b/gabbi/driver.py index 33c0a98..49088fa 100644 --- a/gabbi/driver.py +++ b/gabbi/driver.py @@ -39,7 +39,8 @@ from gabbi import utils def build_tests(path, loader, host=None, port=8001, intercept=None, test_loader_name=None, fixture_module=None, - response_handlers=None, prefix='', require_ssl=False): + response_handlers=None, prefix='', require_ssl=False, + url=None): """Read YAML files from a directory to create tests. Each YAML file represents an ordered sequence of HTTP requests. @@ -54,6 +55,7 @@ def build_tests(path, loader, host=None, port=8001, intercept=None, :param response_handers: ResponseHandler classes. :type response_handlers: List of ResponseHandler classes. :param prefix: A URL prefix for all URLs that are not fully qualified. + :param url: A full URL to test against. Replaces host, port and prefix. :param require_ssl: If ``True``, make all tests default to using SSL. :rtype: TestSuite containing multiple TestSuites (one for each YAML file). """ @@ -63,6 +65,12 @@ def build_tests(path, loader, host=None, port=8001, intercept=None, if not bool(host) ^ bool(intercept): raise AssertionError('must specify exactly one of host or intercept') + # If url is being used, reset host, port and prefix. + if url: + host, port, prefix, force_ssl = utils.host_info_from_target(url) + if force_ssl and not require_ssl: + require_ssl = force_ssl + if test_loader_name is None: test_loader_name = inspect.stack()[1] test_loader_name = os.path.splitext(os.path.basename( @@ -97,7 +105,7 @@ def build_tests(path, loader, host=None, port=8001, intercept=None, def py_test_generator(test_dir, host=None, port=8001, intercept=None, prefix=None, test_loader_name=None, fixture_module=None, response_handlers=None, - require_ssl=False): + require_ssl=False, url=None): """Generate tests cases for py.test This uses build_tests to create TestCases and then yields them in @@ -110,7 +118,8 @@ def py_test_generator(test_dir, host=None, port=8001, intercept=None, test_loader_name=test_loader_name, fixture_module=fixture_module, response_handlers=response_handlers, - prefix=prefix, require_ssl=require_ssl) + prefix=prefix, require_ssl=require_ssl, + url=url) for test in tests: if hasattr(test, '_tests'): diff --git a/gabbi/runner.py b/gabbi/runner.py index 3411dbe..d4e79d5 100644 --- a/gabbi/runner.py +++ b/gabbi/runner.py @@ -17,8 +17,6 @@ from importlib import import_module import sys import unittest -from six.moves.urllib import parse as urlparse - from gabbi import case from gabbi import handlers from gabbi.reporter import ConciseTestRunner @@ -93,7 +91,7 @@ def run(): ) args = parser.parse_args() - host, port, prefix, force_ssl = process_target_args( + host, port, prefix, force_ssl = utils.host_info_from_target( args.target, args.prefix) # Initialize response handlers. @@ -113,31 +111,6 @@ def run(): sys.exit(not result.wasSuccessful()) -def process_target_args(target, prefix): - """Turn the argparse args into a host, port and prefix.""" - force_ssl = False - split_url = urlparse.urlparse(target) - - if split_url.scheme: - if split_url.scheme == 'https': - force_ssl = True - return split_url.hostname, split_url.port, split_url.path, force_ssl - else: - target = target - prefix = prefix - - if ':' in target and '[' not in target: - host, port = target.rsplit(':', 1) - elif ']:' in target: - host, port = target.rsplit(':', 1) - else: - host = target - port = None - host = host.replace('[', '').replace(']', '') - - return host, port, prefix, force_ssl - - def initialize_handlers(response_handlers): custom_response_handlers = [] for import_path in response_handlers or []: diff --git a/gabbi/utils.py b/gabbi/utils.py index 3de040d..172b4bf 100644 --- a/gabbi/utils.py +++ b/gabbi/utils.py @@ -126,6 +126,31 @@ def not_binary(content_type): content_type.startswith('application/json')) +def host_info_from_target(target, prefix=None): + """Turn url or host:port and target into test destination.""" + force_ssl = False + split_url = urlparse.urlparse(target) + + if split_url.scheme: + if split_url.scheme == 'https': + force_ssl = True + return split_url.hostname, split_url.port, split_url.path, force_ssl + else: + target = target + prefix = prefix + + if ':' in target and '[' not in target: + host, port = target.rsplit(':', 1) + elif ']:' in target: + host, port = target.rsplit(':', 1) + else: + host = target + port = None + host = host.replace('[', '').replace(']', '') + + return host, port, prefix, force_ssl + + def _colorize(color, message): """Add a color to the message.""" try:
In 'live' testing scenarios argument passing to build_tests is convoluted and SSL may not work If you want to use `build_tests` to create real TestCases against a live server it's likely you know the URL and that would be most convenient thing to pass instead of having to parse out the host, port and prefix (script_name) and then pass those. In addition, if you have a URL you know if your server is SSL but the tests may not have been written to do SSL (with an `ssl: true` entry). Because of the test building process this is a bit awkward at the moment. It would be better to be able to say "yeah, this is SSL" for the whole run.
cdent/gabbi
diff --git a/gabbi/tests/test_driver.py b/gabbi/tests/test_driver.py index 0b2ce0a..8f6bca0 100644 --- a/gabbi/tests/test_driver.py +++ b/gabbi/tests/test_driver.py @@ -70,3 +70,20 @@ class DriverTest(unittest.TestCase): first_test = suite._tests[0]._tests[0] full_url = first_test._parse_url(first_test.test_data['url']) self.assertEqual('http://localhost:8001/', full_url) + + def test_build_url_target(self): + suite = driver.build_tests(self.test_dir, self.loader, + host='localhost', port='999', + url='https://example.com:1024/theend') + first_test = suite._tests[0]._tests[0] + full_url = first_test._parse_url(first_test.test_data['url']) + self.assertEqual('https://example.com:1024/theend/', full_url) + + def test_build_url_target_forced_ssl(self): + suite = driver.build_tests(self.test_dir, self.loader, + host='localhost', port='999', + url='http://example.com:1024/theend', + require_ssl=True) + first_test = suite._tests[0]._tests[0] + full_url = first_test._parse_url(first_test.test_data['url']) + self.assertEqual('https://example.com:1024/theend/', full_url) diff --git a/gabbi/tests/test_runner.py b/gabbi/tests/test_runner.py index 3c132b1..a854cf9 100644 --- a/gabbi/tests/test_runner.py +++ b/gabbi/tests/test_runner.py @@ -229,93 +229,6 @@ class RunnerTest(unittest.TestCase): self._stderr.write(sys.stderr.read()) -class RunnerHostArgParse(unittest.TestCase): - - def _test_hostport(self, url_or_host, expected_host, - provided_prefix=None, expected_port=None, - expected_prefix=None, expected_ssl=False): - host, port, prefix, ssl = runner.process_target_args( - url_or_host, provided_prefix) - - # normalize hosts, they are case insensitive - self.assertEqual(expected_host.lower(), host.lower()) - # port can be a string or int depending on the inputs - self.assertEqual(expected_port, port) - self.assertEqual(expected_prefix, prefix) - self.assertEqual(expected_ssl, ssl) - - def test_plain_url_no_port(self): - self._test_hostport('http://foobar.com/news', - 'foobar.com', - expected_port=None, - expected_prefix='/news') - - def test_plain_url_with_port(self): - self._test_hostport('http://foobar.com:80/news', - 'foobar.com', - expected_port=80, - expected_prefix='/news') - - def test_ssl_url(self): - self._test_hostport('https://foobar.com/news', - 'foobar.com', - expected_prefix='/news', - expected_ssl=True) - - def test_ssl_port80_url(self): - self._test_hostport('https://foobar.com:80/news', - 'foobar.com', - expected_prefix='/news', - expected_port=80, - expected_ssl=True) - - def test_ssl_port_url(self): - self._test_hostport('https://foobar.com:999/news', - 'foobar.com', - expected_prefix='/news', - expected_port=999, - expected_ssl=True) - - def test_simple_hostport(self): - self._test_hostport('foobar.com:999', - 'foobar.com', - expected_port='999') - - def test_simple_hostport_with_prefix(self): - self._test_hostport('foobar.com:999', - 'foobar.com', - provided_prefix='/news', - expected_port='999', - expected_prefix='/news') - - def test_ipv6_url_long(self): - self._test_hostport( - 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/news', - 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', - expected_port=999, - expected_prefix='/news') - - def test_ipv6_url_localhost(self): - self._test_hostport( - 'http://[::1]:999/news', - '::1', - expected_port=999, - expected_prefix='/news') - - def test_ipv6_host_localhost(self): - # If a user wants to use the hostport form, then they need - # to hack it with the brackets. - self._test_hostport( - '[::1]', - '::1') - - def test_ipv6_hostport_localhost(self): - self._test_hostport( - '[::1]:999', - '::1', - expected_port='999') - - class HTMLResponseHandler(handlers.ResponseHandler): test_key_suffix = 'html' diff --git a/gabbi/tests/test_utils.py b/gabbi/tests/test_utils.py index 1754dad..d5b8b50 100644 --- a/gabbi/tests/test_utils.py +++ b/gabbi/tests/test_utils.py @@ -158,3 +158,90 @@ class CreateURLTest(unittest.TestCase): '/foo', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', port=999) self.assertEqual( 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/foo', url) + + +class UtilsHostInfoFromTarget(unittest.TestCase): + + def _test_hostport(self, url_or_host, expected_host, + provided_prefix=None, expected_port=None, + expected_prefix=None, expected_ssl=False): + host, port, prefix, ssl = utils.host_info_from_target( + url_or_host, provided_prefix) + + # normalize hosts, they are case insensitive + self.assertEqual(expected_host.lower(), host.lower()) + # port can be a string or int depending on the inputs + self.assertEqual(expected_port, port) + self.assertEqual(expected_prefix, prefix) + self.assertEqual(expected_ssl, ssl) + + def test_plain_url_no_port(self): + self._test_hostport('http://foobar.com/news', + 'foobar.com', + expected_port=None, + expected_prefix='/news') + + def test_plain_url_with_port(self): + self._test_hostport('http://foobar.com:80/news', + 'foobar.com', + expected_port=80, + expected_prefix='/news') + + def test_ssl_url(self): + self._test_hostport('https://foobar.com/news', + 'foobar.com', + expected_prefix='/news', + expected_ssl=True) + + def test_ssl_port80_url(self): + self._test_hostport('https://foobar.com:80/news', + 'foobar.com', + expected_prefix='/news', + expected_port=80, + expected_ssl=True) + + def test_ssl_port_url(self): + self._test_hostport('https://foobar.com:999/news', + 'foobar.com', + expected_prefix='/news', + expected_port=999, + expected_ssl=True) + + def test_simple_hostport(self): + self._test_hostport('foobar.com:999', + 'foobar.com', + expected_port='999') + + def test_simple_hostport_with_prefix(self): + self._test_hostport('foobar.com:999', + 'foobar.com', + provided_prefix='/news', + expected_port='999', + expected_prefix='/news') + + def test_ipv6_url_long(self): + self._test_hostport( + 'http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:999/news', + 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', + expected_port=999, + expected_prefix='/news') + + def test_ipv6_url_localhost(self): + self._test_hostport( + 'http://[::1]:999/news', + '::1', + expected_port=999, + expected_prefix='/news') + + def test_ipv6_host_localhost(self): + # If a user wants to use the hostport form, then they need + # to hack it with the brackets. + self._test_hostport( + '[::1]', + '::1') + + def test_ipv6_hostport_localhost(self): + self._test_hostport( + '[::1]:999', + '::1', + expected_port='999')
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 3 }
1.21
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 colorama==0.4.5 decorator==5.1.1 -e git+https://github.com/cdent/gabbi.git@0a8a3b8faf9a900fd132d9b147f67a851d52f178#egg=gabbi importlib-metadata==4.8.3 iniconfig==1.1.1 jsonpath-rw==1.4.0 jsonpath-rw-ext==1.2.2 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 ply==3.11 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 wsgi_intercept==1.13.1 zipp==3.6.0
name: gabbi channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - colorama==0.4.5 - decorator==5.1.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jsonpath-rw==1.4.0 - jsonpath-rw-ext==1.2.2 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - ply==3.11 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wsgi-intercept==1.13.1 - zipp==3.6.0 prefix: /opt/conda/envs/gabbi
[ "gabbi/tests/test_driver.py::DriverTest::test_build_url_target", "gabbi/tests/test_driver.py::DriverTest::test_build_url_target_forced_ssl", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_host_localhost", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_hostport_localhost", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_localhost", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_long", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_no_port", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_with_port", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport_with_prefix", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port80_url", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port_url", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_url" ]
[]
[ "gabbi/tests/test_driver.py::DriverTest::test_build_require_ssl", "gabbi/tests/test_driver.py::DriverTest::test_build_requires_host_or_intercept", "gabbi/tests/test_driver.py::DriverTest::test_driver_loads_two_tests", "gabbi/tests/test_driver.py::DriverTest::test_driver_prefix", "gabbi/tests/test_runner.py::RunnerTest::test_custom_response_handler", "gabbi/tests/test_runner.py::RunnerTest::test_exit_code", "gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing", "gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing_standard_port", "gabbi/tests/test_utils.py::BinaryTypesTest::test_binary", "gabbi/tests/test_utils.py::BinaryTypesTest::test_not_binary", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_bad_params", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_both", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_charset", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_multiple_params", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_with_charset", "gabbi/tests/test_utils.py::ColorizeTest::test_colorize_missing_color", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_already_bracket", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_full", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl_weird_port", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_no_double_colon", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_not_ssl_on_443", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port_and_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_prefix", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_preserve_query", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_simple", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl_on_80" ]
[]
Apache License 2.0
582
kytos__python-openflow-99
1b4d191de2e51695ab94395d4f0ba93a7f0e98f8
2016-06-13 23:18:31
1b4d191de2e51695ab94395d4f0ba93a7f0e98f8
diff --git a/pyof/v0x01/controller2switch/packet_out.py b/pyof/v0x01/controller2switch/packet_out.py index 78cb669..e7c9965 100644 --- a/pyof/v0x01/controller2switch/packet_out.py +++ b/pyof/v0x01/controller2switch/packet_out.py @@ -7,12 +7,16 @@ uses the OFPT_PACKET_OUT message""" # Local source tree imports from pyof.v0x01.common import header as of_header +from pyof.v0x01.common.phy_port import Port from pyof.v0x01.controller2switch import common from pyof.v0x01.foundation import base from pyof.v0x01.foundation import basic_types +from pyof.v0x01.foundation.exceptions import ValidationError # Classes +#: in_port valid virtual port values, for validation +_VIRT_IN_PORTS = (Port.OFPP_LOCAL, Port.OFPP_CONTROLLER, Port.OFPP_NONE) class PacketOut(base.GenericMessage): """ @@ -47,3 +51,25 @@ class PacketOut(base.GenericMessage): self.actions_len = actions_len self.actions = [] if actions is None else actions self.data = data + + def validate(self): + if not super().is_valid(): + raise ValidationError() + self._validate_in_port() + + def is_valid(self): + try: + self.validate() + return True + except ValidationError: + return False + + def _validate_in_port(self): + port = self.in_port + valid = True + if isinstance(port, int) and (port < 1 or port >= Port.OFPP_MAX.value): + valid = False + elif isinstance(port, Port) and port not in _VIRT_IN_PORTS: + valid = False + if not valid: + raise ValidationError('{} is not a valid input port.'.format(port)) diff --git a/pyof/v0x01/foundation/exceptions.py b/pyof/v0x01/foundation/exceptions.py index 0dab2cd..13e9296 100644 --- a/pyof/v0x01/foundation/exceptions.py +++ b/pyof/v0x01/foundation/exceptions.py @@ -1,6 +1,11 @@ """Exceptions defined on this Library""" +class ValidationError(Exception): + """Can be used directly or inherited by specific validation errors.""" + pass + + class MethodNotImplemented(Exception): """Exception to be raised when a method is not implemented""" def __init__(self, message=None): @@ -33,44 +38,11 @@ class WrongListItemType(Exception): return message -class PADHasNoValue(Exception): - """Exception raised when user tries to set a value on a PAD attribute""" - def __str__(self): - return "You can't set a value on a PAD attribute" - - -class AttributeTypeError(Exception): - """Error raise when the attribute is not of the expected type - defined on the class definition""" - - def __init__(self, item, item_class, expected_class): - super().__init__() - self.item = item - self.item_class = item_class - self.expected_class = expected_class - - def __str__(self): - msg = "Unexpected value '{}' ".format(str(self.item)) - msg += "with class '{}' ".format(str(self.item_class)) - msg += "and expected class '{}'".format(str(self.expected_class)) - return msg - - class NotBinaryData(Exception): """Error raised when the content of a BinaryData attribute is not binary""" def __str__(self): return "The content of this variable needs to be binary data" -class ValidationError(Exception): - """Error on validate message or struct""" - def __init__(self, msg="Error on validate message"): - super().__init__() - self.msg = msg - - def __str__(self): - return self.msg - - class UnpackException(Exception): pass
Check 1.0.1 and 1.0.2 compliance
kytos/python-openflow
diff --git a/tests/v0x01/test_controller2switch/test_packet_out.py b/tests/v0x01/test_controller2switch/test_packet_out.py index 38dfd5a..4130c77 100644 --- a/tests/v0x01/test_controller2switch/test_packet_out.py +++ b/tests/v0x01/test_controller2switch/test_packet_out.py @@ -1,11 +1,12 @@ import unittest from pyof.v0x01.common import phy_port +from pyof.v0x01.common.phy_port import Port from pyof.v0x01.controller2switch import packet_out +from pyof.v0x01.foundation.exceptions import ValidationError class TestPacketOut(unittest.TestCase): - def setUp(self): self.message = packet_out.PacketOut() self.message.header.xid = 80 @@ -28,3 +29,35 @@ class TestPacketOut(unittest.TestCase): """[Controller2Switch/PacketOut] - unpacking""" # TODO pass + + def test_valid_virtual_in_ports(self): + """Valid virtual ports as defined in 1.0.1 spec.""" + valid = (Port.OFPP_LOCAL, Port.OFPP_CONTROLLER, Port.OFPP_NONE) + msg = packet_out.PacketOut() + for in_port in valid: + msg.in_port = in_port + self.assertTrue(msg.is_valid()) + + def test_invalid_virtual_in_ports(self): + """Invalid virtual ports as defined in 1.0.1 spec.""" + invalid = (Port.OFPP_IN_PORT, Port.OFPP_TABLE, Port.OFPP_NORMAL, + Port.OFPP_FLOOD, Port.OFPP_ALL) + for in_port in invalid: + self.message.in_port = in_port + self.assertFalse(self.message.is_valid()) + self.assertRaises(ValidationError, self.message.validate) + + def test_valid_physical_in_ports(self): + """Physical port limits from 1.0.0 spec.""" + max_valid = int(Port.OFPP_MAX.value) - 1 + for in_port in (1, max_valid): + self.message.in_port = in_port + self.assertTrue(self.message.is_valid()) + + def test_invalid_physical_in_port(self): + """Physical port limits from 1.0.0 spec.""" + max_valid = int(Port.OFPP_MAX.value) - 1 + for in_port in (-1, 0, max_valid + 1, max_valid + 2): + self.message.in_port = in_port + self.assertFalse(self.message.is_valid()) + self.assertRaises(ValidationError, self.message.validate)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "coverage" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/kytos/python-openflow.git@1b4d191de2e51695ab94395d4f0ba93a7f0e98f8#egg=Kytos_OpenFlow_Parser_library packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 tomli==2.2.1
name: python-openflow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - tomli==2.2.1 prefix: /opt/conda/envs/python-openflow
[ "tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_invalid_physical_in_port", "tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_invalid_virtual_in_ports" ]
[]
[ "tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_get_size", "tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_valid_physical_in_ports", "tests/v0x01/test_controller2switch/test_packet_out.py::TestPacketOut::test_valid_virtual_in_ports" ]
[]
MIT License
583
mozilla__bleach-205
2235b8fcadc8abef3a2845bb0ce67206982f3489
2016-06-14 16:16:47
edd91a00e1c50cebbc512c7db61897ad3d0ba00a
diff --git a/bleach/__init__.py b/bleach/__init__.py index 3092cb7..ac163d1 100644 --- a/bleach/__init__.py +++ b/bleach/__init__.py @@ -315,7 +315,7 @@ def linkify(text, callbacks=DEFAULT_CALLBACKS, skip_pre=False, if node.tag == ETREE_TAG('pre') and skip_pre: linkify_nodes(node, False) elif not (node in _seen): - linkify_nodes(node, True) + linkify_nodes(node, parse_text) current_child += 1
Children of <pre> tags should not be linkified when skip_pre=True (patch attached) The children of `pre` tags should not be linkified when `skip_pre` is on ``` diff --git a/bleach/__init__.py b/bleach/__init__.py index 48b6512..4c2dd1b 100644 --- a/bleach/__init__.py +++ b/bleach/__init__.py @@ -300,7 +300,7 @@ def linkify(text, callbacks=DEFAULT_CALLBACKS, skip_pre=False, if node.tag == ETREE_TAG('pre') and skip_pre: linkify_nodes(node, False) elif not (node in _seen): - linkify_nodes(node, True) + linkify_nodes(node, parse_text) current_child += 1 diff --git a/bleach/tests/test_links.py b/bleach/tests/test_links.py index 62da8d1..ae0fba7 100644 --- a/bleach/tests/test_links.py +++ b/bleach/tests/test_links.py @@ -314,6 +314,13 @@ def test_skip_pre(): eq_(nofollowed, linkify(already_linked)) eq_(nofollowed, linkify(already_linked, skip_pre=True)) +def test_skip_pre_child(): + # Don't linkify the children of pre tags. + intext = '<pre><code>http://foo.com</code></pre>http://bar.com' + expect = '<pre><code>http://foo.com</code></pre><a href="http://bar.com" rel="nofollow">http://bar.com</a>' + output = linkify(intext, skip_pre=True) + eq_(expect, output) + def test_libgl(): """libgl.so.1 should not be linkified.""" ```
mozilla/bleach
diff --git a/bleach/tests/test_links.py b/bleach/tests/test_links.py index 62da8d1..2958f5e 100644 --- a/bleach/tests/test_links.py +++ b/bleach/tests/test_links.py @@ -314,6 +314,13 @@ def test_skip_pre(): eq_(nofollowed, linkify(already_linked)) eq_(nofollowed, linkify(already_linked, skip_pre=True)) + eq_( + linkify('<pre><code>http://example.com</code></pre>http://example.com', + skip_pre=True), + ('<pre><code>http://example.com</code></pre>' + '<a href="http://example.com" rel="nofollow">http://example.com</a>') + ) + def test_libgl(): """libgl.so.1 should not be linkified."""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "flake8", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 -e git+https://github.com/mozilla/bleach.git@2235b8fcadc8abef3a2845bb0ce67206982f3489#egg=bleach certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 colorama==0.4.5 cryptography==40.0.2 distlib==0.3.9 docutils==0.17.1 filelock==3.4.1 flake8==5.0.4 html5lib==0.9999999 idna==3.10 imagesize==1.4.1 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 jeepney==0.7.1 Jinja2==3.0.3 keyring==23.4.1 MarkupSafe==2.0.1 mccabe==0.7.0 nose==1.3.7 ordereddict==1.1 packaging==21.3 pkginfo==1.10.0 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pycparser==2.21 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytz==2025.2 readme-renderer==34.0 requests==2.27.1 requests-toolbelt==1.0.0 rfc3986==1.5.0 SecretStorage==3.3.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==4.3.2 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 toml==0.10.2 tomli==1.2.3 tox==3.28.0 tqdm==4.64.1 twine==3.8.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.16.2 webencodings==0.5.1 zipp==3.6.0
name: bleach channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - colorama==0.4.5 - cryptography==40.0.2 - distlib==0.3.9 - docutils==0.17.1 - filelock==3.4.1 - flake8==5.0.4 - html5lib==0.9999999 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jeepney==0.7.1 - jinja2==3.0.3 - keyring==23.4.1 - markupsafe==2.0.1 - mccabe==0.7.0 - nose==1.3.7 - ordereddict==1.1 - packaging==21.3 - pkginfo==1.10.0 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pycparser==2.21 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytz==2025.2 - readme-renderer==34.0 - requests==2.27.1 - requests-toolbelt==1.0.0 - rfc3986==1.5.0 - secretstorage==3.3.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==4.3.2 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - tqdm==4.64.1 - twine==3.8.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.16.2 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/bleach
[ "bleach/tests/test_links.py::test_skip_pre" ]
[]
[ "bleach/tests/test_links.py::test_empty", "bleach/tests/test_links.py::test_simple_link", "bleach/tests/test_links.py::test_trailing_slash", "bleach/tests/test_links.py::test_mangle_link", "bleach/tests/test_links.py::test_mangle_text", "bleach/tests/test_links.py::test_set_attrs", "bleach/tests/test_links.py::test_only_proto_links", "bleach/tests/test_links.py::test_stop_email", "bleach/tests/test_links.py::test_tlds", "bleach/tests/test_links.py::test_escaping", "bleach/tests/test_links.py::test_nofollow_off", "bleach/tests/test_links.py::test_link_in_html", "bleach/tests/test_links.py::test_links_https", "bleach/tests/test_links.py::test_add_rel_nofollow", "bleach/tests/test_links.py::test_url_with_path", "bleach/tests/test_links.py::test_link_ftp", "bleach/tests/test_links.py::test_link_query", "bleach/tests/test_links.py::test_link_fragment", "bleach/tests/test_links.py::test_link_entities", "bleach/tests/test_links.py::test_escaped_html", "bleach/tests/test_links.py::test_link_http_complete", "bleach/tests/test_links.py::test_non_url", "bleach/tests/test_links.py::test_javascript_url", "bleach/tests/test_links.py::test_unsafe_url", "bleach/tests/test_links.py::test_libgl", "bleach/tests/test_links.py::test_end_of_clause", "bleach/tests/test_links.py::test_sarcasm", "bleach/tests/test_links.py::test_parentheses_with_removing", "bleach/tests/test_links.py::test_tokenizer", "bleach/tests/test_links.py::test_ignore_bad_protocols", "bleach/tests/test_links.py::test_max_recursion_depth", "bleach/tests/test_links.py::test_link_emails_and_urls", "bleach/tests/test_links.py::test_links_case_insensitive", "bleach/tests/test_links.py::test_elements_inside_links", "bleach/tests/test_links.py::test_remove_first_childlink" ]
[]
Apache License 2.0
584
Backblaze__B2_Command_Line_Tool-173
ab2b5b4e3dc2c8b52b28592c7414ebb4646034e2
2016-06-14 20:22:17
01c4e89f63f38b9efa6a6fa63f54cd556a0b5305
diff --git a/b2/sync.py b/b2/sync.py index c3c4ad9..cffdc81 100644 --- a/b2/sync.py +++ b/b2/sync.py @@ -67,12 +67,15 @@ class SyncReport(object): self.closed = False self.lock = threading.Lock() self._update_progress() + self.warnings = [] def close(self): with self.lock: if not self.no_progress: self._print_line('', False) self.closed = True + for warning in self.warnings: + self._print_line(warning, True) def __enter__(self): return self @@ -185,6 +188,9 @@ class SyncReport(object): self.transfer_bytes += byte_delta self._update_progress() + def local_access_error(self, path): + self.warnings.append('WARNING: %s could not be accessed (broken symlink?)' % (path,)) + class SyncFileReporter(AbstractProgressListener): """ @@ -453,13 +459,17 @@ class AbstractFolder(object): """ @abstractmethod - def all_files(self): + def all_files(self, reporter): """ Returns an iterator over all of the files in the folder, in the order that B2 uses. No matter what the folder separator on the local file system is, "/" is used in the returned file names. + + If a file is found, but does not exist (for example due to + a broken symlink or a race), reporter will be informed about + each such problem. """ @abstractmethod @@ -494,9 +504,9 @@ class LocalFolder(AbstractFolder): def folder_type(self): return 'local' - def all_files(self): + def all_files(self, reporter): prefix_len = len(self.root) + 1 # include trailing '/' in prefix length - for relative_path in self._walk_relative_paths(prefix_len, self.root): + for relative_path in self._walk_relative_paths(prefix_len, self.root, reporter): yield self._make_file(relative_path) def make_full_path(self, file_name): @@ -514,7 +524,7 @@ class LocalFolder(AbstractFolder): elif not os.path.isdir(self.root): raise Exception('%s is not a directory' % (self.root,)) - def _walk_relative_paths(self, prefix_len, dir_path): + def _walk_relative_paths(self, prefix_len, dir_path, reporter): """ Yields all of the file names anywhere under this folder, in the order they would appear in B2. @@ -535,16 +545,21 @@ class LocalFolder(AbstractFolder): ) full_path = os.path.join(dir_path, name) relative_path = full_path[prefix_len:] - if os.path.isdir(full_path): - name += six.u('/') - dirs.add(name) - names[name] = (full_path, relative_path) + # Skip broken symlinks or other inaccessible files + if not os.path.exists(full_path): + if reporter is not None: + reporter.local_access_error(full_path) + else: + if os.path.isdir(full_path): + name += six.u('/') + dirs.add(name) + names[name] = (full_path, relative_path) # Yield all of the answers for name in sorted(names): (full_path, relative_path) = names[name] if name in dirs: - for rp in self._walk_relative_paths(prefix_len, full_path): + for rp in self._walk_relative_paths(prefix_len, full_path, reporter): yield rp else: yield relative_path @@ -573,7 +588,7 @@ class B2Folder(AbstractFolder): self.bucket = api.get_bucket_by_name(bucket_name) self.prefix = '' if self.folder_name == '' else self.folder_name + '/' - def all_files(self): + def all_files(self, reporter): current_name = None current_versions = [] for (file_version_info, folder_name) in self.bucket.ls( @@ -625,7 +640,7 @@ def next_or_none(iterator): return None -def zip_folders(folder_a, folder_b, exclusions=tuple()): +def zip_folders(folder_a, folder_b, reporter, exclusions=tuple()): """ An iterator over all of the files in the union of two folders, matching file names. @@ -637,8 +652,10 @@ def zip_folders(folder_a, folder_b, exclusions=tuple()): :param folder_b: A Folder object. """ - iter_a = (f for f in folder_a.all_files() if not any(ex.match(f.name) for ex in exclusions)) - iter_b = folder_b.all_files() + iter_a = ( + f for f in folder_a.all_files(reporter) if not any(ex.match(f.name) for ex in exclusions) + ) + iter_b = folder_b.all_files(reporter) current_a = next_or_none(iter_a) current_b = next_or_none(iter_b) @@ -810,7 +827,7 @@ def make_folder_sync_actions(source_folder, dest_folder, args, now_millis, repor ('b2', 'local'), ('local', 'b2') ]: raise NotImplementedError("Sync support only local-to-b2 and b2-to-local") - for (source_file, dest_file) in zip_folders(source_folder, dest_folder, exclusions): + for (source_file, dest_file) in zip_folders(source_folder, dest_folder, reporter, exclusions): if source_folder.folder_type() == 'local': if source_file is not None: reporter.update_compare(1) @@ -863,7 +880,9 @@ def count_files(local_folder, reporter): """ Counts all of the files in a local folder. """ - for _ in local_folder.all_files(): + # Don't pass in a reporter to all_files. Broken symlinks will be reported + # during the next pass when the source and dest files are compared. + for _ in local_folder.all_files(None): reporter.update_local(1) reporter.end_local()
Broken symlink break sync I had this issue where one of my sysmlinks was broken and b2 tool broke, this is the stack trace: ``` Traceback (most recent call last): File "/usr/local/bin/b2", line 9, in <module> load_entry_point('b2==0.5.4', 'console_scripts', 'b2')() File "/usr/local/lib/python2.7/dist-packages/b2/console_tool.py", line 861, in main exit_status = ct.run_command(decoded_argv) File "/usr/local/lib/python2.7/dist-packages/b2/console_tool.py", line 789, in run_command return command.run(args) File "/usr/local/lib/python2.7/dist-packages/b2/console_tool.py", line 609, in run max_workers=max_workers File "/usr/local/lib/python2.7/dist-packages/b2/sync.py", line 877, in sync_folders source_folder, dest_folder, args, now_millis, reporter File "/usr/local/lib/python2.7/dist-packages/b2/sync.py", line 777, in make_folder_sync_actions for (source_file, dest_file) in zip_folders(source_folder, dest_folder): File "/usr/local/lib/python2.7/dist-packages/b2/sync.py", line 646, in zip_folders current_a = next_or_none(iter_a) File "/usr/local/lib/python2.7/dist-packages/b2/sync.py", line 620, in next_or_none return six.advance_iterator(iterator) File "/usr/local/lib/python2.7/dist-packages/b2/sync.py", line 499, in all_files yield self._make_file(relative_path) File "/usr/local/lib/python2.7/dist-packages/b2/sync.py", line 553, in _make_file mod_time = int(round(os.path.getmtime(full_path) * 1000)) File "/usr/lib/python2.7/genericpath.py", line 54, in getmtime return os.stat(filename).st_mtime OSError: [Errno 2] No such file or directory: '/media/2a9074d0-4788-45ab-bfae-fc46427c69fa/PersonalData/some-broken-symlink' ```
Backblaze/B2_Command_Line_Tool
diff --git a/test/test_sync.py b/test/test_sync.py index ad2b140..9102b6e 100644 --- a/test/test_sync.py +++ b/test/test_sync.py @@ -37,36 +37,58 @@ def write_file(path, contents): f.write(contents) -def create_files(root_dir, relative_paths): - for relative_path in relative_paths: - full_path = os.path.join(root_dir, relative_path) - write_file(full_path, b'') +class TestLocalFolder(unittest.TestCase): + NAMES = [ + six.u('.dot_file'), six.u('hello.'), six.u('hello/a/1'), six.u('hello/a/2'), + six.u('hello/b'), six.u('hello0'), six.u('\u81ea\u7531') + ] + def setUp(self): + self.reporter = MagicMock() + + @classmethod + def _create_files(cls, root_dir, relative_paths): + for relative_path in relative_paths: + full_path = os.path.join(root_dir, relative_path) + write_file(full_path, b'') + + def _prepare_folder(self, root_dir, broken_symlink=False): + self._create_files(root_dir, self.NAMES) + if broken_symlink: + os.symlink( + os.path.join(root_dir, 'non_existant_file'), os.path.join(root_dir, 'bad_symlink') + ) + return LocalFolder(root_dir) -class TestLocalFolder(unittest.TestCase): def test_slash_sorting(self): # '/' should sort between '.' and '0' - names = [ - six.u('.dot_file'), six.u('hello.'), six.u('hello/a/1'), six.u('hello/a/2'), - six.u('hello/b'), six.u('hello0'), six.u('\u81ea\u7531') - ] with TempDir() as tmpdir: - create_files(tmpdir, names) - folder = LocalFolder(tmpdir) - actual_names = list(f.name for f in folder.all_files()) - self.assertEqual(names, actual_names) + folder = self._prepare_folder(tmpdir) + actual_names = list(f.name for f in folder.all_files(self.reporter)) + self.assertEqual(self.NAMES, actual_names) + self.reporter.local_access_error.assert_not_called() + + def test_broken_symlink(self): + with TempDir() as tmpdir: + folder = self._prepare_folder(tmpdir, broken_symlink=True) + for f in folder.all_files(self.reporter): + pass # just generate all the files + self.reporter.local_access_error.assert_called_once_with( + os.path.join(tmpdir, 'bad_symlink') + ) class TestB2Folder(unittest.TestCase): def setUp(self): self.bucket = MagicMock() self.api = MagicMock() + self.reporter = MagicMock() self.api.get_bucket_by_name.return_value = self.bucket self.b2_folder = B2Folder('bucket-name', 'folder', self.api) def test_empty(self): self.bucket.ls.return_value = [] - self.assertEqual([], list(self.b2_folder.all_files())) + self.assertEqual([], list(self.b2_folder.all_files(self.reporter))) def test_multiple_versions(self): # Test two files, to cover the yield within the loop, and @@ -102,7 +124,7 @@ class TestB2Folder(unittest.TestCase): [ "File(a.txt, [FileVersion('a2', 'folder/a.txt', 2000, 'upload'), FileVersion('a1', 'folder/a.txt', 1000, 'upload')])", "File(b.txt, [FileVersion('b2', 'folder/b.txt', 2000, 'upload'), FileVersion('b1', 'folder/b.txt', 1000, 'upload')])", - ], [str(f) for f in self.b2_folder.all_files()] + ], [str(f) for f in self.b2_folder.all_files(self.reporter)] ) @@ -111,7 +133,7 @@ class FakeFolder(AbstractFolder): self.f_type = f_type self.files = files - def all_files(self): + def all_files(self, reporter): return iter(self.files) def folder_type(self): @@ -150,16 +172,19 @@ class TestParseSyncFolder(unittest.TestCase): class TestZipFolders(unittest.TestCase): + def setUp(self): + self.reporter = MagicMock() + def test_empty(self): folder_a = FakeFolder('b2', []) folder_b = FakeFolder('b2', []) - self.assertEqual([], list(zip_folders(folder_a, folder_b))) + self.assertEqual([], list(zip_folders(folder_a, folder_b, self.reporter))) def test_one_empty(self): file_a1 = File("a.txt", [FileVersion("a", "a", 100, "upload", 10)]) folder_a = FakeFolder('b2', [file_a1]) folder_b = FakeFolder('b2', []) - self.assertEqual([(file_a1, None)], list(zip_folders(folder_a, folder_b))) + self.assertEqual([(file_a1, None)], list(zip_folders(folder_a, folder_b, self.reporter))) def test_two(self): file_a1 = File("a.txt", [FileVersion("a", "a", 100, "upload", 10)]) @@ -174,9 +199,22 @@ class TestZipFolders(unittest.TestCase): [ (file_a1, None), (file_a2, file_b1), (file_a3, None), (None, file_b2), (file_a4, None) - ], list(zip_folders(folder_a, folder_b)) + ], list(zip_folders(folder_a, folder_b, self.reporter)) ) + def test_pass_reporter_to_folder(self): + """ + Check that the zip_folders() function passes the reporter through + to both folders. + """ + folder_a = MagicMock() + folder_b = MagicMock() + folder_a.all_files = MagicMock(return_value=iter([])) + folder_b.all_files = MagicMock(return_value=iter([])) + self.assertEqual([], list(zip_folders(folder_a, folder_b, self.reporter))) + folder_a.all_files.assert_called_once_with(self.reporter) + folder_b.all_files.assert_called_once_with(self.reporter) + class FakeArgs(object): """ diff --git a/test_b2_command_line.py b/test_b2_command_line.py index 8d23678..0628248 100644 --- a/test_b2_command_line.py +++ b/test_b2_command_line.py @@ -200,6 +200,8 @@ class CommandLine(object): sys.exit(1) if expected_pattern is not None: if re.search(expected_pattern, stdout) is None: + print('STDOUT:') + print(stdout) error_and_exit('did not match pattern: ' + expected_pattern) return stdout @@ -469,8 +471,12 @@ def _sync_test_using_dir(b2_tool, bucket_name, dir_): write_file(p('a'), b'hello') write_file(p('b'), b'hello') write_file(p('c'), b'hello') + os.symlink('broken', p('d')) - b2_tool.should_succeed(['sync', '--noProgress', dir_path, b2_sync_point]) + b2_tool.should_succeed( + ['sync', '--noProgress', dir_path, b2_sync_point], + expected_pattern="/d could not be accessed" + ) file_versions = b2_tool.list_file_versions(bucket_name) should_equal( [
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt", "requirements-test.txt", "requirements-setup.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 -e git+https://github.com/Backblaze/B2_Command_Line_Tool.git@ab2b5b4e3dc2c8b52b28592c7414ebb4646034e2#egg=b2 certifi==2021.5.30 charset-normalizer==2.0.12 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyflakes==3.0.1 pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 six==1.17.0 tomli==1.2.3 tqdm==4.64.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: B2_Command_Line_Tool channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyflakes==3.0.1 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - six==1.17.0 - tomli==1.2.3 - tqdm==4.64.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/B2_Command_Line_Tool
[ "test/test_sync.py::TestLocalFolder::test_broken_symlink", "test/test_sync.py::TestLocalFolder::test_slash_sorting", "test/test_sync.py::TestB2Folder::test_empty", "test/test_sync.py::TestB2Folder::test_multiple_versions", "test/test_sync.py::TestZipFolders::test_empty", "test/test_sync.py::TestZipFolders::test_one_empty", "test/test_sync.py::TestZipFolders::test_pass_reporter_to_folder", "test/test_sync.py::TestZipFolders::test_two", "test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_delete", "test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_keep", "test/test_sync.py::TestMakeSyncActions::test_already_hidden_multiple_versions_keep_days", "test/test_sync.py::TestMakeSyncActions::test_compare_b2_none_newer", "test/test_sync.py::TestMakeSyncActions::test_compare_b2_none_older", "test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_equal", "test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_not_equal", "test/test_sync.py::TestMakeSyncActions::test_compare_b2_size_not_equal_delete", "test/test_sync.py::TestMakeSyncActions::test_delete_b2", "test/test_sync.py::TestMakeSyncActions::test_delete_b2_multiple_versions", "test/test_sync.py::TestMakeSyncActions::test_delete_hide_b2_multiple_versions", "test/test_sync.py::TestMakeSyncActions::test_delete_local", "test/test_sync.py::TestMakeSyncActions::test_empty_b2", "test/test_sync.py::TestMakeSyncActions::test_empty_local", "test/test_sync.py::TestMakeSyncActions::test_file_exclusions", "test/test_sync.py::TestMakeSyncActions::test_file_exclusions_with_delete", "test/test_sync.py::TestMakeSyncActions::test_keep_days_no_change_with_old_file", "test/test_sync.py::TestMakeSyncActions::test_newer_b2", "test/test_sync.py::TestMakeSyncActions::test_newer_b2_clean_old_versions", "test/test_sync.py::TestMakeSyncActions::test_newer_b2_delete_old_versions", "test/test_sync.py::TestMakeSyncActions::test_newer_local", "test/test_sync.py::TestMakeSyncActions::test_no_delete_b2", "test/test_sync.py::TestMakeSyncActions::test_no_delete_local", "test/test_sync.py::TestMakeSyncActions::test_not_there_b2", "test/test_sync.py::TestMakeSyncActions::test_not_there_local", "test/test_sync.py::TestMakeSyncActions::test_older_b2", "test/test_sync.py::TestMakeSyncActions::test_older_b2_replace", "test/test_sync.py::TestMakeSyncActions::test_older_b2_replace_delete", "test/test_sync.py::TestMakeSyncActions::test_older_b2_skip", "test/test_sync.py::TestMakeSyncActions::test_older_local", "test/test_sync.py::TestMakeSyncActions::test_older_local_replace", "test/test_sync.py::TestMakeSyncActions::test_older_local_skip", "test/test_sync.py::TestMakeSyncActions::test_same_b2", "test/test_sync.py::TestMakeSyncActions::test_same_clean_old_versions", "test/test_sync.py::TestMakeSyncActions::test_same_delete_old_versions", "test/test_sync.py::TestMakeSyncActions::test_same_leave_old_versions", "test/test_sync.py::TestMakeSyncActions::test_same_local" ]
[]
[ "test/test_sync.py::TestParseSyncFolder::test_b2_double_slash", "test/test_sync.py::TestParseSyncFolder::test_b2_no_double_slash", "test/test_sync.py::TestParseSyncFolder::test_b2_no_folder", "test/test_sync.py::TestParseSyncFolder::test_b2_trailing_slash", "test/test_sync.py::TestParseSyncFolder::test_local", "test/test_sync.py::TestParseSyncFolder::test_local_trailing_slash", "test/test_sync.py::TestMakeSyncActions::test_illegal_b2_to_b2", "test/test_sync.py::TestMakeSyncActions::test_illegal_delete_and_keep_days", "test/test_sync.py::TestMakeSyncActions::test_illegal_local_to_local", "test/test_sync.py::TestMakeSyncActions::test_illegal_skip_and_replace", "test_b2_command_line.py::TestCommandLine::test_stderr_patterns" ]
[]
MIT License
585
juju-solutions__charms.reactive-71
04663e45f3683d4c497f43526d3ac26593ee10a2
2016-06-14 21:26:10
59b07bd9447d8a4cb027ea2515089216b8d20549
kwmonroe: There was some chatter on #juju about not using a string representation for toggle (instead using `object()`). I'm fine with this as-in, or with that changed. stub42: This needs a test, which I suspect is trivial.
diff --git a/charms/reactive/relations.py b/charms/reactive/relations.py index 173ef28..a8c1499 100644 --- a/charms/reactive/relations.py +++ b/charms/reactive/relations.py @@ -30,7 +30,9 @@ from charms.reactive.bus import _load_module from charms.reactive.bus import StateList -ALL = '__ALL_SERVICES__' +# arbitrary obj instances to use as defaults instead of None +ALL = object() +TOGGLE = object() class scopes(object): @@ -296,13 +298,13 @@ class RelationBase(with_metaclass(AutoAccessors, object)): """ return self.conversation(scope).is_state(state) - def toggle_state(self, state, active=None, scope=None): + def toggle_state(self, state, active=TOGGLE, scope=None): """ Toggle the state for the :class:`Conversation` with the given scope. In Python, this is equivalent to:: - relation.conversation(scope).toggle_state(state) + relation.conversation(scope).toggle_state(state, active) See :meth:`conversation` and :meth:`Conversation.toggle_state`. """ @@ -549,7 +551,7 @@ class Conversation(object): return False return self.key in value['conversations'] - def toggle_state(self, state, active=None): + def toggle_state(self, state, active=TOGGLE): """ Toggle the given state for this conversation. @@ -565,7 +567,7 @@ class Conversation(object): This will set the state if ``value`` is equal to ``foo``. """ - if active is None: + if active is TOGGLE: active = not self.is_state(state) if active: self.set_state(state)
toggle_state default for active is error-prone `toggle_state` takes an optional `active` param that lets you specify whether the state should be on or off, instead of it being switched from its previous value. Having a default value of `None` is problematic because `None` can easily be mistaken for a "truthy" `False` when dealing with relation data, which leads to the state being unexpectedly set. For example, the following breaks: ```python conv.toggle_state('{relation_name}.feature_x', active=conv.get_remote('feature_x_available')) ``` This can also be more subtle because `None and <anything>` returns `None` instead of `False` as one might expect. For example, this also breaks: ```python name = conv.get_remote('name') version = conv.get_remote('version') conv.toggle_state('{relation_name}.ready', name and version) ```
juju-solutions/charms.reactive
diff --git a/tests/test_relations.py b/tests/test_relations.py index c4977da..d49c3e1 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -171,6 +171,11 @@ class TestRelationBase(unittest.TestCase): rb.conversation.assert_called_once_with('scope') conv.toggle_state.assert_called_once_with('state', 'active') + conv.toggle_state.reset_mock() + rb.toggle_state('state') + conv.toggle_state.assert_called_once_with('state', + relations.TOGGLE) + def test_set_remote(self): conv = mock.Mock(name='conv') rb = relations.RelationBase('relname', 'unit') @@ -391,12 +396,14 @@ class TestConversation(unittest.TestCase): conv.toggle_state('foo') self.assertEqual(conv.remove_state.call_count, 1) + conv.toggle_state('foo', None) + self.assertEqual(conv.remove_state.call_count, 2) conv.toggle_state('foo') self.assertEqual(conv.set_state.call_count, 1) conv.toggle_state('foo', True) self.assertEqual(conv.set_state.call_count, 2) conv.toggle_state('foo', False) - self.assertEqual(conv.remove_state.call_count, 2) + self.assertEqual(conv.remove_state.call_count, 3) @mock.patch.object(relations.hookenv, 'relation_set') @mock.patch.object(relations.Conversation, 'relation_ids', ['rel:1', 'rel:2'])
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "flake8", "ipython", "ipdb", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backcall==0.2.0 certifi==2021.5.30 charmhelpers==1.2.1 -e git+https://github.com/juju-solutions/charms.reactive.git@04663e45f3683d4c497f43526d3ac26593ee10a2#egg=charms.reactive coverage==6.2 decorator==5.1.1 flake8==5.0.4 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 ipdb==0.13.13 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 MarkupSafe==2.0.1 mccabe==0.7.0 mock==5.2.0 netaddr==0.10.1 nose==1.3.7 packaging==21.3 parso==0.7.1 pbr==6.1.1 pexpect==4.9.0 pickleshare==0.7.5 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pyaml==23.5.8 pycodestyle==2.9.1 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 tomli==1.2.3 traitlets==4.3.3 typing_extensions==4.1.1 wcwidth==0.2.13 zipp==3.6.0
name: charms.reactive channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backcall==0.2.0 - charmhelpers==1.2.1 - coverage==6.2 - decorator==5.1.1 - flake8==5.0.4 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - ipdb==0.13.13 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - markupsafe==2.0.1 - mccabe==0.7.0 - mock==5.2.0 - netaddr==0.10.1 - nose==1.3.7 - packaging==21.3 - parso==0.7.1 - pbr==6.1.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pyaml==23.5.8 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - traitlets==4.3.3 - typing-extensions==4.1.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/charms.reactive
[ "tests/test_relations.py::TestRelationBase::test_toggle_state", "tests/test_relations.py::TestConversation::test_toggle_state" ]
[]
[ "tests/test_relations.py::TestAutoAccessors::test_accessor", "tests/test_relations.py::TestAutoAccessors::test_accessor_doc", "tests/test_relations.py::TestRelationBase::test_conversation", "tests/test_relations.py::TestRelationBase::test_find_impl", "tests/test_relations.py::TestRelationBase::test_find_subclass", "tests/test_relations.py::TestRelationBase::test_from_name", "tests/test_relations.py::TestRelationBase::test_from_state", "tests/test_relations.py::TestRelationBase::test_get_local", "tests/test_relations.py::TestRelationBase::test_get_remote", "tests/test_relations.py::TestRelationBase::test_is_state", "tests/test_relations.py::TestRelationBase::test_remove_state", "tests/test_relations.py::TestRelationBase::test_set_local", "tests/test_relations.py::TestRelationBase::test_set_remote", "tests/test_relations.py::TestRelationBase::test_set_state", "tests/test_relations.py::TestConversation::test_depart", "tests/test_relations.py::TestConversation::test_get_local", "tests/test_relations.py::TestConversation::test_get_remote", "tests/test_relations.py::TestConversation::test_is_state", "tests/test_relations.py::TestConversation::test_join", "tests/test_relations.py::TestConversation::test_key", "tests/test_relations.py::TestConversation::test_load", "tests/test_relations.py::TestConversation::test_relation_ids", "tests/test_relations.py::TestConversation::test_remove_state", "tests/test_relations.py::TestConversation::test_set_local", "tests/test_relations.py::TestConversation::test_set_remote", "tests/test_relations.py::TestConversation::test_set_state", "tests/test_relations.py::TestMigrateConvs::test_migrate", "tests/test_relations.py::TestRelationCall::test_call_conversations", "tests/test_relations.py::TestRelationCall::test_call_name", "tests/test_relations.py::TestRelationCall::test_call_state", "tests/test_relations.py::TestRelationCall::test_no_impl" ]
[]
Apache License 2.0
586
juju-solutions__charms.reactive-73
04663e45f3683d4c497f43526d3ac26593ee10a2
2016-06-15 01:33:48
59b07bd9447d8a4cb027ea2515089216b8d20549
diff --git a/charms/reactive/bus.py b/charms/reactive/bus.py index 885e498..853571a 100644 --- a/charms/reactive/bus.py +++ b/charms/reactive/bus.py @@ -229,6 +229,7 @@ class Handler(object): self._action = action self._args = [] self._predicates = [] + self._post_callbacks = [] self._states = set() def id(self): @@ -255,6 +256,12 @@ class Handler(object): hookenv.log(' Adding predicate for %s: %s' % (self.id(), _predicate), level=hookenv.DEBUG) self._predicates.append(predicate) + def add_post_callback(self, callback): + """ + Add a callback to be run after the action is invoked. + """ + self._post_callbacks.append(callback) + def test(self): """ Check the predicate(s) and return True if this handler should be invoked. @@ -278,6 +285,8 @@ class Handler(object): """ args = self._get_args() self._action(*args) + for callback in self._post_callbacks: + callback() def register_states(self, states): """ diff --git a/charms/reactive/decorators.py b/charms/reactive/decorators.py index 7918106..e89332f 100644 --- a/charms/reactive/decorators.py +++ b/charms/reactive/decorators.py @@ -205,18 +205,18 @@ def not_unless(*desired_states): return _decorator -def only_once(action): +def only_once(action=None): """ - Ensure that the decorated function is only executed the first time it is called. + Register the decorated function to be run once, and only once. - This can be used on reactive handlers to ensure that they are only triggered - once, even if their conditions continue to match on subsequent calls, even - across hook invocations. + This decorator will never cause arguments to be passed to the handler. """ - @wraps(action) - def wrapper(*args, **kwargs): - action_id = _action_id(action) - if not was_invoked(action_id): - action(*args, **kwargs) - mark_invoked(action_id) - return wrapper + if action is None: + # allow to be used as @only_once or @only_once() + return only_once + + action_id = _action_id(action) + handler = Handler.get(action) + handler.add_predicate(lambda: not was_invoked(action_id)) + handler.add_post_callback(partial(mark_invoked, action_id)) + return action
only_once help unclear _From @jacekn on January 27, 2016 17:29_ I was trying to execute certain function only once in my code. This does not work: ``` @only_once() def basenode(): print("in basenode") ``` ``` TypeError: only_once() missing 1 required positional argument: 'action' ``` I tried like this but it also did not work: ``` @only_once("basenode") def basenode(): print("in basenode") ``` ``` AttributeError: 'str' object has no attribute '__code__' ``` Can documentation be clarified to show correct use of this decorator? _Copied from original issue: juju/charm-tools#94_
juju-solutions/charms.reactive
diff --git a/tests/test_decorators.py b/tests/test_decorators.py index 4691a30..2599b53 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -241,11 +241,28 @@ class TestReactiveDecorators(unittest.TestCase): calls = [] @reactive.decorators.only_once - def test(num): - calls.append(num) + def test(): + calls.append(len(calls)+1) + + handler = reactive.bus.Handler.get(test) - test(1) - test(2) + assert handler.test() + handler.invoke() + assert not handler.test() + self.assertEquals(calls, [1]) + + def test_only_once_parens(self): + calls = [] + + @reactive.decorators.only_once() + def test(): + calls.append(len(calls)+1) + + handler = reactive.bus.Handler.get(test) + + assert handler.test() + handler.invoke() + assert not handler.test() self.assertEquals(calls, [1]) def test_multi(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "flake8", "ipython", "ipdb", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backcall==0.2.0 certifi==2021.5.30 charmhelpers==1.2.1 -e git+https://github.com/juju-solutions/charms.reactive.git@04663e45f3683d4c497f43526d3ac26593ee10a2#egg=charms.reactive coverage==6.2 decorator==5.1.1 flake8==5.0.4 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 ipdb==0.13.13 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 MarkupSafe==2.0.1 mccabe==0.7.0 mock==5.2.0 netaddr==0.10.1 nose==1.3.7 packaging==21.3 parso==0.7.1 pbr==6.1.1 pexpect==4.9.0 pickleshare==0.7.5 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pyaml==23.5.8 pycodestyle==2.9.1 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 tomli==1.2.3 traitlets==4.3.3 typing_extensions==4.1.1 wcwidth==0.2.13 zipp==3.6.0
name: charms.reactive channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backcall==0.2.0 - charmhelpers==1.2.1 - coverage==6.2 - decorator==5.1.1 - flake8==5.0.4 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - ipdb==0.13.13 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - markupsafe==2.0.1 - mccabe==0.7.0 - mock==5.2.0 - netaddr==0.10.1 - nose==1.3.7 - packaging==21.3 - parso==0.7.1 - pbr==6.1.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pyaml==23.5.8 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - traitlets==4.3.3 - typing-extensions==4.1.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/charms.reactive
[ "tests/test_decorators.py::TestReactiveDecorators::test_only_once", "tests/test_decorators.py::TestReactiveDecorators::test_only_once_parens" ]
[]
[ "tests/test_decorators.py::TestReactiveDecorators::test_hook", "tests/test_decorators.py::TestReactiveDecorators::test_multi", "tests/test_decorators.py::TestReactiveDecorators::test_not_unless", "tests/test_decorators.py::TestReactiveDecorators::test_when", "tests/test_decorators.py::TestReactiveDecorators::test_when_all", "tests/test_decorators.py::TestReactiveDecorators::test_when_any", "tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed", "tests/test_decorators.py::TestReactiveDecorators::test_when_none", "tests/test_decorators.py::TestReactiveDecorators::test_when_not", "tests/test_decorators.py::TestReactiveDecorators::test_when_not_all" ]
[]
Apache License 2.0
587
juju-solutions__charms.reactive-74
04663e45f3683d4c497f43526d3ac26593ee10a2
2016-06-15 02:46:03
59b07bd9447d8a4cb027ea2515089216b8d20549
diff --git a/charms/reactive/bus.py b/charms/reactive/bus.py index 885e498..1bd1364 100644 --- a/charms/reactive/bus.py +++ b/charms/reactive/bus.py @@ -170,12 +170,16 @@ def get_state(state, default=None): def _action_id(action): + if hasattr(action, '_action_id'): + return action._action_id return "%s:%s:%s" % (action.__code__.co_filename, action.__code__.co_firstlineno, action.__code__.co_name) def _short_action_id(action): + if hasattr(action, '_short_action_id'): + return action._short_action_id filepath = os.path.relpath(action.__code__.co_filename, hookenv.charm_dir()) return "%s:%s:%s" % (filepath, action.__code__.co_firstlineno, diff --git a/charms/reactive/decorators.py b/charms/reactive/decorators.py index 7918106..7de571c 100644 --- a/charms/reactive/decorators.py +++ b/charms/reactive/decorators.py @@ -21,6 +21,7 @@ from charmhelpers.core import hookenv from charms.reactive.bus import Handler from charms.reactive.bus import get_states from charms.reactive.bus import _action_id +from charms.reactive.bus import _short_action_id from charms.reactive.relations import RelationBase from charms.reactive.helpers import _hook from charms.reactive.helpers import _when_all @@ -188,19 +189,21 @@ def not_unless(*desired_states): This is primarily for informational purposes and as a guard clause. """ def _decorator(func): + action_id = _action_id(func) + short_action_id = _short_action_id(func) + @wraps(func) def _wrapped(*args, **kwargs): active_states = get_states() missing_states = [state for state in desired_states if state not in active_states] if missing_states: - func_id = "%s:%s:%s" % (func.__code__.co_filename, - func.__code__.co_firstlineno, - func.__code__.co_name) hookenv.log('%s called before state%s: %s' % ( - func_id, + short_action_id, 's' if len(missing_states) > 1 else '', ', '.join(missing_states)), hookenv.WARNING) return func(*args, **kwargs) + _wrapped._action_id = action_id + _wrapped._short_action_id = short_action_id return _wrapped return _decorator
Incorrect handler name logged using not_unless decorator I'm getting the following in my logs: 2016-01-11 14:58:37 INFO juju-log replication:1: Invoking reactive handler: lib/pypi/charms/reactive/decorators.py:149:_wrapped It looks like a name isn't being copied from the wrapped function in the not_unless decorator
juju-solutions/charms.reactive
diff --git a/tests/test_decorators.py b/tests/test_decorators.py index 4691a30..78733c7 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -236,6 +236,10 @@ class TestReactiveDecorators(unittest.TestCase): self.assertEqual(action.call_count, 3) assert log_msg(0).endswith('test called before states: foo, bar'), log_msg(0) assert log_msg(1).endswith('test called before state: bar'), log_msg(1) + self.assertIn('tests/test_decorators.py:', reactive.bus._action_id(test)) + self.assertIn(':test', reactive.bus._action_id(test)) + self.assertIn('tests/test_decorators.py:', reactive.bus._short_action_id(test)) + self.assertIn(':test', reactive.bus._short_action_id(test)) def test_only_once(self): calls = []
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "flake8", "ipython", "ipdb", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backcall==0.2.0 certifi==2021.5.30 charmhelpers==1.2.1 -e git+https://github.com/juju-solutions/charms.reactive.git@04663e45f3683d4c497f43526d3ac26593ee10a2#egg=charms.reactive coverage==6.2 decorator==5.1.1 flake8==5.0.4 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 ipdb==0.13.13 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 MarkupSafe==2.0.1 mccabe==0.7.0 mock==5.2.0 netaddr==0.10.1 nose==1.3.7 packaging==21.3 parso==0.7.1 pbr==6.1.1 pexpect==4.9.0 pickleshare==0.7.5 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pyaml==23.5.8 pycodestyle==2.9.1 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 tomli==1.2.3 traitlets==4.3.3 typing_extensions==4.1.1 wcwidth==0.2.13 zipp==3.6.0
name: charms.reactive channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backcall==0.2.0 - charmhelpers==1.2.1 - coverage==6.2 - decorator==5.1.1 - flake8==5.0.4 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - ipdb==0.13.13 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - markupsafe==2.0.1 - mccabe==0.7.0 - mock==5.2.0 - netaddr==0.10.1 - nose==1.3.7 - packaging==21.3 - parso==0.7.1 - pbr==6.1.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pyaml==23.5.8 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - traitlets==4.3.3 - typing-extensions==4.1.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/charms.reactive
[ "tests/test_decorators.py::TestReactiveDecorators::test_not_unless" ]
[]
[ "tests/test_decorators.py::TestReactiveDecorators::test_hook", "tests/test_decorators.py::TestReactiveDecorators::test_multi", "tests/test_decorators.py::TestReactiveDecorators::test_only_once", "tests/test_decorators.py::TestReactiveDecorators::test_when", "tests/test_decorators.py::TestReactiveDecorators::test_when_all", "tests/test_decorators.py::TestReactiveDecorators::test_when_any", "tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed", "tests/test_decorators.py::TestReactiveDecorators::test_when_none", "tests/test_decorators.py::TestReactiveDecorators::test_when_not", "tests/test_decorators.py::TestReactiveDecorators::test_when_not_all" ]
[]
Apache License 2.0
588
cdent__gabbi-157
1b9a0be830dac86865bee85c33886d3b2fb4d37b
2016-06-16 12:05:42
1b9a0be830dac86865bee85c33886d3b2fb4d37b
diff --git a/gabbi/driver.py b/gabbi/driver.py index 9cb88fe..22a48c4 100644 --- a/gabbi/driver.py +++ b/gabbi/driver.py @@ -29,8 +29,10 @@ import os import unittest from unittest import suite import uuid +import warnings from gabbi import case +from gabbi import exception from gabbi import handlers from gabbi import reporter from gabbi import suitemaker @@ -83,6 +85,10 @@ def build_tests(path, loader, host=None, port=8001, intercept=None, top_suite = suite.TestSuite() for test_file in glob.iglob('%s/*.yaml' % path): + if '_' in os.path.basename(test_file): + warnings.warn(exception.GabbiSyntaxWarning( + "'_' in test filename %s. This can break suite grouping." + % test_file)) if intercept: host = str(uuid.uuid4()) suite_dict = utils.load_yaml(yaml_file=test_file) @@ -134,7 +140,6 @@ def py_test_generator(test_dir, host=None, port=8001, intercept=None, def test_suite_from_yaml(loader, test_base_name, test_yaml, test_directory, host, port, fixture_module, intercept, prefix=''): """Legacy wrapper retained for backwards compatibility.""" - import warnings with warnings.catch_warnings(): # ensures warnings filter is restored warnings.simplefilter('default', DeprecationWarning) diff --git a/gabbi/exception.py b/gabbi/exception.py index 3d4ef45..2bc93e4 100644 --- a/gabbi/exception.py +++ b/gabbi/exception.py @@ -16,3 +16,8 @@ class GabbiFormatError(ValueError): """An exception to encapsulate poorly formed test data.""" pass + + +class GabbiSyntaxWarning(SyntaxWarning): + """A warning about syntax that is not desirable.""" + pass
Q: What characters are legal / recommended for test name in YAML? I suspect plain alphanum + spaces is recommended, but I might sometimes want to do hyphen or parens. So, just being thorough. Thanks!
cdent/gabbi
diff --git a/gabbi/tests/gabbits_intercept/json_extensions.yaml b/gabbi/tests/gabbits_intercept/json-extensions.yaml similarity index 100% rename from gabbi/tests/gabbits_intercept/json_extensions.yaml rename to gabbi/tests/gabbits_intercept/json-extensions.yaml diff --git a/gabbi/tests/gabbits_intercept/last_url.yaml b/gabbi/tests/gabbits_intercept/last-url.yaml similarity index 100% rename from gabbi/tests/gabbits_intercept/last_url.yaml rename to gabbi/tests/gabbits_intercept/last-url.yaml diff --git a/gabbi/tests/gabbits_intercept/method_shortcut.yaml b/gabbi/tests/gabbits_intercept/method-shortcut.yaml similarity index 100% rename from gabbi/tests/gabbits_intercept/method_shortcut.yaml rename to gabbi/tests/gabbits_intercept/method-shortcut.yaml diff --git a/gabbi/tests/test_syntax_warning.py b/gabbi/tests/test_syntax_warning.py new file mode 100644 index 0000000..529dbf6 --- /dev/null +++ b/gabbi/tests/test_syntax_warning.py @@ -0,0 +1,41 @@ +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +"""Test that the driver warns on bad yaml name.""" + +import os +import unittest +import warnings + +from gabbi import driver +from gabbi import exception + + +TESTS_DIR = 'warning_gabbits' + + +class DriverTest(unittest.TestCase): + + def setUp(self): + super(DriverTest, self).setUp() + self.loader = unittest.defaultTestLoader + self.test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR) + + def test_driver_warngs_on_files(self): + with warnings.catch_warnings(record=True) as the_warnings: + driver.build_tests( + self.test_dir, self.loader, host='localhost', port=8001) + self.assertEqual(1, len(the_warnings)) + the_warning = the_warnings[-1] + self.assertEqual( + the_warning.category, exception.GabbiSyntaxWarning) + self.assertIn("'_' in test filename", str(the_warning.message)) diff --git a/gabbi/tests/warning_gabbits/underscore_sample.yaml b/gabbi/tests/warning_gabbits/underscore_sample.yaml new file mode 100644 index 0000000..185e378 --- /dev/null +++ b/gabbi/tests/warning_gabbits/underscore_sample.yaml @@ -0,0 +1,6 @@ + +tests: + - name: one + url: / + - name: two + url: http://example.com/moo
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 2 }
1.22
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mock", "testrepository", "coverage", "hacking", "sphinx", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 colorama==0.4.5 coverage==6.2 decorator==5.1.1 docutils==0.18.1 extras==1.0.0 fixtures==4.0.1 flake8==3.8.4 -e git+https://github.com/cdent/gabbi.git@1b9a0be830dac86865bee85c33886d3b2fb4d37b#egg=gabbi hacking==4.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 iso8601==1.1.0 Jinja2==3.0.3 jsonpath-rw==1.4.0 jsonpath-rw-ext==1.2.2 MarkupSafe==2.0.1 mccabe==0.6.1 mock==5.2.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 ply==3.11 py==1.11.0 pycodestyle==2.6.0 pyflakes==2.2.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 python-subunit==1.4.2 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testrepository==0.0.21 testtools==2.6.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 wsgi_intercept==1.13.1 zipp==3.6.0
name: gabbi channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - colorama==0.4.5 - coverage==6.2 - decorator==5.1.1 - docutils==0.18.1 - extras==1.0.0 - fixtures==4.0.1 - flake8==3.8.4 - hacking==4.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - iso8601==1.1.0 - jinja2==3.0.3 - jsonpath-rw==1.4.0 - jsonpath-rw-ext==1.2.2 - markupsafe==2.0.1 - mccabe==0.6.1 - mock==5.2.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - ply==3.11 - py==1.11.0 - pycodestyle==2.6.0 - pyflakes==2.2.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-subunit==1.4.2 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testrepository==0.0.21 - testtools==2.6.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wsgi-intercept==1.13.1 - zipp==3.6.0 prefix: /opt/conda/envs/gabbi
[ "gabbi/tests/test_syntax_warning.py::DriverTest::test_driver_warngs_on_files" ]
[]
[]
[]
Apache License 2.0
589
box__box-python-sdk-139
a1dba2d7699f6d3e798e89821d4650720e299ffd
2016-06-16 15:45:59
ded623f4b6de0530d8f983d3c3d2cafe646c126b
boxcla: Hi @kelseymorris95, thanks for the pull request. Before we can merge it, we need you to sign our Contributor License Agreement. You can do so electronically here: http://opensource.box.com/cla Once you have signed, just add a comment to this pull request saying, "CLA signed". Thanks! kelseymorris95: CLA signed boxcla: Verified that @kelseymorris95 has just signed the CLA. Thanks, and we look forward to your contribution. jmoldow: Something to think about: `Translator.translate()` takes a type, and tries to translate it. If it fails, it'll return `BaseObject`. Then, the usual procedure is to pass `session, object_id, response_object` to the class that is returned. This has two problems: - Ideally, the default return value would be either `BaseObject` or `APIJSONObject`, depending on the object. I would choose `BaseObject` if there were an `id`, and `APIJSONObject` otherwise. However, we can't do that since the method only accepts type. We'd need to make a backwards-incompatible change to make it accept additional information. - The types of classes we return have different `__init__` parameters. So you can't initialize an object unless you know in advance which type it's going to be. We could fix this by: - Moving the object creation inside of `Translator.translate()` (after dealing with the above problem). - Making `APIJSONObject.__init__` have the same argument list as `BaseObject.__init__`, even though it doesn't need most of them. Let's not worry about this right now. What we have now works well enough to push what you have as-is. But we'll want to revisit this before or during work on #140. HootyMcOwlface: :+1: jmoldow: 👍 Thanks @kelseymorris95 ! This all looks great. I'm going to merge it now. Before releasing this to PyPI, over the next few days, let's make sure we're happy with the names of the new classes, make a final decision about `Mapping` vs `MutableMapping` vs `dict`, and double-check that we aren't introducing any other backwards incompatibilities.
diff --git a/boxsdk/object/__init__.py b/boxsdk/object/__init__.py index ffd3611..e4fdb61 100644 --- a/boxsdk/object/__init__.py +++ b/boxsdk/object/__init__.py @@ -5,4 +5,4 @@ from six.moves import map # pylint:disable=redefined-builtin -__all__ = list(map(str, ['collaboration', 'events', 'file', 'folder', 'group', 'group_membership', 'search', 'user'])) +__all__ = list(map(str, ['collaboration', 'events', 'event', 'file', 'folder', 'group', 'group_membership', 'search', 'user'])) diff --git a/boxsdk/object/api_json_object.py b/boxsdk/object/api_json_object.py new file mode 100644 index 0000000..e407b1c --- /dev/null +++ b/boxsdk/object/api_json_object.py @@ -0,0 +1,26 @@ +# coding: utf-8 + +from __future__ import unicode_literals, absolute_import +from collections import Mapping +from abc import ABCMeta +import six + +from .base_api_json_object import BaseAPIJSONObject, BaseAPIJSONObjectMeta + + +class APIJSONObjectMeta(BaseAPIJSONObjectMeta, ABCMeta): + """ + Avoid conflicting metaclass definitions for APIJSONObject. + http://code.activestate.com/recipes/204197-solving-the-metaclass-conflict/ + """ + pass + + +class APIJSONObject(six.with_metaclass(APIJSONObjectMeta, BaseAPIJSONObject, Mapping)): + """Class representing objects that are not part of the REST API.""" + + def __len__(self): + return len(self._response_object) + + def __iter__(self): + return iter(self._response_object) diff --git a/boxsdk/object/base_api_json_object.py b/boxsdk/object/base_api_json_object.py new file mode 100644 index 0000000..8dbacde --- /dev/null +++ b/boxsdk/object/base_api_json_object.py @@ -0,0 +1,63 @@ +# coding: utf-8 + +from __future__ import unicode_literals, absolute_import +import six + +from ..util.translator import Translator + + +class BaseAPIJSONObjectMeta(type): + """ + Metaclass for Box API objects. Registers classes so that API responses can be translated to the correct type. + Relies on the _item_type field defined on the classes to match the type property of the response json. + But the type-class mapping will only be registered if the module of the class is imported. + So it's also important to add the module name to __all__ in object/__init__.py. + """ + def __init__(cls, name, bases, attrs): + super(BaseAPIJSONObjectMeta, cls).__init__(name, bases, attrs) + item_type = attrs.get('_item_type', None) + if item_type is not None: + Translator().register(item_type, cls) + + [email protected]_metaclass(BaseAPIJSONObjectMeta) +class BaseAPIJSONObject(object): + """Base class containing basic logic shared between true REST objects and other objects (such as an Event)""" + + _item_type = None + + def __init__(self, response_object=None, **kwargs): + """ + :param response_object: + A JSON object representing the object returned from a Box API request. + :type response_object: + `dict` + """ + super(BaseAPIJSONObject, self).__init__(**kwargs) + self._response_object = response_object or {} + self.__dict__.update(self._response_object) + + def __getitem__(self, item): + """ + Try to get the attribute from the API response object. + + :param item: + The attribute to retrieve from the API response object. + :type item: + `unicode` + """ + return self._response_object[item] + + def __repr__(self): + """Base class override. Return a human-readable representation using the Box ID or name of the object.""" + extra_description = ' - {0}'.format(self._description) if self._description else '' + description = '<Box {0}{1}>'.format(self.__class__.__name__, extra_description) + if six.PY2: + return description.encode('utf-8') + else: + return description + + @property + def _description(self): + """Return a description of the object if one exists.""" + return "" diff --git a/boxsdk/object/base_endpoint.py b/boxsdk/object/base_endpoint.py index 76b0ffe..d24d8ca 100644 --- a/boxsdk/object/base_endpoint.py +++ b/boxsdk/object/base_endpoint.py @@ -1,19 +1,23 @@ # coding: utf-8 -from __future__ import unicode_literals +from __future__ import unicode_literals, absolute_import class BaseEndpoint(object): """A Box API endpoint.""" - def __init__(self, session): + def __init__(self, session, **kwargs): """ - :param session: The Box session used to make requests. :type session: :class:`BoxSession` + :param kwargs: + Keyword arguments for base class constructors. + :type kwargs: + `dict` """ + super(BaseEndpoint, self).__init__(**kwargs) self._session = session def get_url(self, endpoint, *args): diff --git a/boxsdk/object/base_object.py b/boxsdk/object/base_object.py index 3fe1d8b..5823222 100644 --- a/boxsdk/object/base_object.py +++ b/boxsdk/object/base_object.py @@ -1,35 +1,15 @@ # coding: utf-8 -from __future__ import unicode_literals -from abc import ABCMeta +from __future__ import unicode_literals, absolute_import import json -import six +from .base_endpoint import BaseEndpoint +from .base_api_json_object import BaseAPIJSONObject +from ..util.translator import Translator -from boxsdk.object.base_endpoint import BaseEndpoint -from boxsdk.util.translator import Translator - -class ObjectMeta(ABCMeta): - """ - Metaclass for Box API objects. Registers classes so that API responses can be translated to the correct type. - Relies on the _item_type field defined on the classes to match the type property of the response json. - But the type-class mapping will only be registered if the module of the class is imported. - So it's also important to add the module name to __all__ in object/__init__.py. - """ - def __init__(cls, name, bases, attrs): - super(ObjectMeta, cls).__init__(name, bases, attrs) - item_type = attrs.get('_item_type', None) - if item_type is not None: - Translator().register(item_type, cls) - - [email protected]_metaclass(ObjectMeta) -class BaseObject(BaseEndpoint): - """ - A Box API endpoint for interacting with a Box object. - """ - _item_type = None +class BaseObject(BaseEndpoint, BaseAPIJSONObject): + """A Box API endpoint for interacting with a Box object.""" def __init__(self, session, object_id, response_object=None): """ @@ -42,29 +22,16 @@ def __init__(self, session, object_id, response_object=None): :type object_id: `unicode` :param response_object: - The Box API response representing the object. + A JSON object representing the object returned from a Box API request. :type response_object: - :class:`BoxResponse` + `dict` """ - super(BaseObject, self).__init__(session) + super(BaseObject, self).__init__(session=session, response_object=response_object) self._object_id = object_id - self._response_object = response_object or {} - self.__dict__.update(self._response_object) - - def __getitem__(self, item): - """Base class override. Try to get the attribute from the API response object.""" - return self._response_object[item] - - def __repr__(self): - """Base class override. Return a human-readable representation using the Box ID or name of the object.""" - description = '<Box {0} - {1}>'.format(self.__class__.__name__, self._description) - if six.PY2: - return description.encode('utf-8') - else: - return description @property def _description(self): + """Base class override. Return a description for the object.""" if 'name' in self._response_object: return '{0} ({1})'.format(self._object_id, self.name) # pylint:disable=no-member else: @@ -185,7 +152,7 @@ def delete(self, params=None, headers=None): return box_response.ok def __eq__(self, other): - """Base class override. Equality is determined by object id.""" + """Equality as determined by object id""" return self._object_id == other.object_id def _paging_wrapper(self, url, starting_index, limit, factory=None): diff --git a/boxsdk/object/event.py b/boxsdk/object/event.py new file mode 100644 index 0000000..8025d80 --- /dev/null +++ b/boxsdk/object/event.py @@ -0,0 +1,11 @@ +# coding: utf-8 + +from __future__ import unicode_literals, absolute_import + +from .api_json_object import APIJSONObject + + +class Event(APIJSONObject): + """Represents a single Box event.""" + + _item_type = 'event' diff --git a/boxsdk/object/events.py b/boxsdk/object/events.py index dbb321f..3d62b43 100644 --- a/boxsdk/object/events.py +++ b/boxsdk/object/events.py @@ -1,14 +1,14 @@ # coding: utf-8 -from __future__ import unicode_literals - +from __future__ import unicode_literals, absolute_import from requests.exceptions import Timeout from six import with_metaclass -from boxsdk.object.base_endpoint import BaseEndpoint -from boxsdk.util.enum import ExtendableEnumMeta -from boxsdk.util.lru_cache import LRUCache -from boxsdk.util.text_enum import TextEnum +from .base_endpoint import BaseEndpoint +from ..util.enum import ExtendableEnumMeta +from ..util.lru_cache import LRUCache +from ..util.text_enum import TextEnum +from ..util.translator import Translator # pylint:disable=too-many-ancestors @@ -79,8 +79,7 @@ def get_events(self, limit=100, stream_position=0, stream_type=UserEventsStreamT :type stream_type: :enum:`EventsStreamType` :returns: - JSON response from the Box /events endpoint. Contains the next stream position to use for the next call, - along with some number of events. + Dictionary containing the next stream position along with a list of some number of events. :rtype: `dict` """ @@ -91,7 +90,10 @@ def get_events(self, limit=100, stream_position=0, stream_type=UserEventsStreamT 'stream_type': stream_type, } box_response = self._session.get(url, params=params) - return box_response.json() + response = box_response.json().copy() + if 'entries' in response: + response['entries'] = [Translator().translate(item['type'])(item) for item in response['entries']] + return response def get_latest_stream_position(self, stream_type=UserEventsStreamType.ALL): """ diff --git a/boxsdk/object/folder.py b/boxsdk/object/folder.py index 3aaf1c2..db07b60 100644 --- a/boxsdk/object/folder.py +++ b/boxsdk/object/folder.py @@ -4,6 +4,7 @@ import json import os from six import text_type + from boxsdk.config import API from boxsdk.object.collaboration import Collaboration from boxsdk.object.file import File diff --git a/boxsdk/object/item.py b/boxsdk/object/item.py index cc885af..d0d99cd 100644 --- a/boxsdk/object/item.py +++ b/boxsdk/object/item.py @@ -1,7 +1,6 @@ # coding: utf-8 -from __future__ import unicode_literals - +from __future__ import unicode_literals, absolute_import import json from .base_object import BaseObject @@ -111,6 +110,10 @@ def rename(self, name): def get(self, fields=None, etag=None): """Base class override. + :param fields: + List of fields to request. + :type fields: + `Iterable` of `unicode` :param etag: If specified, instruct the Box API to get the info only if the current version's etag doesn't match. :type etag: diff --git a/boxsdk/object/metadata.py b/boxsdk/object/metadata.py index 9c3fed0..7d5adee 100644 --- a/boxsdk/object/metadata.py +++ b/boxsdk/object/metadata.py @@ -1,6 +1,6 @@ # coding: utf-8 -from __future__ import unicode_literals +from __future__ import unicode_literals, absolute_import import json from boxsdk.object.base_endpoint import BaseEndpoint
Add an Event class Right now `get_events()` method in the `Events` class returns a `dict`. Ideally, we should have an `Event` class, and `Event` objects can also be translated. So `Events.get_events()` call will return a list of `Event` objects.
box/box-python-sdk
diff --git a/test/functional/test_events.py b/test/functional/test_events.py index b0ccd49..590682d 100644 --- a/test/functional/test_events.py +++ b/test/functional/test_events.py @@ -8,6 +8,7 @@ import requests from boxsdk.object.folder import FolderSyncState +from boxsdk.object.event import Event as BoxEvent @pytest.fixture @@ -36,6 +37,7 @@ def helper(get_item, event_type, stream_position=0): assert event['event_type'] == event_type assert event['source']['name'] == item.name assert event['source']['id'] == item.id + assert isinstance(event, BoxEvent) return helper diff --git a/test/unit/object/test_api_json_object.py b/test/unit/object/test_api_json_object.py new file mode 100644 index 0000000..1be04ef --- /dev/null +++ b/test/unit/object/test_api_json_object.py @@ -0,0 +1,21 @@ +# coding: utf-8 + +from __future__ import unicode_literals, absolute_import +import pytest + +from boxsdk.object.api_json_object import APIJSONObject + + [email protected](params=[{'foo': 'bar'}, {'a': {'b': 'c'}}]) +def api_json_object(request): + return request.param, APIJSONObject(request.param) + + +def test_len(api_json_object): + dictionary, test_object = api_json_object + assert len(dictionary) == len(test_object) + + +def test_api_json_object_dict(api_json_object): + dictionary, test_object = api_json_object + assert dictionary == test_object diff --git a/test/unit/object/test_base_api_json_object.py b/test/unit/object/test_base_api_json_object.py new file mode 100644 index 0000000..3032f11 --- /dev/null +++ b/test/unit/object/test_base_api_json_object.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +from __future__ import unicode_literals, absolute_import +import pytest + +from boxsdk.object.base_api_json_object import BaseAPIJSONObject + + [email protected](params=[{'foo': 'bar'}, {'a': {'b': 'c'}}]) +def response(request): + return request.param + + [email protected]() +def base_api_json_object(response): + dictionary_response = response + return dictionary_response, BaseAPIJSONObject(dictionary_response) + + +def test_getitem(base_api_json_object): + dictionary_response, test_object = base_api_json_object + assert isinstance(test_object, BaseAPIJSONObject) + for key in dictionary_response: + assert test_object[key] == dictionary_response[key] diff --git a/test/unit/object/test_event.py b/test/unit/object/test_event.py new file mode 100644 index 0000000..1c4cd2e --- /dev/null +++ b/test/unit/object/test_event.py @@ -0,0 +1,20 @@ +# coding: utf-8 + +from __future__ import unicode_literals + +from boxsdk.object.event import Event + + +def test_init_event(): + event = Event( + { + "type": "event", + "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", + "source": + { + "type": "folder", + "id": "11446498", + }, + }) + assert event['type'] == 'event' + assert event['event_id'] == 'f82c3ba03e41f7e8a7608363cc6c0390183c3f83' diff --git a/test/unit/object/test_events.py b/test/unit/object/test_events.py index bf45687..ff6c88e 100644 --- a/test/unit/object/test_events.py +++ b/test/unit/object/test_events.py @@ -1,6 +1,6 @@ # coding: utf-8 -from __future__ import unicode_literals +from __future__ import unicode_literals, absolute_import from itertools import chain import json @@ -13,6 +13,7 @@ from boxsdk.network.default_network import DefaultNetworkResponse from boxsdk.object.events import Events, EventsStreamType, UserEventsStreamType +from boxsdk.object.event import Event from boxsdk.session.box_session import BoxResponse from boxsdk.util.ordered_dict import OrderedDict @@ -169,22 +170,22 @@ def max_retries_long_poll_response(make_mock_box_request): @pytest.fixture() -def mock_event(): +def mock_event_json(): return { "type": "event", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "source": { "type": "folder", "id": "11446498", - } + }, } @pytest.fixture() -def events_response(initial_stream_position, mock_event, make_mock_box_request): +def events_response(initial_stream_position, mock_event_json, make_mock_box_request): # pylint:disable=redefined-outer-name mock_box_response, _ = make_mock_box_request( - response={"next_stream_position": initial_stream_position, "entries": [mock_event]}, + response={"next_stream_position": initial_stream_position, "entries": [mock_event_json]}, ) return mock_box_response @@ -205,6 +206,10 @@ def test_get_events( expected_url, params=dict(limit=100, stream_position=0, **expected_stream_type_params), ) + event_entries = events['entries'] + assert event_entries == events_response.json.return_value['entries'] + for event in event_entries: + assert isinstance(event, Event) def test_get_long_poll_options( @@ -234,7 +239,7 @@ def test_generate_events_with_long_polling( new_change_long_poll_response, reconnect_long_poll_response, max_retries_long_poll_response, - mock_event, + mock_event_json, stream_type_kwargs, expected_stream_type, expected_stream_type_params, @@ -253,7 +258,7 @@ def test_generate_events_with_long_polling( empty_events_response, ] events = test_events.generate_events_with_long_polling(**stream_type_kwargs) - assert next(events) == mock_event + assert next(events) == Event(mock_event_json) with pytest.raises(StopIteration): next(events) events.close()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 7 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt", "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 astroid==3.3.9 async-timeout==5.0.1 babel==2.17.0 bottle==0.13.2 -e git+https://github.com/box/box-python-sdk.git@a1dba2d7699f6d3e798e89821d4650720e299ffd#egg=boxsdk cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 chardet==5.2.0 charset-normalizer==3.4.1 colorama==0.4.6 coverage==7.8.0 cryptography==44.0.2 dill==0.3.9 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 greenlet==3.1.1 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 isort==6.0.1 Jinja2==3.1.6 jsonpatch==1.33 jsonpointer==3.0.0 MarkupSafe==3.0.2 mccabe==0.7.0 mock==5.2.0 packaging==24.2 pep8==1.7.1 platformdirs==4.3.7 pluggy==1.5.0 pycparser==2.22 Pygments==2.19.1 PyJWT==2.10.1 pylint==3.3.6 pyproject-api==1.9.0 pytest==8.3.5 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 redis==5.2.1 requests==2.32.3 requests-toolbelt==1.0.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 SQLAlchemy==2.0.40 tomli==2.2.1 tomlkit==0.13.2 tox==4.25.0 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 zipp==3.21.0
name: box-python-sdk channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - astroid==3.3.9 - async-timeout==5.0.1 - babel==2.17.0 - bottle==0.13.2 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - chardet==5.2.0 - charset-normalizer==3.4.1 - colorama==0.4.6 - coverage==7.8.0 - cryptography==44.0.2 - dill==0.3.9 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - greenlet==3.1.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - isort==6.0.1 - jinja2==3.1.6 - jsonpatch==1.33 - jsonpointer==3.0.0 - markupsafe==3.0.2 - mccabe==0.7.0 - mock==5.2.0 - packaging==24.2 - pep8==1.7.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pycparser==2.22 - pygments==2.19.1 - pyjwt==2.10.1 - pylint==3.3.6 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - redis==5.2.1 - requests==2.32.3 - requests-toolbelt==1.0.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - sqlalchemy==2.0.40 - tomli==2.2.1 - tomlkit==0.13.2 - tox==4.25.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/box-python-sdk
[ "test/unit/object/test_api_json_object.py::test_len[api_json_object0]", "test/unit/object/test_api_json_object.py::test_len[api_json_object1]", "test/unit/object/test_api_json_object.py::test_api_json_object_dict[api_json_object0]", "test/unit/object/test_api_json_object.py::test_api_json_object_dict[api_json_object1]", "test/unit/object/test_base_api_json_object.py::test_getitem[response0]", "test/unit/object/test_base_api_json_object.py::test_getitem[response1]", "test/unit/object/test_event.py::test_init_event", "test/unit/object/test_events.py::test_events_stream_type_extended_enum_class_has_expected_members", "test/unit/object/test_events.py::test_get_events[None]", "test/unit/object/test_events.py::test_get_long_poll_options[None]", "test/unit/object/test_events.py::test_get_events[all0]", "test/unit/object/test_events.py::test_get_long_poll_options[all0]", "test/unit/object/test_events.py::test_get_events[changes0]", "test/unit/object/test_events.py::test_get_long_poll_options[changes0]", "test/unit/object/test_events.py::test_get_events[sync0]", "test/unit/object/test_events.py::test_get_long_poll_options[sync0]", "test/unit/object/test_events.py::test_get_events[admin_logs0]", "test/unit/object/test_events.py::test_get_long_poll_options[admin_logs0]", "test/unit/object/test_events.py::test_get_events[all1]", "test/unit/object/test_events.py::test_get_long_poll_options[all1]", "test/unit/object/test_events.py::test_get_events[changes1]", "test/unit/object/test_events.py::test_get_long_poll_options[changes1]", "test/unit/object/test_events.py::test_get_events[sync1]", "test/unit/object/test_events.py::test_get_long_poll_options[sync1]", "test/unit/object/test_events.py::test_get_events[admin_logs1]", "test/unit/object/test_events.py::test_get_long_poll_options[admin_logs1]", "test/unit/object/test_events.py::test_get_events[future_stream_type]", "test/unit/object/test_events.py::test_get_long_poll_options[future_stream_type]" ]
[ "test/unit/object/test_events.py::test_generate_events_with_long_polling[None]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[all0]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[changes0]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[sync0]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[admin_logs0]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[all1]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[changes1]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[sync1]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[admin_logs1]", "test/unit/object/test_events.py::test_generate_events_with_long_polling[future_stream_type]" ]
[]
[]
Apache License 2.0
590
Tiendil__pynames-15
bc496f64be0da44db0882b74b54125ce2e5e556b
2016-06-17 08:36:12
bc496f64be0da44db0882b74b54125ce2e5e556b
diff --git a/helpers/merge_names.py b/helpers/merge_names.py index b4628a9..a282df3 100644 --- a/helpers/merge_names.py +++ b/helpers/merge_names.py @@ -3,6 +3,8 @@ import os import json +import six + FIXTURES = ['mongolian/fixtures/mongolian_names_list.json', 'russian/fixtures/pagan_names_list.json', @@ -27,8 +29,8 @@ def names_equal(name, original_name): if language not in original_languages: continue - text = languages[language] if isinstance(languages[language], basestring) else languages[language][0] - original_text = original_languages[language] if isinstance(original_languages[language], basestring) else original_languages[language][0] + text = languages[language] if isinstance(languages[language], six.string_types) else languages[language][0] + original_text = original_languages[language] if isinstance(original_languages[language], six.string_types) else original_languages[language][0] if text == original_text: return True @@ -37,8 +39,8 @@ def names_equal(name, original_name): def merge_names(name, original_name): - for gender, languages in name['genders'].iteritems(): - for language, data in languages.iteritems(): + for gender, languages in six.iteritems(name['genders']): + for language, data in six.iteritems(languages): original_name['genders'][gender][language] = data @@ -54,7 +56,7 @@ def pretty_dump(data): content = [] content.append(u'{') - for key, value in data.iteritems(): + for key, value in six.iteritems(data): if key != 'names': content.append(u' "%s": %s,' % (key, json.dumps(value, ensure_ascii=False))) diff --git a/pynames/exceptions.py b/pynames/exceptions.py index 48d5de7..16bbfb2 100644 --- a/pynames/exceptions.py +++ b/pynames/exceptions.py @@ -1,5 +1,7 @@ # coding: utf-8 +from __future__ import unicode_literals + class PynamesError(Exception): MSG = None @@ -9,7 +11,7 @@ class PynamesError(Exception): class NoDefaultNameValue(PynamesError): - MSG = u'Name: can not get default value for name with data: %(raw_data)r' + MSG = 'Name: can not get default value for name with data: %(raw_data)r' class FromListGeneratorError(PynamesError): @@ -17,7 +19,7 @@ class FromListGeneratorError(PynamesError): class NoNamesLoadedFromListError(FromListGeneratorError): - MSG = u'no names loaded from "%(source)s"' + MSG = 'no names loaded from "%(source)s"' class FromTablesGeneratorError(PynamesError): @@ -25,11 +27,11 @@ class FromTablesGeneratorError(PynamesError): class WrongTemplateStructureError(FromTablesGeneratorError): - MSG = u'wrong template structure - cannot choose template for genders %(genders)r with template source: "%(source)s"' + MSG = 'wrong template structure - cannot choose template for genders %(genders)r with template source: "%(source)s"' class NotEqualFormsLengths(FromTablesGeneratorError): - MSG = u'not equal forms lengths: [%(left)r] and [%(right)r]' + MSG = 'not equal forms lengths: [%(left)r] and [%(right)r]' class WrongCSVData(FromTablesGeneratorError): diff --git a/pynames/from_list_generator.py b/pynames/from_list_generator.py index 9875e38..996e214 100644 --- a/pynames/from_list_generator.py +++ b/pynames/from_list_generator.py @@ -1,4 +1,7 @@ # coding: utf-8 + +from __future__ import unicode_literals + import json import random diff --git a/pynames/from_tables_generator.py b/pynames/from_tables_generator.py index 7b68475..8688ec8 100644 --- a/pynames/from_tables_generator.py +++ b/pynames/from_tables_generator.py @@ -1,11 +1,14 @@ # coding: utf-8 +from __future__ import unicode_literals + # python lib: import json import random from collections import Iterable # thirdparties: +import six import unicodecsv # pynames: @@ -39,28 +42,28 @@ class Template(object): @classmethod def merge_forms(cls, left, right): - if not isinstance(left, basestring): - if not isinstance(right, basestring): + if not isinstance(left, six.string_types): + if not isinstance(right, six.string_types): if len(left) != len(right): raise exceptions.NotEqualFormsLengths(left=left, right=right) return [l+r for l, r in zip(left, right)] else: return [l+right for l in left] else: - if not isinstance(right, basestring): + if not isinstance(right, six.string_types): return [left+r for r in right] else: return left + right def get_name(self, tables): languages = dict( - (lang, u'') for lang in self.languages + (lang, '') for lang in self.languages ) for slug in self.template: record = random.choice(tables[slug]) languages = { lang: self.merge_forms(forms, record['languages'][lang]) - for lang, forms in languages.iteritems() + for lang, forms in six.iteritems(languages) } genders = dict( @@ -103,7 +106,7 @@ class FromTablesGenerator(BaseGenerator): raise NotImplementedError(error_msg) with file_adapter(source) as f: - data = json.load(f) + data = json.loads(f.read().decode('utf-8')) self.native_language = data['native_language'] self.languages = set(data['languages']) self.full_forms_for_languages = set(data.get('full_forms_for_languages', set())) @@ -153,7 +156,7 @@ class FromTablesGenerator(BaseGenerator): return name.get_for(gender, language) def test_names_consistency(self, test): - for table_name, table in self.tables.iteritems(): + for table_name, table in six.iteritems(self.tables): for record in table: test.assertEqual(set(record['languages'].keys()) & self.languages, self.languages) diff --git a/pynames/names.py b/pynames/names.py index 1fcf27d..d69a297 100644 --- a/pynames/names.py +++ b/pynames/names.py @@ -1,5 +1,9 @@ # coding: utf-8 +from __future__ import unicode_literals + +import six + from pynames.relations import GENDER, LANGUAGE from pynames import exceptions @@ -20,7 +24,7 @@ class Name(object): forms = self.translations[gender][language] - if not isinstance(forms, basestring): + if not isinstance(forms, six.string_types): return forms[0] return forms @@ -31,7 +35,7 @@ class Name(object): forms = self.translations[gender][language] - if not isinstance(forms, basestring): + if not isinstance(forms, six.string_types): return list(forms) return None diff --git a/pynames/relations.py b/pynames/relations.py index 3b2b5f3..f065488 100644 --- a/pynames/relations.py +++ b/pynames/relations.py @@ -1,5 +1,7 @@ # coding: utf-8 +from __future__ import unicode_literals + class GENDER: MALE = 'm' FEMALE = 'f' diff --git a/pynames/utils.py b/pynames/utils.py index b7865e8..0430487 100644 --- a/pynames/utils.py +++ b/pynames/utils.py @@ -1,5 +1,7 @@ # coding: utf-8 +from __future__ import unicode_literals + import contextlib import importlib import pkgutil @@ -54,6 +56,6 @@ def file_adapter(file_or_path): if is_file(file_or_path): file_obj = file_or_path else: - file_obj = open(file_or_path) + file_obj = open(file_or_path, 'rb') yield file_obj file_obj.close() diff --git a/setup.py b/setup.py index a5e70ad..eb2a544 100644 --- a/setup.py +++ b/setup.py @@ -22,12 +22,14 @@ setuptools.setup( 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', 'Natural Language :: English', 'Natural Language :: Russian'], keywords=['gamedev', 'game', 'game development', 'names', 'names generation'], packages=setuptools.find_packages(), - install_requires=['unicodecsv'], + install_requires=['six', 'unicodecsv'], include_package_data=True, test_suite = 'tests', )
Поддержка Python 3
Tiendil/pynames
diff --git a/pynames/tests/__init__.py b/pynames/tests/__init__.py index 91bd147..e69de29 100644 --- a/pynames/tests/__init__.py +++ b/pynames/tests/__init__.py @@ -1,7 +0,0 @@ -# coding: utf-8 - -from pynames.tests.test_name import * -from pynames.tests.test_from_list_generator import * -from pynames.tests.test_from_tables_generator import * -from pynames.tests.test_generators import * -from pynames.tests.test_utils import * diff --git a/pynames/tests/test_from_list_generator.py b/pynames/tests/test_from_list_generator.py index 35b7e10..3ffc28a 100644 --- a/pynames/tests/test_from_list_generator.py +++ b/pynames/tests/test_from_list_generator.py @@ -1,8 +1,12 @@ # coding: utf-8 +from __future__ import unicode_literals + import os import unittest +from six.moves import xrange + from pynames.relations import GENDER, LANGUAGE from pynames.from_list_generator import FromListGenerator diff --git a/pynames/tests/test_from_tables_generator.py b/pynames/tests/test_from_tables_generator.py index 52b07e7..b1aef3f 100644 --- a/pynames/tests/test_from_tables_generator.py +++ b/pynames/tests/test_from_tables_generator.py @@ -1,8 +1,13 @@ # coding: utf-8 +from __future__ import unicode_literals + import os import unittest +import six +from six.moves import xrange + from pynames.relations import GENDER, LANGUAGE from pynames.from_tables_generator import FromTablesGenerator, FromCSVTablesGenerator @@ -116,13 +121,9 @@ class TestFromCSVTablesGenerator(unittest.TestCase): csv_generator = self.TestCSVGenerator() for attr_name in ['native_language', 'languages', 'templates', 'tables']: - try: - json_attr = getattr(json_generator, attr_name) - csv_attr = getattr(csv_generator, attr_name) - if isinstance(json_attr, list): - self.assertItemsEqual(csv_attr, json_attr) - else: - self.assertEqual(csv_attr, json_attr) - except Exception: - from nose.tools import set_trace; set_trace() - raise + json_attr = getattr(json_generator, attr_name) + csv_attr = getattr(csv_generator, attr_name) + if isinstance(json_attr, list): + six.assertCountEqual(self, csv_attr, json_attr) + else: + self.assertEqual(csv_attr, json_attr) diff --git a/pynames/tests/test_name.py b/pynames/tests/test_name.py index 19182c0..0403736 100644 --- a/pynames/tests/test_name.py +++ b/pynames/tests/test_name.py @@ -1,5 +1,8 @@ # coding: utf-8 +from __future__ import unicode_literals + +import six import unittest from pynames.relations import GENDER, LANGUAGE @@ -10,7 +13,7 @@ class TestName(unittest.TestCase): def test_base(self): name = Name('ru', {'genders': {'m': {'ru': 'ru_name'}}}) - self.assertEqual(unicode(name), 'ru_name') + self.assertEqual(six.text_type(name), 'ru_name') self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.RU), 'ru_name') self.assertEqual(name.get_for(GENDER.MALE), 'ru_name') self.assertEqual(name.get_forms_for(GENDER.MALE), None) @@ -18,7 +21,7 @@ class TestName(unittest.TestCase): def test_genders(self): name = Name('ru', {'genders': {'m': {'ru': 'ru_m_name'}, 'f': {'ru': 'ru_f_name'}}}) - self.assertEqual(unicode(name), 'ru_m_name') + self.assertEqual(six.text_type(name), 'ru_m_name') self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.RU), 'ru_m_name') self.assertEqual(name.get_for(GENDER.FEMALE, LANGUAGE.RU), 'ru_f_name') @@ -27,7 +30,7 @@ class TestName(unittest.TestCase): 'en': 'en_m_name'}, 'f': {'ru': 'ru_f_name', 'en': 'en_f_name'}}}) - self.assertEqual(unicode(name), 'ru_m_name') + self.assertEqual(six.text_type(name), 'ru_m_name') self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.RU), 'ru_m_name') self.assertEqual(name.get_for(GENDER.FEMALE, LANGUAGE.RU), 'ru_f_name') self.assertEqual(name.get_for(GENDER.MALE, LANGUAGE.EN), 'en_m_name') diff --git a/pynames/tests/test_utils.py b/pynames/tests/test_utils.py index acab40a..a62aa06 100644 --- a/pynames/tests/test_utils.py +++ b/pynames/tests/test_utils.py @@ -1,5 +1,7 @@ # coding: utf-8 +from __future__ import unicode_literals + import os import tempfile import unittest
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 8 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "six" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/Tiendil/pynames.git@bc496f64be0da44db0882b74b54125ce2e5e556b#egg=Pynames pytest==8.3.5 six==1.17.0 tomli==2.2.1 unicodecsv==0.14.1
name: pynames channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 - unicodecsv==0.14.1 prefix: /opt/conda/envs/pynames
[ "pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_base", "pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_get_name__with_forms", "pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_get_name_simple", "pynames/tests/test_from_tables_generator.py::TestFromCSVTablesGenerator::test_init_state_equal", "pynames/tests/test_name.py::TestName::test_base", "pynames/tests/test_name.py::TestName::test_forms", "pynames/tests/test_name.py::TestName::test_genders", "pynames/tests/test_name.py::TestName::test_languages" ]
[ "pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_base", "pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_get_name__simple", "pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_get_name__with_forms", "pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_male_female_selection" ]
[ "pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_not_derived", "pynames/tests/test_from_list_generator.py::TestFromListGenerator::test_wrong_path", "pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_male_female_selection", "pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_not_derived", "pynames/tests/test_from_tables_generator.py::TestFromTablesGenerator::test_wrong_path", "pynames/tests/test_utils.py::TestName::test_file_adapter", "pynames/tests/test_utils.py::TestName::test_is_file", "pynames/tests/test_utils.py::TestName::test_is_file_on_django_files" ]
[]
BSD 3-Clause "New" or "Revised" License
591
Axelrod-Python__Axelrod-638
89651f45910f4b41a79c58358d9f5beca4197fc1
2016-06-19 20:45:17
89651f45910f4b41a79c58358d9f5beca4197fc1
diff --git a/axelrod/strategies/finite_state_machines.py b/axelrod/strategies/finite_state_machines.py index defc4770..1c231d43 100644 --- a/axelrod/strategies/finite_state_machines.py +++ b/axelrod/strategies/finite_state_machines.py @@ -54,6 +54,7 @@ class FSMPlayer(Player): initial_state = 1 initial_action = C Player.__init__(self) + self.initial_state = initial_state self.initial_action = initial_action self.fsm = SimpleFSM(transitions, initial_state) @@ -67,6 +68,10 @@ class FSMPlayer(Player): self.state = self.fsm.state return action + def reset(self): + Player.reset(self) + self.fsm.state = self.initial_state + class Fortress3(FSMPlayer): """Finite state machine player specified in DOI:10.1109/CEC.2006.1688322.
Finite state machine players don't reset properly ``` >>> import axelrod as axl >>> tft = axl.TitForTat() >>> predator = axl.Predator() >>> predator.fsm.state 1 >>> m = axl.Match((tft, predator), 2) >>> m.play() [('C', 'C'), ('C', 'D')] >>> predator.fsm.state 2 >>> predator.reset() >>> predator.fsm.state 2 ``` Stumbled on this working on #636 (writing a hypothesis strategy that contrite TfT reduces to TfT in 0 noise) so the above is reduced from seeing that when playing the same match again we get a different output: ``` >>> m = axl.Match((tft, predator), 2) >>> m.play() [('C', 'C'), ('C', 'C')] ``` Am going to work on a fix now and include a hypothesis test that checks that random deterministic matches give the same outcomes.
Axelrod-Python/Axelrod
diff --git a/axelrod/tests/integration/test_matches.py b/axelrod/tests/integration/test_matches.py new file mode 100644 index 00000000..b6241145 --- /dev/null +++ b/axelrod/tests/integration/test_matches.py @@ -0,0 +1,25 @@ +"""Tests for some expected match behaviours""" +import unittest +import axelrod + +from hypothesis import given +from hypothesis.strategies import integers +from axelrod.tests.property import strategy_lists + +C, D = axelrod.Actions.C, axelrod.Actions.D + +deterministic_strategies = [s for s in axelrod.ordinary_strategies + if not s().classifier['stochastic']] # Well behaved strategies + +class TestMatchOutcomes(unittest.TestCase): + + @given(strategies=strategy_lists(strategies=deterministic_strategies, + min_size=2, max_size=2), + turns=integers(min_value=1, max_value=20)) + def test_outcome_repeats(self, strategies, turns): + """A test that if we repeat 3 matches with deterministic and well + behaved strategies then we get the same result""" + players = [s() for s in strategies] + matches = [axelrod.Match(players, turns) for _ in range(3)] + self.assertEqual(matches[0].play(), matches[1].play()) + self.assertEqual(matches[1].play(), matches[2].play()) diff --git a/axelrod/tests/unit/test_finite_state_machines.py b/axelrod/tests/unit/test_finite_state_machines.py index 043834a1..d8147a59 100644 --- a/axelrod/tests/unit/test_finite_state_machines.py +++ b/axelrod/tests/unit/test_finite_state_machines.py @@ -111,6 +111,12 @@ class TestFSMPlayer(TestPlayer): fsm = player.fsm self.assertTrue(check_state_transitions(fsm.state_transitions)) + def test_reset_initial_state(self): + player = self.player() + player.fsm.state = -1 + player.reset() + self.assertFalse(player.fsm.state == -1) + class TestFortress3(TestFSMPlayer):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 -e git+https://github.com/Axelrod-Python/Axelrod.git@89651f45910f4b41a79c58358d9f5beca4197fc1#egg=Axelrod coverage==7.8.0 cycler==0.12.1 exceptiongroup==1.2.2 hypothesis==6.130.5 iniconfig==2.1.0 kiwisolver==1.4.7 matplotlib==3.3.4 numpy==2.0.2 packaging==24.2 pillow==11.1.0 pluggy==1.5.0 pyparsing==2.1.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 six==1.17.0 sortedcontainers==2.4.0 tomli==2.2.1 tqdm==3.4.0
name: Axelrod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - coverage==7.8.0 - cycler==0.12.1 - exceptiongroup==1.2.2 - hypothesis==6.130.5 - iniconfig==2.1.0 - kiwisolver==1.4.7 - matplotlib==3.3.4 - numpy==2.0.2 - packaging==24.2 - pillow==11.1.0 - pluggy==1.5.0 - pyparsing==2.1.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - six==1.17.0 - sortedcontainers==2.4.0 - tomli==2.2.1 - tqdm==3.4.0 prefix: /opt/conda/envs/Axelrod
[ "axelrod/tests/integration/test_matches.py::TestMatchOutcomes::test_outcome_repeats", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_reset_initial_state", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_reset_initial_state" ]
[]
[ "axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestPlayer::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_cooperator", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_defector", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_malformed_tables", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_tft", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayers::test_wsls", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestFSMPlayer::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestPredator::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestRaider::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestRipoff::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB1::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestSolutionB5::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_clone", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_initialisation", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_match_attributes", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_repr", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_reset", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_strategy", "axelrod/tests/unit/test_finite_state_machines.py::TestThumper::test_transitions", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsFortress3::test_rounds", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsTitForTat::test_rounds", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress3vsCooperator::test_rounds", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsFortress4::test_rounds", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsTitForTat::test_rounds", "axelrod/tests/unit/test_finite_state_machines.py::TestFortress4vsCooperator::test_rounds" ]
[]
MIT License
592
scrapy__scrapy-2065
d43a35735a062a4260b002cfbcd3236c77ef9399
2016-06-20 14:49:59
d7b26edf6b419e379a7a0a425093f02cac2fcf33
diff --git a/scrapy/utils/gz.py b/scrapy/utils/gz.py index cfb652143..afc7ed128 100644 --- a/scrapy/utils/gz.py +++ b/scrapy/utils/gz.py @@ -50,9 +50,12 @@ def gunzip(data): raise return output -_is_gzipped_re = re.compile(br'^application/(x-)?gzip\b', re.I) +_is_gzipped = re.compile(br'^application/(x-)?gzip\b', re.I).search +_is_octetstream = re.compile(br'^(application|binary)/octet-stream\b', re.I).search def is_gzipped(response): """Return True if the response is gzipped, or False otherwise""" ctype = response.headers.get('Content-Type', b'') - return _is_gzipped_re.search(ctype) is not None + cenc = response.headers.get('Content-Encoding', b'').lower() + return (_is_gzipped(ctype) or + (_is_octetstream(ctype) and cenc in (b'gzip', b'x-gzip')))
IOError, 'Not a gzipped file' while trying to access sitemap from robots.txt , Scrapy fails with **IOError, 'Not a gzipped file'** error not sure if this issue is related to following issue(s) https://github.com/scrapy/scrapy/issues/193 -> closed issue https://github.com/scrapy/scrapy/pull/660 -> merged pull request to address issue 193 https://github.com/scrapy/scrapy/issues/951 -> open issue > line where code fails in gzip.py at line # 197 ```python def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != '\037\213': raise IOError, 'Not a gzipped file' ``` #Response Header ``` Content-Encoding: gzip Accept-Ranges: bytes X-Amz-Request-Id: BFFF010DDE6268DA Vary: Accept-Encoding Server: AmazonS3 Last-Modified: Wed, 15 Jun 2016 19:02:20 GMT Etag: "300bb71d6897cb2a22bba0bd07978c84" Cache-Control: no-transform Date: Sun, 19 Jun 2016 10:54:53 GMT Content-Type: binary/octet-stream ``` Error Log: ```log Traceback (most recent call last): File "c:\venv\scrapy1.0\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback yield next(it) File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 29, in process_spider_output for x in result: File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 22, in <genexpr> return (_set_referer(r) for r in result or ()) File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in <genexpr> return (r for r in result or () if _filter(r)) File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in <genexpr> return (r for r in result or () if _filter(r)) File "D:\projects\sitemap_spider\sitemap_spider\spiders\mainspider.py", line 31, in _parse_sitemap body = self._get_sitemap_body(response) File "c:\venv\scrapy1.0\lib\site-packages\scrapy\spiders\sitemap.py", line 67, in _get_sitemap_body return gunzip(response.body) File "c:\venv\scrapy1.0\lib\site-packages\scrapy\utils\gz.py", line 37, in gunzip chunk = read1(f, 8196) File "c:\venv\scrapy1.0\lib\site-packages\scrapy\utils\gz.py", line 21, in read1 return gzf.read(size) File "c:\python27\Lib\gzip.py", line 268, in read self._read(readsize) File "c:\python27\Lib\gzip.py", line 303, in _read self._read_gzip_header() File "c:\python27\Lib\gzip.py", line 197, in _read_gzip_header raise IOError, 'Not a gzipped file' ``` i did download file manually and was able to extract the content so it is not like file is corrupted as an example sitemap url : you can follow amazon robots.txt
scrapy/scrapy
diff --git a/tests/test_downloadermiddleware_httpcompression.py b/tests/test_downloadermiddleware_httpcompression.py index 24955a515..b2426946d 100644 --- a/tests/test_downloadermiddleware_httpcompression.py +++ b/tests/test_downloadermiddleware_httpcompression.py @@ -145,6 +145,26 @@ class HttpCompressionTest(TestCase): self.assertEqual(response.headers['Content-Encoding'], b'gzip') self.assertEqual(response.headers['Content-Type'], b'application/gzip') + def test_process_response_gzip_app_octetstream_contenttype(self): + response = self._getresponse('gzip') + response.headers['Content-Type'] = 'application/octet-stream' + request = response.request + + newresponse = self.mw.process_response(request, response, self.spider) + self.assertIs(newresponse, response) + self.assertEqual(response.headers['Content-Encoding'], b'gzip') + self.assertEqual(response.headers['Content-Type'], b'application/octet-stream') + + def test_process_response_gzip_binary_octetstream_contenttype(self): + response = self._getresponse('x-gzip') + response.headers['Content-Type'] = 'binary/octet-stream' + request = response.request + + newresponse = self.mw.process_response(request, response, self.spider) + self.assertIs(newresponse, response) + self.assertEqual(response.headers['Content-Encoding'], b'gzip') + self.assertEqual(response.headers['Content-Type'], b'binary/octet-stream') + def test_process_response_head_request_no_decode_required(self): response = self._getresponse('gzip') response.headers['Content-Type'] = 'application/gzip'
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 Automat==24.8.1 cffi==1.17.1 constantly==23.10.4 coverage==7.8.0 cryptography==44.0.2 cssselect==1.3.0 exceptiongroup==1.2.2 execnet==2.1.1 hyperlink==21.0.0 idna==3.10 incremental==24.7.2 iniconfig==2.1.0 jmespath==1.0.1 lxml==5.3.1 packaging==24.2 parsel==1.10.0 pluggy==1.5.0 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyDispatcher==2.0.7 pyOpenSSL==25.0.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 queuelib==1.7.0 -e git+https://github.com/scrapy/scrapy.git@d43a35735a062a4260b002cfbcd3236c77ef9399#egg=Scrapy service-identity==24.2.0 six==1.17.0 tomli==2.2.1 Twisted==24.11.0 typing_extensions==4.13.0 w3lib==2.3.1 zope.interface==7.2
name: scrapy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - automat==24.8.1 - cffi==1.17.1 - constantly==23.10.4 - coverage==7.8.0 - cryptography==44.0.2 - cssselect==1.3.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - hyperlink==21.0.0 - idna==3.10 - incremental==24.7.2 - iniconfig==2.1.0 - jmespath==1.0.1 - lxml==5.3.1 - packaging==24.2 - parsel==1.10.0 - pluggy==1.5.0 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pydispatcher==2.0.7 - pyopenssl==25.0.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - queuelib==1.7.0 - service-identity==24.2.0 - six==1.17.0 - tomli==2.2.1 - twisted==24.11.0 - typing-extensions==4.13.0 - w3lib==2.3.1 - zope-interface==7.2 prefix: /opt/conda/envs/scrapy
[ "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_app_octetstream_contenttype", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip_binary_octetstream_contenttype" ]
[]
[ "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_multipleencodings", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_request", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_encoding_inside_body", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_force_recalculate_encoding", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzip", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_gzipped_contenttype", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_head_request_no_decode_required", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_plain", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_rawdeflate", "tests/test_downloadermiddleware_httpcompression.py::HttpCompressionTest::test_process_response_zlibdelate" ]
[]
BSD 3-Clause "New" or "Revised" License
593
Backblaze__B2_Command_Line_Tool-178
761d24c8dbd00f94decbf14cf0136de0a0d9f054
2016-06-21 15:08:47
01c4e89f63f38b9efa6a6fa63f54cd556a0b5305
diff --git a/b2/bucket.py b/b2/bucket.py index 9347570..6d4332a 100644 --- a/b2/bucket.py +++ b/b2/bucket.py @@ -34,7 +34,7 @@ class LargeFileUploadState(object): """ def __init__(self, file_progress_listener): - self.lock = threading.Lock() + self.lock = threading.RLock() self.error_message = None self.file_progress_listener = file_progress_listener self.part_number_to_part_state = {} @@ -48,6 +48,11 @@ class LargeFileUploadState(object): with self.lock: return self.error_message is not None + def get_error_message(self): + with self.lock: + assert self.has_error() + return self.error_message + def update_part_bytes(self, bytes_delta): with self.lock: self.bytes_completed += bytes_delta
LargeFileUploadState object has no attribute get_error_message In my backup log file I saw this line: `b2_upload(/backup/#########.tar.gz,#########.tar.gz, 1466468375649): AttributeError("'LargeFileUploadState' object has no attribute 'get_error_message'",) 'LargeFileUploadState' object has no attribute 'get_error_message'` No retry attempt were made and the file failed to upload. (the ### were intentional and not the real file name)
Backblaze/B2_Command_Line_Tool
diff --git a/test/test_bucket.py b/test/test_bucket.py index 766af3c..44cb2e2 100644 --- a/test/test_bucket.py +++ b/test/test_bucket.py @@ -18,8 +18,9 @@ import six from b2.account_info import StubAccountInfo from b2.api import B2Api +from b2.bucket import LargeFileUploadState from b2.download_dest import DownloadDestBytes -from b2.exception import B2Error, InvalidAuthToken, MaxRetriesExceeded +from b2.exception import AlreadyFailed, B2Error, InvalidAuthToken, MaxRetriesExceeded from b2.file_version import FileVersionInfo from b2.part import Part from b2.progress import AbstractProgressListener @@ -146,6 +147,22 @@ class TestListParts(TestCaseWithBucket): self.assertEqual(expected_parts, list(self.bucket.list_parts(file1.file_id, batch_size=1))) +class TestUploadPart(TestCaseWithBucket): + def test_error_in_state(self): + file1 = self.bucket.start_large_file('file1.txt', 'text/plain', {}) + content = six.b('hello world') + file_progress_listener = mock.MagicMock() + large_file_upload_state = LargeFileUploadState(file_progress_listener) + large_file_upload_state.set_error('test error') + try: + self.bucket._upload_part( + file1.file_id, 1, (0, 11), UploadSourceBytes(content), large_file_upload_state + ) + self.fail('should have thrown') + except AlreadyFailed: + pass + + class TestListUnfinished(TestCaseWithBucket): def test_empty(self): self.assertEqual([], list(self.bucket.list_unfinished_large_files())) diff --git a/test_b2_command_line.py b/test_b2_command_line.py index 7cadd76..8d23678 100644 --- a/test_b2_command_line.py +++ b/test_b2_command_line.py @@ -319,8 +319,8 @@ def basic_test(b2_tool, bucket_name): file_to_upload = 'README.md' - with open(file_to_upload, 'rb') as f: - hex_sha1 = hashlib.sha1(f.read()).hexdigest() + hex_sha1 = hashlib.sha1(read_file(file_to_upload)).hexdigest() + uploaded_a = b2_tool.should_succeed_json( [ 'upload_file', '--noProgress', '--quiet', bucket_name, file_to_upload, 'a'
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "yapf", "pyflakes", "pytest" ], "pre_install": [], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 -e git+https://github.com/Backblaze/B2_Command_Line_Tool.git@761d24c8dbd00f94decbf14cf0136de0a0d9f054#egg=b2 certifi==2021.5.30 charset-normalizer==2.0.12 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyflakes==3.0.1 pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 six==1.17.0 tomli==1.2.3 tqdm==4.64.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: B2_Command_Line_Tool channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyflakes==3.0.1 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - six==1.17.0 - tomli==1.2.3 - tqdm==4.64.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/B2_Command_Line_Tool
[ "test/test_bucket.py::TestUploadPart::test_error_in_state" ]
[]
[ "test/test_bucket.py::TestReauthorization::testCreateBucket", "test/test_bucket.py::TestListParts::testEmpty", "test/test_bucket.py::TestListParts::testThree", "test/test_bucket.py::TestListUnfinished::test_empty", "test/test_bucket.py::TestListUnfinished::test_one", "test/test_bucket.py::TestListUnfinished::test_three", "test/test_bucket.py::TestLs::test_empty", "test/test_bucket.py::TestLs::test_hidden_file", "test/test_bucket.py::TestLs::test_one_file_at_root", "test/test_bucket.py::TestLs::test_started_large_file", "test/test_bucket.py::TestLs::test_three_files_at_root", "test/test_bucket.py::TestLs::test_three_files_in_dir", "test/test_bucket.py::TestLs::test_three_files_multiple_versions", "test/test_bucket.py::TestUpload::test_upload_bytes", "test/test_bucket.py::TestUpload::test_upload_bytes_progress", "test/test_bucket.py::TestUpload::test_upload_file_one_fatal_error", "test/test_bucket.py::TestUpload::test_upload_file_too_many_retryable_errors", "test/test_bucket.py::TestUpload::test_upload_large", "test/test_bucket.py::TestUpload::test_upload_large_resume", "test/test_bucket.py::TestUpload::test_upload_large_resume_all_parts_there", "test/test_bucket.py::TestUpload::test_upload_large_resume_file_info", "test/test_bucket.py::TestUpload::test_upload_large_resume_file_info_does_not_match", "test/test_bucket.py::TestUpload::test_upload_large_resume_no_parts", "test/test_bucket.py::TestUpload::test_upload_large_resume_part_does_not_match", "test/test_bucket.py::TestUpload::test_upload_large_resume_wrong_part_size", "test/test_bucket.py::TestUpload::test_upload_local_file", "test/test_bucket.py::TestUpload::test_upload_one_retryable_error", "test/test_bucket.py::TestDownload::test_download_by_id_no_progress", "test/test_bucket.py::TestDownload::test_download_by_id_progress", "test/test_bucket.py::TestDownload::test_download_by_name_no_progress", "test/test_bucket.py::TestDownload::test_download_by_name_progress", "test_b2_command_line.py::TestCommandLine::test_stderr_patterns" ]
[]
MIT License
594
joblib__joblib-370
40341615cc2600675ce7457d9128fb030f6f89fa
2016-06-22 09:45:21
40341615cc2600675ce7457d9128fb030f6f89fa
aabadie: I pushed an update commit (1c7763e) that ensures the numpy array wrapper is written in a dedicated frame in the pickle byte stream. I think it's cleaner. aabadie: @lesteve, comments addressed. aabadie: @lesteve, I reverted to the initial solution. lesteve: LGTM, merging, great job!
diff --git a/joblib/numpy_pickle.py b/joblib/numpy_pickle.py index 0cb616d..f029582 100644 --- a/joblib/numpy_pickle.py +++ b/joblib/numpy_pickle.py @@ -265,6 +265,14 @@ class NumpyPickler(Pickler): wrapper = self._create_array_wrapper(obj) Pickler.save(self, wrapper) + # A framer was introduced with pickle protocol 4 and we want to + # ensure the wrapper object is written before the numpy array + # buffer in the pickle file. + # See https://www.python.org/dev/peps/pep-3154/#framing to get + # more information on the framer behavior. + if self.proto >= 4: + self.framer.commit_frame(force=True) + # And then array bytes are written right after the wrapper. wrapper.write_array(obj, self) return
load fails when dump use pickle.HIGHEST_PROTOCOL in Python 3 in master branch a96878e (version 0.10.0.dev0), the following code gives `KeyError` ```py import pickle import numpy as np import joblib a = np.zeros((1, 235), np.uint32) joblib.dump(a, 'tmp.jl', protocol=pickle.HIGHEST_PROTOCOL) joblib.load('tmp.jl') ``` That is: joblib seems do not support load data which saved with `pickle.HIGHEST_PROTOCOL`
joblib/joblib
diff --git a/joblib/test/test_numpy_pickle.py b/joblib/test/test_numpy_pickle.py index 321a428..19a5e95 100644 --- a/joblib/test/test_numpy_pickle.py +++ b/joblib/test/test_numpy_pickle.py @@ -13,6 +13,7 @@ import warnings import nose import gzip import zlib +import pickle from contextlib import closing from joblib.test.common import np, with_numpy @@ -821,3 +822,18 @@ def test_non_contiguous_array_pickling(): array_reloaded = numpy_pickle.load(filename) np.testing.assert_array_equal(array_reloaded, array) os.remove(filename) + + +@with_numpy +def test_pickle_highest_protocol(): + # ensure persistence of a numpy array is valid even when using + # the pickle HIGHEST_PROTOCOL. + # see https://github.com/joblib/joblib/issues/362 + + filename = env['filename'] + str(random.randint(0, 1000)) + test_array = np.zeros(10) + + numpy_pickle.dump(test_array, filename, protocol=pickle.HIGHEST_PROTOCOL) + array_reloaded = numpy_pickle.load(filename) + + np.testing.assert_array_equal(array_reloaded, test_array)
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "nose", "coverage", "numpy>=1.6.1", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/joblib/joblib.git@40341615cc2600675ce7457d9128fb030f6f89fa#egg=joblib nose==1.3.7 numpy==1.19.5 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: joblib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - numpy==1.19.5 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/joblib
[ "joblib/test/test_numpy_pickle.py::test_pickle_highest_protocol" ]
[ "joblib/test/test_numpy_pickle.py::test_cache_size_warning", "joblib/test/test_numpy_pickle.py::test_joblib_pickle_across_python_versions" ]
[ "joblib/test/test_numpy_pickle.py::test_value_error", "joblib/test/test_numpy_pickle.py::test_compress_level_error", "joblib/test/test_numpy_pickle.py::test_numpy_persistence", "joblib/test/test_numpy_pickle.py::test_numpy_persistence_bufferred_array_compression", "joblib/test/test_numpy_pickle.py::test_memmap_persistence", "joblib/test/test_numpy_pickle.py::test_memmap_persistence_mixed_dtypes", "joblib/test/test_numpy_pickle.py::test_masked_array_persistence", "joblib/test/test_numpy_pickle.py::test_compress_mmap_mode_warning", "joblib/test/test_numpy_pickle.py::test_compressed_pickle_dump_and_load", "joblib/test/test_numpy_pickle.py::test_compress_tuple_argument", "joblib/test/test_numpy_pickle.py::test_joblib_compression_formats", "joblib/test/test_numpy_pickle.py::test_load_externally_decompressed_files", "joblib/test/test_numpy_pickle.py::test_compression_using_file_extension", "joblib/test/test_numpy_pickle.py::test_binary_zlibfile", "joblib/test/test_numpy_pickle.py::test_numpy_subclass", "joblib/test/test_numpy_pickle.py::test_pathlib", "joblib/test/test_numpy_pickle.py::test_non_contiguous_array_pickling" ]
[]
BSD 3-Clause "New" or "Revised" License
595
enthought__okonomiyaki-217
a23c1b4909741d649ebd22f30dc1268712e63c0f
2016-06-24 10:22:10
5cbd87f7c349f999ac8d53fec18e44f5656bf5eb
diff --git a/okonomiyaki/file_formats/_egg_info.py b/okonomiyaki/file_formats/_egg_info.py index ddc2e2f..afc373c 100644 --- a/okonomiyaki/file_formats/_egg_info.py +++ b/okonomiyaki/file_formats/_egg_info.py @@ -663,6 +663,18 @@ def _normalized_info_from_string(spec_depend_string, epd_platform=None, return data, epd_platform +_JSON_METADATA_VERSION = "metadata_version" +_JSON__RAW_NAME = "_raw_name" +_JSON_VERSION = "version" +_JSON_EPD_PLATFORM = "epd_platform" +_JSON_PYTHON_TAG = "python_tag" +_JSON_ABI_TAG = "abi_tag" +_JSON_PLATFORM_TAG = "platform_tag" +_JSON_PLATFORM_ABI_TAG = "platform_abi_tag" +_JSON_RUNTIME_DEPENDENCIES = "runtime_dependencies" +_JSON_SUMMARY = "summary" + + class EggMetadata(object): """ Enthought egg metadata for format 1.x. """ @@ -707,6 +719,32 @@ class EggMetadata(object): sha256 = compute_sha256(path_or_file.fp) return cls._from_egg(path_or_file, sha256, strict) + @classmethod + def from_json_dict(cls, json_dict, pkg_info): + version = EnpkgVersion.from_string(json_dict[_JSON_VERSION]) + + if json_dict[_JSON_PYTHON_TAG] is not None: + python = PythonImplementation.from_string(json_dict[_JSON_PYTHON_TAG]) + else: + python = None + + if json_dict[_JSON_EPD_PLATFORM] is None: + epd_platform = None + else: + epd_platform = EPDPlatform.from_epd_string(json_dict[_JSON_EPD_PLATFORM]) + + dependencies = Dependencies(tuple(json_dict[_JSON_RUNTIME_DEPENDENCIES])) + metadata_version = MetadataVersion.from_string( + json_dict[_JSON_METADATA_VERSION] + ) + + return cls( + json_dict[_JSON__RAW_NAME], version, epd_platform, python, + json_dict[_JSON_ABI_TAG], json_dict[_JSON_PLATFORM_ABI_TAG], + dependencies, pkg_info, json_dict[_JSON_SUMMARY], + metadata_version=metadata_version + ) + @classmethod def _from_egg(cls, path_or_file, sha256, strict=True): def _read_summary(fp): @@ -1015,6 +1053,27 @@ class EggMetadata(object): if self.pkg_info: self.pkg_info._dump_as_zip(zp) + def to_json_dict(self): + if self.platform is None: + epd_platform = None + else: + epd_platform = six.text_type(self.platform) + + return { + _JSON_METADATA_VERSION: six.text_type(self.metadata_version), + _JSON__RAW_NAME: self._raw_name, + _JSON_VERSION: six.text_type(self.version), + _JSON_EPD_PLATFORM: epd_platform, + _JSON_PYTHON_TAG: self.python_tag, + _JSON_ABI_TAG: self.abi_tag, + _JSON_PLATFORM_TAG: self.platform_tag, + _JSON_PLATFORM_ABI_TAG: self.platform_abi_tag, + _JSON_RUNTIME_DEPENDENCIES: [ + six.text_type(p) for p in self.runtime_dependencies + ], + _JSON_SUMMARY: self.summary, + } + # Protocol implementations def __eq__(self, other): if isinstance(other, self.__class__):
Move EggMetadata json serialization from edm See enthought/edm#719
enthought/okonomiyaki
diff --git a/okonomiyaki/file_formats/tests/test__egg_info.py b/okonomiyaki/file_formats/tests/test__egg_info.py index 80dd58b..b658c36 100644 --- a/okonomiyaki/file_formats/tests/test__egg_info.py +++ b/okonomiyaki/file_formats/tests/test__egg_info.py @@ -17,7 +17,9 @@ from ...errors import ( InvalidEggName, InvalidMetadata, InvalidMetadataField, MissingMetadata, UnsupportedMetadata) from ...utils import tempdir -from ...utils.test_data import NOSE_1_3_4_OSX_X86_64 +from ...utils.test_data import ( + MKL_10_3_RH5_X86_64, NOSE_1_3_4_OSX_X86_64, NOSE_1_3_4_RH5_X86_64 +) from ...platforms import EPDPlatform, PlatformABI, PythonImplementation from ...platforms.legacy import LegacyEPDPlatform from ...versions import EnpkgVersion, MetadataVersion, RuntimeVersion @@ -1552,3 +1554,68 @@ class TestEggMetadata(unittest.TestCase): # Then metadata = EggMetadata.from_egg(path) self.assertEqual(metadata.platform_tag, "win32") + + def test_to_json_dict(self): + # Given + egg = NOSE_1_3_4_RH5_X86_64 + metadata = EggMetadata.from_egg(egg) + + r_json_dict = { + "metadata_version": u"1.3", + "_raw_name": u"nose", + "version": u"1.3.4-1", + "epd_platform": u"rh5_x86_64", + "python_tag": u"cp27", + "abi_tag": u"cp27m", + "platform_tag": u"linux_x86_64", + "platform_abi_tag": u"gnu", + "runtime_dependencies": [], + "summary": ( + u"Extends the Python Unittest module with additional " + "disocvery and running\noptions\n" + ) + } + + # When + json_dict = metadata.to_json_dict() + + # Then + self.assertEqual(json_dict, r_json_dict) + + def test_from_json_dict(self): + # Given + egg = NOSE_1_3_4_RH5_X86_64 + r_metadata = EggMetadata.from_egg(egg) + + json_dict = { + "metadata_version": u"1.3", + "_raw_name": u"nose", + "version": u"1.3.4-1", + "epd_platform": u"rh5_x86_64", + "python_tag": u"cp27", + "abi_tag": u"cp27m", + "platform_tag": u"linux_x86_64", + "platform_abi_tag": u"gnu", + "runtime_dependencies": [], + "summary": ( + u"Extends the Python Unittest module with additional " + "disocvery and running\noptions\n" + ) + } + + # When + metadata = EggMetadata.from_json_dict(json_dict, r_metadata.pkg_info) + + # Then + self.assertEqual(metadata, r_metadata) + + def _test_roundtrip(self, egg): + r_metadata = EggMetadata.from_egg(egg) + metadata = EggMetadata.from_json_dict( + r_metadata.to_json_dict(), r_metadata.pkg_info + ) + + self.assertEqual(metadata, r_metadata) + + def test_mkl_roundtrip(self): + self._test_roundtrip(MKL_10_3_RH5_X86_64)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 1 }
0.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "dev_requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 coverage==7.8.0 docutils==0.21.2 enum34==1.1.10 exceptiongroup==1.2.2 flake8==7.2.0 haas==0.9.0 iniconfig==2.1.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 mccabe==0.7.0 mock==1.0.1 -e git+https://github.com/enthought/okonomiyaki.git@a23c1b4909741d649ebd22f30dc1268712e63c0f#egg=okonomiyaki packaging==24.2 pbr==6.1.1 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.2 pytest==8.3.5 referencing==0.36.2 rpds-py==0.24.0 six==1.17.0 statistics==1.0.3.5 stevedore==4.1.1 testfixtures==8.3.0 tomli==2.2.1 typing_extensions==4.13.0 zipfile2==0.0.12
name: okonomiyaki channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - coverage==7.8.0 - docutils==0.21.2 - enum34==1.1.10 - exceptiongroup==1.2.2 - flake8==7.2.0 - haas==0.9.0 - iniconfig==2.1.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - mccabe==0.7.0 - mock==1.0.1 - packaging==24.2 - pbr==6.1.1 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytest==8.3.5 - referencing==0.36.2 - rpds-py==0.24.0 - six==1.17.0 - statistics==1.0.3.5 - stevedore==4.1.1 - testfixtures==8.3.0 - tomli==2.2.1 - typing-extensions==4.13.0 - zipfile2==0.0.12 prefix: /opt/conda/envs/okonomiyaki
[ "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_json_dict", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_mkl_roundtrip", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_to_json_dict" ]
[]
[ "okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_from_spec_string", "okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_from_string", "okonomiyaki/file_formats/tests/test__egg_info.py::TestRequirement::test_str", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_blacklisted_platform", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_create_from_egg1", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_create_from_egg2", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_error_python_to_python_tag", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_format_1_3", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_format_1_4", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_from_string", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_missing_spec_depend", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_to_string", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_unsupported_metadata_version", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDepend::test_windows_platform", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_extension_python_egg", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_no_python_egg", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_pure_python_egg", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_default_pure_python_egg_pypi", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependAbi::test_to_string", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_all_none", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_rh5_32", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_rh5_64", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_win_32", "okonomiyaki/file_formats/tests/test__egg_info.py::TestLegacySpecDependPlatform::test_default_win_64", "okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_no_platform", "okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_no_python_implementation", "okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_27", "okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_34", "okonomiyaki/file_formats/tests/test__egg_info.py::TestGuessPlatformAbi::test_python_35", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggName::test_split_egg_name", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggName::test_split_egg_name_invalid", "okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_invalid_spec_strings", "okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_1_1", "okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_1_2", "okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_simple_unsupported", "okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_with_dependencies", "okonomiyaki/file_formats/tests/test__egg_info.py::TestParseRawspec::test_with_none", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_pkg_info", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_platform", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_blacklisted_python_tag", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_blacklisted", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_blacklisted_platform", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_dump_simple", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_fixed_requirement", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_cross_platform_egg", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_from_platform_egg", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_no_pkg_info", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_platform_abi", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_platform_abi_no_python", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_simple", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_simple_non_python_egg", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_strictness", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_support_higher_compatible_version", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_support_lower_compatible_version", "okonomiyaki/file_formats/tests/test__egg_info.py::TestEggMetadata::test_to_spec_string" ]
[]
BSD License
596
ifosch__accloudtant-88
79e3cf915208ffd58a63412ffc87bd48f8bfb2dd
2016-06-24 12:10:46
33f90ff0bc1639c9fe793afd837eee80170caf3e
diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py index d83c3dc..f360c03 100644 --- a/accloudtant/aws/instance.py +++ b/accloudtant/aws/instance.py @@ -28,6 +28,9 @@ class Instance(object): 'best': 0.0, } + def __repr__(self): + return "<accloudtant.aws.instance.Instance id={}>".format(self.id) + @property def current(self): return self._prices['current'] diff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py index 0bbbeb9..e8f2fc9 100644 --- a/accloudtant/aws/reports.py +++ b/accloudtant/aws/reports.py @@ -25,9 +25,26 @@ class Reports(object): def __init__(self): ec2 = boto3.resource('ec2') ec2_client = boto3.client('ec2') + instances_filters = [{ + 'Name': 'instance-state-name', + 'Values': ['running', ], + }, ] + reserved_instances_filters = [{ + 'Name': 'state', + 'Values': ['active', ], + }, ] try: - self.instances = [Instance(i) for i in ec2.instances.all()] - self.reserved_instances = ec2_client.describe_reserved_instances() + self.instances = [ + Instance(i) + for i in ec2.instances.filter(Filters=instances_filters) + ] + # self.instances = [Instance(i) for i in ec2.instances.all()] + self.reserved_instances = ec2_client.\ + describe_reserved_instances( + Filters=reserved_instances_filters + ) + # self.reserved_instances = ec2_client + # .describe_reserved_instances() except exceptions.NoCredentialsError: print("Error: no AWS credentials found", file=sys.stderr) sys.exit(1)
Iterate over appropriate subsets for performance improvement When generating reports, the code iterates over all instances, and all reserved instances, to get the links between these, the report should iterate over running instances and active reserved instances, only.
ifosch/accloudtant
diff --git a/tests/aws/conftest.py b/tests/aws/conftest.py index 0594830..5a97b58 100644 --- a/tests/aws/conftest.py +++ b/tests/aws/conftest.py @@ -65,6 +65,14 @@ def ec2_resource(): for instance in self.instances: yield MockEC2Instance(instance) + def filter(self, Filters=None): + if Filters is None: + self.all() + if Filters[0]['Name'] == 'instance-state-name': + for instance in self.instances: + if instance['state']['Name'] in Filters[0]['Values']: + yield MockEC2Instance(instance) + class MockEC2Resource(object): def __init__(self, responses): self.responses = responses @@ -94,7 +102,19 @@ def ec2_client(): def describe_instances(self): return self.instances - def describe_reserved_instances(self): + def describe_reserved_instances(self, Filters=None): + final_reserved = {'ReservedInstances': []} + if Filters is None: + final_reserved = self.reserved + else: + filter = Filters[0] + if filter['Name'] == 'state': + final_reserved['ReservedInstances'] = [ + reserved_instance + for reserved_instance + in self.reserved['ReservedInstances'] + if reserved_instance['State'] not in filter['Values'] + ] return self.reserved class MockEC2ClientCall(object): diff --git a/tests/aws/report_running_expected.txt b/tests/aws/report_running_expected.txt new file mode 100644 index 0000000..befecd0 --- /dev/null +++ b/tests/aws/report_running_expected.txt @@ -0,0 +1,8 @@ +Id Name Type AZ OS State Launch time Reserved Current hourly price Renewed hourly price +---------- --------- ---------- ---------- ------------------------ ------- ------------------- ---------- ---------------------- ---------------------- +i-912a4392 web1 c3.8xlarge us-east-1c Windows running 2015-10-22 14:15:10 Yes 0.5121 0.3894 +i-1840273e app1 r2.8xlarge us-east-1b Red Hat Enterprise Linux running 2015-10-22 14:15:10 Yes 0.3894 0.3794 +i-9840273d app2 r2.8xlarge us-east-1c SUSE Linux running 2015-10-22 14:15:10 Yes 0.5225 0.389 +i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 +i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 +i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No 0.767 0.3892 diff --git a/tests/aws/test_reports.py b/tests/aws/test_reports.py index 35fd236..d0f6793 100644 --- a/tests/aws/test_reports.py +++ b/tests/aws/test_reports.py @@ -17,6 +17,10 @@ from dateutil.tz import tzutc import accloudtant.aws.reports +def get_future_date(years=1): + return datetime.datetime.now() + datetime.timedelta(years) + + def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): instances = { 'instances': [{ @@ -232,16 +236,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - 494000, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', @@ -266,16 +261,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - 494000, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233321', @@ -300,15 +286,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233322', @@ -333,15 +311,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', @@ -421,7 +391,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): }, }, }, - 'od': '0.767', + 'od': '0.867', 'memoryGiB': '15', 'vCPU': '8', }, @@ -618,7 +588,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): 'best': 0.3892, }, } - expected = open('tests/aws/report_expected.txt', 'r').read() + expected = open('tests/aws/report_running_expected.txt', 'r').read() monkeypatch.setattr('boto3.resource', ec2_resource) ec2_resource.set_responses(instances) @@ -634,6 +604,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): print(reports) out, err = capsys.readouterr() + assert(len(reports.instances) == 6) for mock in instances['instances']: mock['current'] = instances_prices[mock['id']]['current'] mock['best'] = instances_prices[mock['id']]['best'] @@ -641,5 +612,4 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): if instance.id == mock['id']: assert(instance.current == mock['current']) assert(instance.best == mock['best']) - print(out) assert(out == expected)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/ifosch/accloudtant.git@79e3cf915208ffd58a63412ffc87bd48f8bfb2dd#egg=accloudtant boto3==1.1.4 botocore==1.2.10 click==4.1 docutils==0.21.2 exceptiongroup==1.2.2 futures==2.2.0 iniconfig==2.1.0 jmespath==0.10.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 requests==2.8.1 six==1.17.0 tabulate==0.7.5 tomli==2.2.1
name: accloudtant channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.1.4 - botocore==1.2.10 - click==4.1 - docutils==0.21.2 - exceptiongroup==1.2.2 - futures==2.2.0 - iniconfig==2.1.0 - jmespath==0.10.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - requests==2.8.1 - six==1.17.0 - tabulate==0.7.5 - tomli==2.2.1 prefix: /opt/conda/envs/accloudtant
[ "tests/aws/test_reports.py::test_reports" ]
[]
[]
[]
null
597
ifosch__accloudtant-90
96ca7fbc89be0344db1af0ec2bc9fdecff6380eb
2016-06-24 19:51:52
33f90ff0bc1639c9fe793afd837eee80170caf3e
diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py index f360c03..02ca135 100644 --- a/accloudtant/aws/instance.py +++ b/accloudtant/aws/instance.py @@ -94,11 +94,11 @@ class Instance(object): def match_reserved_instance(self, reserved): return not ( self.state != 'running' or - reserved['State'] != 'active' or - reserved['InstancesLeft'] == 0 or - reserved['ProductDescription'] != self.operating_system or - reserved['InstanceType'] != self.size or - reserved['AvailabilityZone'] != self.availability_zone + reserved.state != 'active' or + reserved.instances_left == 0 or + reserved.product_description != self.operating_system or + reserved.instance_type != self.size or + reserved.az != self.availability_zone ) diff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py index e8f2fc9..bcfe9c0 100644 --- a/accloudtant/aws/reports.py +++ b/accloudtant/aws/reports.py @@ -17,6 +17,7 @@ import boto3 from botocore import exceptions from tabulate import tabulate from accloudtant.aws.instance import Instance +from accloudtant.aws.reserved_instance import ReservedInstance from accloudtant.aws.prices import Prices import sys @@ -39,10 +40,12 @@ class Reports(object): for i in ec2.instances.filter(Filters=instances_filters) ] # self.instances = [Instance(i) for i in ec2.instances.all()] - self.reserved_instances = ec2_client.\ - describe_reserved_instances( + self.reserved_instances = [ + ReservedInstance(i) + for i in ec2_client.describe_reserved_instances( Filters=reserved_instances_filters - ) + )['ReservedInstances'] + ] # self.reserved_instances = ec2_client # .describe_reserved_instances() except exceptions.NoCredentialsError: @@ -60,13 +63,11 @@ class Reports(object): instance.current = 0.0 instance_all_upfront = instance_size['ri']['yrTerm3']['allUpfront'] instance.best = float(instance_all_upfront['effectiveHourly']) - for reserved in self.reserved_instances['ReservedInstances']: - if 'InstancesLeft' not in reserved.keys(): - reserved['InstancesLeft'] = reserved['InstanceCount'] + for reserved in self.reserved_instances: if instance.match_reserved_instance(reserved): instance.reserved = 'Yes' - instance.current = reserved['UsagePrice'] - reserved['InstancesLeft'] -= 1 + instance.current = reserved.usage_price + reserved.link(instance) break def __repr__(self): diff --git a/accloudtant/aws/reserved_instance.py b/accloudtant/aws/reserved_instance.py new file mode 100644 index 0000000..4073a20 --- /dev/null +++ b/accloudtant/aws/reserved_instance.py @@ -0,0 +1,86 @@ + +# Copyright 2015-2016 See CONTRIBUTORS.md file +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +class ReservedInstance(object): + def __init__(self, data): + self.reserved_instance = data + if data['State'] != 'active': + self.instances_left = 0 + else: + self.instances_left = self.instance_count + + @property + def id(self): + return self.reserved_instance['ReservedInstancesId'] + + @property + def az(self): + return self.reserved_instance['AvailabilityZone'] + + @property + def instance_type(self): + return self.reserved_instance['InstanceType'] + + @property + def product_description(self): + return self.reserved_instance['ProductDescription'] + + @property + def start(self): + return self.reserved_instance['Start'] + + @property + def end(self): + return self.reserved_instance['End'] + + @property + def state(self): + return self.reserved_instance['State'] + + @property + def duration(self): + return self.reserved_instance['Duration'] + + @property + def offering_type(self): + return self.reserved_instance['OfferingType'] + + @property + def usage_price(self): + return self.reserved_instance['UsagePrice'] + + @property + def fixed_price(self): + return self.reserved_instance['FixedPrice'] + + @property + def currency_code(self): + return self.reserved_instance['CurrencyCode'] + + @property + def recurring_charges(self): + return self.reserved_instance['RecurringCharges'] + + @property + def instance_count(self): + return self.reserved_instance['InstanceCount'] + + @property + def instance_tenancy(self): + return self.reserved_instance['InstanceTenancy'] + + def link(self, instance): + self.instances_left -= 1
Create a Reserved Instance type/class Reserved instances are currently simple dictionaries. Implementing these as objects might help to use them.
ifosch/accloudtant
diff --git a/tests/aws/test_instance.py b/tests/aws/test_instance.py index 6f6d73c..fae2e82 100644 --- a/tests/aws/test_instance.py +++ b/tests/aws/test_instance.py @@ -16,6 +16,7 @@ import datetime import pytest from dateutil.tz import tzutc import accloudtant.aws.instance +from accloudtant.aws.reserved_instance import ReservedInstance from conftest import MockEC2Instance @@ -261,7 +262,7 @@ def test_match_reserved_instance(benchmark): ), 'console_output': {'Output': 'RHEL Linux', }, } - reserved_instance = { + ri_data = { 'ProductDescription': 'Red Hat Enterprise Linux', 'InstanceTenancy': 'default', 'InstanceCount': 1, @@ -298,31 +299,36 @@ def test_match_reserved_instance(benchmark): ec2_instance = MockEC2Instance(instance_data) instance = accloudtant.aws.instance.Instance(ec2_instance) - reserved_instance['InstancesLeft'] = reserved_instance['InstanceCount'] + reserved_instance = ReservedInstance(ri_data) assert(instance.match_reserved_instance(reserved_instance)) benchmark(instance.match_reserved_instance, reserved_instance) - reserved_instance['State'] = 'pending' + ri_data['State'] = 'pending' + reserved_instance = ReservedInstance(ri_data) assert(not instance.match_reserved_instance(reserved_instance)) - reserved_instance['State'] = 'active' - reserved_instance['InstancesLeft'] = 0 + ri_data['State'] = 'active' + reserved_instance = ReservedInstance(ri_data) + reserved_instance.instances_left = 0 assert(not instance.match_reserved_instance(reserved_instance)) - reserved_instance['InstacesLeft'] = 1 - reserved_instance['ProductDescription'] = 'Windows' + ri_data['ProductDescription'] = 'Windows' + reserved_instance = ReservedInstance(ri_data) + reserved_instance.instances_left = 1 assert(not instance.match_reserved_instance(reserved_instance)) - reserved_instance['ProductionDescription'] = 'Red Hat Enterprise Linux' - reserved_instance['InstaceType'] = 't1.micro' + ri_data['ProductionDescription'] = 'Red Hat Enterprise Linux' + ri_data['InstaceType'] = 't1.micro' + reserved_instance = ReservedInstance(ri_data) assert(not instance.match_reserved_instance(reserved_instance)) - reserved_instance['InstaceType'] = 'r2.8xlarge' - reserved_instance['AvailabilityZone'] = 'us-east-1c' + ri_data['InstaceType'] = 'r2.8xlarge' + ri_data['AvailabilityZone'] = 'us-east-1c' + reserved_instance = ReservedInstance(ri_data) assert(not instance.match_reserved_instance(reserved_instance)) diff --git a/tests/aws/test_reserved_instance.py b/tests/aws/test_reserved_instance.py new file mode 100644 index 0000000..9627ebf --- /dev/null +++ b/tests/aws/test_reserved_instance.py @@ -0,0 +1,189 @@ +# Copyright 2015-2016 See CONTRIBUTORS.md file +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import datetime +import pytest +from dateutil.tz import tzutc +import accloudtant.aws.reserved_instance +from conftest import MockEC2Instance +from test_reports import get_future_date + + +def test_retired_ri(): + az = 'us-east-1b' + ri_data = { + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 29, + 'InstanceType': 'm1.large', + 'Start': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + tzinfo=tzutc() + ), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df1223331f', + 'FixedPrice': 910.0, + 'AvailabilityZone': az, + 'UsagePrice': 0.12, + 'Duration': 31536000, + 'State': 'retired', + } + + ri = accloudtant.aws.reserved_instance.ReservedInstance(ri_data) + + assert(ri.id == ri_data['ReservedInstancesId']) + assert(ri.product_description == ri_data['ProductDescription']) + assert(ri.instance_tenancy == ri_data['InstanceTenancy']) + assert(ri.instance_count == ri_data['InstanceCount']) + assert(ri.instance_type == ri_data['InstanceType']) + assert(ri.start == ri_data['Start']) + assert(ri.recurring_charges == ri_data['RecurringCharges']) + assert(ri.end == ri_data['End']) + assert(ri.currency_code == ri_data['CurrencyCode']) + assert(ri.offering_type == ri_data['OfferingType']) + assert(ri.fixed_price == ri_data['FixedPrice']) + assert(ri.az == ri_data['AvailabilityZone']) + assert(ri.usage_price == ri_data['UsagePrice']) + assert(ri.duration == ri_data['Duration']) + assert(ri.state == ri_data['State']) + assert(ri.instances_left == 0) + + +def test_active_ri(): + az = 'us-east-1b' + ri_data = { + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 'm1.large', + 'Start': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': get_future_date(), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df1223331f', + 'FixedPrice': 910.0, + 'AvailabilityZone': az, + 'UsagePrice': 0.12, + 'Duration': 31536000, + 'State': 'active', + } + + ri = accloudtant.aws.reserved_instance.ReservedInstance(ri_data) + + assert(ri.id == ri_data['ReservedInstancesId']) + assert(ri.product_description == ri_data['ProductDescription']) + assert(ri.instance_tenancy == ri_data['InstanceTenancy']) + assert(ri.instance_count == ri_data['InstanceCount']) + assert(ri.instance_type == ri_data['InstanceType']) + assert(ri.start == ri_data['Start']) + assert(ri.recurring_charges == ri_data['RecurringCharges']) + assert(ri.end == ri_data['End']) + assert(ri.currency_code == ri_data['CurrencyCode']) + assert(ri.offering_type == ri_data['OfferingType']) + assert(ri.fixed_price == ri_data['FixedPrice']) + assert(ri.az == ri_data['AvailabilityZone']) + assert(ri.usage_price == ri_data['UsagePrice']) + assert(ri.duration == ri_data['Duration']) + assert(ri.state == ri_data['State']) + assert(ri.instances_left == ri_data['InstanceCount']) + + +def test_ri_link(): + az = 'us-east-1b' + ri_data = { + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 'm1.large', + 'Start': datetime.datetime( + 2015, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': get_future_date(), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df1223331f', + 'FixedPrice': 910.0, + 'AvailabilityZone': az, + 'UsagePrice': 0.12, + 'Duration': 31536000, + 'State': 'active', + } + instance_data = { + 'id': 'i-1840273e', + 'tags': [{ + 'Key': 'Name', + 'Value': 'app1', + }, ], + 'instance_type': 'm1.large', + 'placement': { + 'AvailabilityZone': az, + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'Linux', }, + } + + ri = accloudtant.aws.reserved_instance.ReservedInstance(ri_data) + instance = MockEC2Instance(instance_data) + + assert(ri.instances_left == 1) + + ri.link(instance) + + assert(ri.instances_left == 0)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/ifosch/accloudtant.git@96ca7fbc89be0344db1af0ec2bc9fdecff6380eb#egg=accloudtant boto3==1.1.4 botocore==1.2.10 click==4.1 docutils==0.21.2 exceptiongroup==1.2.2 futures==2.2.0 iniconfig==2.1.0 jmespath==0.10.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 requests==2.8.1 six==1.17.0 tabulate==0.7.5 tomli==2.2.1
name: accloudtant channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.1.4 - botocore==1.2.10 - click==4.1 - docutils==0.21.2 - exceptiongroup==1.2.2 - futures==2.2.0 - iniconfig==2.1.0 - jmespath==0.10.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - requests==2.8.1 - six==1.17.0 - tabulate==0.7.5 - tomli==2.2.1 prefix: /opt/conda/envs/accloudtant
[ "tests/aws/test_instance.py::test_instance", "tests/aws/test_instance.py::test_unnamed_instance", "tests/aws/test_instance.py::test_guess_os", "tests/aws/test_reserved_instance.py::test_retired_ri", "tests/aws/test_reserved_instance.py::test_active_ri", "tests/aws/test_reserved_instance.py::test_ri_link" ]
[]
[]
[]
null
598
sympy__sympy-11297
230b1bf3a3a67c0621a3b4a8f2a45e950f82393f
2016-06-25 06:46:20
8bb5814067cfa0348fb8b708848f35dba2b55ff4
diff --git a/setup.py b/setup.py index 097efc5f42..bee2324d13 100755 --- a/setup.py +++ b/setup.py @@ -86,6 +86,7 @@ 'sympy.functions.special', 'sympy.functions.special.benchmarks', 'sympy.geometry', + 'sympy.holonomic', 'sympy.integrals', 'sympy.integrals.benchmarks', 'sympy.interactive', @@ -270,6 +271,7 @@ def run(self): 'sympy.functions.elementary.tests', 'sympy.functions.special.tests', 'sympy.geometry.tests', + 'sympy.holonomic.tests', 'sympy.integrals.tests', 'sympy.interactive.tests', 'sympy.liealgebras.tests', diff --git a/sympy/holonomic/holonomic.py b/sympy/holonomic/holonomic.py index 2a2c1ef65e..3868cb4e80 100644 --- a/sympy/holonomic/holonomic.py +++ b/sympy/holonomic/holonomic.py @@ -2,7 +2,8 @@ from __future__ import print_function, division -from sympy import symbols, Symbol, diff, S, Dummy, Order, rf, meijerint, I, solve +from sympy import (symbols, Symbol, diff, S, Dummy, Order, rf, meijerint, I, + solve, limit) from sympy.printing import sstr from .linearsolver import NewMatrix from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators @@ -323,6 +324,14 @@ def __eq__(self, other): else: return False + def is_singular(self, x0=0): + """ + Checks if the differential equation is singular at x0. + """ + + domain = str(self.parent.base.domain)[0] + return x0 in roots(self.listofpoly[-1].rep, filter=domain) + class HolonomicFunction(object): """ @@ -336,6 +345,21 @@ class HolonomicFunction(object): Given two Holonomic Functions f and g, their sum, product, integral and derivative is also a Holonomic Function. + To plot a Holonomic Function, one can use `.evalf()` for numerical computation. + Here's an example on `sin(x)**2/x` using numpy and matplotlib. + + `` + import sympy.holonomic + from sympy import var, sin + import matplotlib.pyplot as plt + import numpy as np + var("x") + r = np.linspace(1, 5, 100) + y = sympy.holonomic.from_sympy(sin(x)**2/x, x0=1).evalf(r) + plt.plot(r, y, label="holonomic function") + plt.show() + `` + Examples ======== @@ -482,6 +506,7 @@ def __add__(self, other): sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False) # solving initial conditions if self._have_init_cond and other._have_init_cond: + if self.x0 == other.x0: # try to extended the initial conditions # using the annihilator @@ -489,14 +514,29 @@ def __add__(self, other): y0_other = _extend_y0(other, sol.order) y0 = [a + b for a, b in zip(y0_self, y0_other)] return HolonomicFunction(sol, self.x, self.x0, y0) + else: - # initial conditions for different points - # to be implemented - pass + + if self.x0 == 0 and not self.annihilator.is_singular() \ + and not other.annihilator.is_singular(): + return self + other.change_ics(0) + + elif other.x0 == 0 and not self.annihilator.is_singular() \ + and not other.annihilator.is_singular(): + return self.change_ics(0) + other + + else: + + if not self.annihilator.is_singular(x0=self.x0) and \ + not other.annihilator.is_singular(x0=self.x0): + return self + other.change_ics(self.x0) + + else: + return self.change_ics(other.x0) + other return HolonomicFunction(sol, self.x) - def integrate(self, *args): + def integrate(self, limits): """ Integrate the given holonomic function. Limits can be provided, Initial conditions can only be computed when limits are (x0, x). @@ -518,19 +558,126 @@ def integrate(self, *args): HolonomicFunction((1)Dx + (1)Dx**3, x), f(0) = 0, f'(0) = 1, f''(0) = 0 """ - # just multiply by Dx from right + # to get the annihilator, just multiply by Dx from right D = self.annihilator.parent.derivative_operator - if (not args) or (not self._have_init_cond): + + # for indefinite integration + if (not limits) or (not self._have_init_cond): return HolonomicFunction(self.annihilator * D, self.x) - # definite integral if limits are (x0, x) - if len(args) == 1 and len(args[0]) == 3 and args[0][1] == self.x0 and args[0][2] == self.x: + # definite integral + # initial conditions for the answer will be stored at point `a`, + # where `a` is the lower limit of the integrand + if hasattr(limits, "__iter__"): + + if len(limits) == 3 and limits[0] == self.x: + x0 = self.x0 + a = limits[1] + b = limits[2] + + else: + x0 = self.x0 + a = self.x0 + b = self.x + + if x0 == a: y0 = [S(0)] y0 += self.y0 - return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) + + # use evalf to get the values at `a` + else: + y0 = [S(0)] + tempy0 = self.evalf(a, derivatives=True) + y0 += tempy0 + + # if the upper limit is `x`, the answer will be a function + if b == self.x: + return HolonomicFunction(self.annihilator * D, self.x, a, y0) + + # if the upper limits is a Number, a numerical value will be returned + elif S(b).is_Number: + return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b) return HolonomicFunction(self.annihilator * D, self.x) + def diff(self, *args): + """ + Differentiation of the given Holonomic function. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy.polys.domains import ZZ, QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + + # derivative of sin(x) + >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_sympy() + cos(x) + + # derivative of e^2*x + >>> HolonomicFunction(Dx - 2, x, 0, 1).diff().to_sympy() + 2*exp(2*x) + + See Also + ======= + + .integrate() + """ + + if args: + if args[0] != self.x: + return S(0) + elif len(args) == 2: + sol = self + for i in range(args[1]): + sol = sol.diff(args[0]) + return sol + + ann = self.annihilator + dx = ann.parent.derivative_operator + + # if the function is constant. + if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1: + return S(0) + + # if the coefficient of y in the differential equation is zero. + # a shifting is done to compute the answer in this case. + elif ann.listofpoly[0] == ann.parent.base.zero: + + sol = DifferentialOperator(ann.listofpoly[1:], ann.parent) + + if self._have_init_cond: + return HolonomicFunction(sol, self.x, self.x0, self.y0[1:]) + + else: + return HolonomicFunction(sol, self.x) + + # the general algorithm + R = ann.parent.base + K = R.get_field() + + seq_dmf = [K.new(i.rep) for i in ann.listofpoly] + + # -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0 + rhs = [i / seq_dmf[0] for i in seq_dmf[1:]] + rhs.insert(0, K.zero) + + # differentiate both lhs and rhs + sol = _derivate_diff_eq(rhs) + + # add the term y' in lhs to rhs + sol = _add_lists(sol, [K.zero, K.one]) + + sol = _normalize(sol[1:], self.annihilator.parent, negative=False) + + if not self._have_init_cond: + return HolonomicFunction(sol, self.x) + + y0 = _extend_y0(self, sol.order + 1)[1:] + return HolonomicFunction(sol, self.x, self.x0, y0) def __eq__(self, other): if self.annihilator == other.annihilator: @@ -635,6 +782,8 @@ def __mul__(self, other): sol_ann = _normalize(sol[0][0:], self.annihilator.parent, negative=False) if self._have_init_cond and other._have_init_cond: + + # if both the conditions are at same point if self.x0 == other.x0: # try to find more inital conditions @@ -657,9 +806,28 @@ def __mul__(self, other): sol += coeff[j][k]* y0_self[j] * y0_other[k] y0.append(sol) + return HolonomicFunction(sol_ann, self.x, self.x0, y0) + + # if the points are different, consider one else: - raise NotImplementedError + + if self.x0 == 0 and not ann_self.is_singular() \ + and not ann_other.is_singular(): + return self * other.change_ics(0) + + elif other.x0 == 0 and not ann_self.is_singular() \ + and not ann_other.is_singular(): + return self.change_ics(0) * other + + else: + + if not ann_self.is_singular(x0=self.x0) and \ + not ann_other.is_singular(x0=self.x0): + return self * other.change_ics(self.x0) + + else: + return self.change_ics(other.x0) * other return HolonomicFunction(sol_ann, self.x) @@ -770,10 +938,15 @@ def composition(self, expr, *args): def to_sequence(self, lb=True): """ Finds the recurrence relation in power series expansion - of the function. + of the function about origin. + + Returns a tuple (R, n0), with R being the Recurrence relation + and a non-negative integer `n0` such that the recurrence relation + holds for all n >= n0. - Returns a tuple of the recurrence relation and a value `n0` such that - the recurrence relation holds for all n >= n0. + If it's not possible to numerically compute a initial condition, + it is returned as a symbol C_j, denoting the coefficient of x^j + in the power series about origin. Examples ======== @@ -858,12 +1031,6 @@ def to_sequence(self, lb=True): # the recurrence relation sol = RecurrenceOperator(sol, R) - if not self._have_init_cond or self.x0 != 0: - if lb: - return (HolonomicSequence(sol), smallest_n) - else: - return HolonomicSequence(sol) - # computing the initial conditions for recurrence order = sol.order all_roots = roots(sol.listofpoly[-1].rep, filter='Z') @@ -884,34 +1051,61 @@ def to_sequence(self, lb=True): # if sufficient conditions can't be computed then # try to use the series method i.e. - # equate the coefficients of x^k in series to zero. + # equate the coefficients of x^k in the equation formed by + # substituting the series in differential equation, to zero. if len(u0) < order: for i in range(degree): eq = S(0) for j in dict1: - if i + j[0] < len(u0): + + if i + j[0] < 0: + dummys[i + j[0]] = S(0) + + elif i + j[0] < len(u0): dummys[i + j[0]] = u0[i + j[0]] elif not i + j[0] in dummys: - dummys[i + j[0]] = Dummy('x_%s' %(i + j[0])) + dummys[i + j[0]] = Symbol('C_%s' %(i + j[0])) if j[1] <= i: eq += dict1[j].subs(n, i) * dummys[i + j[0]] eqs.append(eq) + # solve the system of equations formed soleqs = solve(eqs) + if isinstance(soleqs, dict): + + for i in range(len(u0), order): + + if i not in dummys: + dummys[i] = Symbol('C_%s' %i) + + if dummys[i] in soleqs: + u0.append(soleqs[dummys[i]]) + + else: + u0.append(dummys[i]) + + if lb: + return (HolonomicSequence(sol, u0), smallest_n) + return HolonomicSequence(sol, u0) + for i in range(len(u0), order): + + if i not in dummys: + dummys[i] = Symbol('C_%s' %i) + s = False for j in soleqs: if dummys[i] in j: u0.append(j[dummys[i]]) s = True if not s: - break + u0.append(dummys[i]) if lb: return (HolonomicSequence(sol, u0), smallest_n) @@ -1022,7 +1216,7 @@ def _pole_degree(poly): y *= x - i return roots(s.rep, filter='R').keys() - def evalf(self, points, method='RK4'): + def evalf(self, points, method='RK4', h=0.05, derivatives=False): """ Finds numerical value of a holonomic function using numerical methods. (RK4 by default). A set of points (real or complex) must be provided @@ -1062,10 +1256,33 @@ def evalf(self, points, method='RK4'): """ from sympy.holonomic.numerical import _evalf + lp = False + + # if a point `b` is given instead of a mesh + if not hasattr(points, "__iter__"): + lp = True + b = S(points) + if self.x0 == b: + return _evalf(self, [b], method=method, derivatives=derivatives)[-1] + + if not b.is_Number: + raise NotImplementedError + + a = self.x0 + if a > b: + h = -h + n = int((b - a) / h) + points = [a + h] + for i in range(n - 1): + points.append(points[-1] + h) + for i in roots(self.annihilator.listofpoly[-1].rep): if i == self.x0 or i in points: raise TypeError("Provided path contains a singularity") - return _evalf(self, points, method=method) + + if lp: + return _evalf(self, points, method=method, derivatives=derivatives)[-1] + return _evalf(self, points, method=method, derivatives=derivatives) def _subs(self, z): """ @@ -1123,6 +1340,18 @@ def to_hyper(self): # order of the recurrence relation m = r.order + # when no recurrence exists, and the power series have finite terms + if m == 0: + nonzeroterms = roots(r.listofpoly[0].rep, filter='Z') + if max(nonzeroterms) >= len(u0): + raise NotImplementedError("Initial conditions aren't sufficient") + sol = S(0) + for i in nonzeroterms: + if i >= 0: + sol += u0[i] * x**i + return sol + + if smallest_n + m > len(u0): raise NotImplementedError("Can't compute sufficient Initial Conditions") @@ -1135,7 +1364,7 @@ def to_hyper(self): is_hyper = False break - if not is_hyper or m == 0: + if not is_hyper: raise TypeError("The series is not Hypergeometric") a = r.listofpoly[0] @@ -1214,6 +1443,37 @@ def to_sympy(self): return hyperexpand(self.to_hyper()).simplify() + def change_ics(self, b): + """ + Changes the point `x0` to `b` for initial conditions. + + Examples + ======== + + >>> from sympy.holonomic import from_sympy + >>> from sympy import symbols, sin, cos, exp + >>> x = symbols('x') + + >>> from_sympy(sin(x)).change_ics(1) + HolonomicFunction((1) + (1)Dx**2, x), f(1) = sin(1), f'(1) = cos(1) + + >>> from_sympy(exp(x)).change_ics(2) + HolonomicFunction((-1) + (1)Dx, x), f(2) = exp(2) + """ + + symbolic = True + + try: + sol = from_sympy(self.to_sympy(), x0=b) + except: + symbolic = False + + if symbolic: + return sol + + y0 = self.evalf(b, derivatives=True) + return HolonomicFunction(self.annihilator, self.x, b, y0) + def from_hyper(func, x0=0, evalf=False): """ @@ -1376,7 +1636,7 @@ def _find_conditions(simp, x, x0, order, evalf=False): from sympy.integrals.meijerint import _mytype -def from_sympy(func, x=None, initcond=True): +def from_sympy(func, x=None, initcond=True, x0=0): """ Uses `meijerint._rewrite1` to convert to `meijerg` function and then eventually to Holonomic Functions. Only works when `meijerint._rewrite1` @@ -1404,7 +1664,7 @@ def from_sympy(func, x=None, initcond=True): x = func.atoms(Symbol).pop() # try to convert if the function is polynomial or rational - solpoly = _convert_poly_rat(func, x, initcond=initcond) + solpoly = _convert_poly_rat(func, x, initcond=initcond, x0=x0) if solpoly: return solpoly @@ -1425,7 +1685,6 @@ def from_sympy(func, x=None, initcond=True): sol = _convert_meijerint(func, x, initcond=False) if not sol: raise NotImplementedError - x0 = 0 y0 = _find_conditions(func, x, x0, sol.annihilator.order) while not y0: x0 += 1 @@ -1435,7 +1694,6 @@ def from_sympy(func, x=None, initcond=True): if not initcond: return sol.composition(func.args[0]) - x0 = 0 y0 = _find_conditions(func, x, x0, sol.annihilator.order) while not y0: x0 += 1 @@ -1464,7 +1722,6 @@ def from_sympy(func, x=None, initcond=True): if not initcond: return sol - x0 = 0 y0 = _find_conditions(func, x, x0, sol.annihilator.order) while not y0: x0 += 1 @@ -1484,8 +1741,7 @@ def _normalize(list_of, parent, negative=True): denom = [] base = parent.base K = base.get_field() - R = ZZ.old_poly_ring(base.gens[0]) - lcm_denom = R.from_sympy(S(1)) + lcm_denom = base.from_sympy(S(1)) list_of_coeff = [] # convert polynomials to the elements of associated @@ -1499,15 +1755,10 @@ def _normalize(list_of, parent, negative=True): list_of_coeff.append(j) # corresponding numerators of the sequence of polynomials - num.append(base(list_of_coeff[i].num)) + num.append(list_of_coeff[i].numer()) # corresponding denominators - den = list_of_coeff[i].den - if isinstance(den[0], PythonRational): - for i, j in enumerate(den): - den[i] = j.p - - denom.append(R(den)) + denom.append(list_of_coeff[i].denom()) # lcm of denominators in the coefficients for i in denom: @@ -1522,7 +1773,7 @@ def _normalize(list_of, parent, negative=True): for i, j in enumerate(list_of_coeff): list_of_coeff[i] = j * lcm_denom - gcd_numer = base.from_FractionField(list_of_coeff[-1], K) + gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep) # gcd of numerators in the coefficients for i in num: @@ -1532,7 +1783,8 @@ def _normalize(list_of, parent, negative=True): # divide all the coefficients by the gcd for i, j in enumerate(list_of_coeff): - list_of_coeff[i] = base.from_FractionField(j / gcd_numer, K) + frac_ans = j / gcd_numer + list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep) return DifferentialOperator(list_of_coeff, parent) @@ -1618,7 +1870,7 @@ def DMFdiff(frac): return K((sol_num.rep, sol_denom.rep)) -def DMFsubs(frac, x0): +def DMFsubs(frac, x0, mpm=False): # substitute the point x0 in DMF object of the form p/q if not isinstance(frac, DMF): return frac @@ -1628,20 +1880,23 @@ def DMFsubs(frac, x0): sol_p = S(0) sol_q = S(0) + if mpm: + from mpmath import mp + for i, j in enumerate(reversed(p)): - if isinstance(j, PythonRational): - j = sympify(j) + if mpm: + j = sympify(j)._to_mpmath(mp.prec) sol_p += j * x0**i for i, j in enumerate(reversed(q)): - if isinstance(j, PythonRational): - j = sympify(j) + if mpm: + j = sympify(j)._to_mpmath(mp.prec) sol_q += j * x0**i return sol_p / sol_q -def _convert_poly_rat(func, x, initcond=True): +def _convert_poly_rat(func, x, initcond=True, x0=0): """Converts Polynomials and Rationals to Holonomic. """ @@ -1657,6 +1912,10 @@ def _convert_poly_rat(func, x, initcond=True): R = QQ.old_poly_ring(x) _, Dx = DifferentialOperators(R, 'Dx') + # if the function is constant + if not func.has(x): + return HolonomicFunction(Dx, x, 0, func) + if ispoly: # differential equation satisfied by polynomial sol = func * Dx - func.diff() @@ -1672,7 +1931,6 @@ def _convert_poly_rat(func, x, initcond=True): if not initcond: return HolonomicFunction(sol, x) - x0 = 0 y0 = _find_conditions(func, x, x0, sol.order) while not y0: x0 += 1 @@ -1771,6 +2029,8 @@ def _find_conditions(func, x, x0, order): y0 = [] for i in range(order): val = func.subs(x, x0) + if isinstance(val, NaN): + val = limit(func, x, x0) if (val.is_finite is not None and not val.is_finite) or isinstance(val, NaN): return None y0.append(val) diff --git a/sympy/holonomic/numerical.py b/sympy/holonomic/numerical.py index c91b6836f5..afbcd1b242 100644 --- a/sympy/holonomic/numerical.py +++ b/sympy/holonomic/numerical.py @@ -58,7 +58,7 @@ def _euler(red, x0, x1, y0, a): f_0_n = 0 for i in range(a): - f_0_n += sympify(DMFsubs(red[i], A))._to_mpmath(mp.prec) * y_0[i] + f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i] f_0.append(f_0_n) sol = [] @@ -85,22 +85,22 @@ def _rk4(red, x0, x1, y0, a): f_0 = y_0[1:] for i in range(a): - f_0_n += sympify(DMFsubs(red[i], A))._to_mpmath(mp.prec) * y_0[i] + f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i] f_0.append(f_0_n) f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)] for i in range(a): - f_1_n += sympify(DMFsubs(red[i], A + h/2))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2) + f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2) f_1.append(f_1_n) f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)] for i in range(a): - f_2_n += sympify(DMFsubs(red[i], A + h/2))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2) + f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2) f_2.append(f_2_n) f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)] for i in range(a): - f_3_n += sympify(DMFsubs(red[i], A + h))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h) + f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h) f_3.append(f_3_n) sol = []
Add a docstring how to plot a holonomic function Something like this: ``` import sympy.holonomic import numpy as np r = np.linspace(1, 5, 100) y = sympy.holonomic.from_sympy(sin(x)**2/x).evalf(r) plot(r, y) ``` This should be part of some larger docstring, or part of a tutorial for the holonomic module. Here is a jupyter notebook showing that it works: http://nbviewer.jupyter.org/gist/certik/849a62d23f615d89dd37585b76159e78 cc @shubhamtibra .
sympy/sympy
diff --git a/sympy/holonomic/tests/test_holonomic.py b/sympy/holonomic/tests/test_holonomic.py index d917e4c9f7..643df52114 100644 --- a/sympy/holonomic/tests/test_holonomic.py +++ b/sympy/holonomic/tests/test_holonomic.py @@ -2,7 +2,7 @@ DifferentialOperators, from_hyper, from_meijerg, from_sympy) from sympy.holonomic.recurrence import RecurrenceOperators, HolonomicSequence from sympy import (symbols, hyper, S, sqrt, pi, exp, erf, erfc, sstr, - O, I, meijerg, sin, cos, log, cosh, besselj, hyperexpand) + O, I, meijerg, sin, cos, log, cosh, besselj, hyperexpand, Ci, EulerGamma, Si) from sympy import ZZ, QQ @@ -91,8 +91,8 @@ def test_addition_initial_condition(): assert p + q == r p = HolonomicFunction(Dx - x + Dx**2, x, 0, [1, 2]) q = HolonomicFunction(Dx**2 + x, x, 0, [1, 0]) - r = HolonomicFunction((-4*x**4 - x**3 - 4*x**2 + 1) + (4*x**3 + x**2 + 3*x + 4)*Dx + \ - (-6*x + 7)*Dx**2 + (4*x**2 - 7*x + 1)*Dx**3 + (4*x**2 + x + 2)*Dx**4, x, 0, [2, 2, -2, 2]) + r = HolonomicFunction((-x**4 - x**3/4 - x**2 + 1/4) + (x**3 + x**2/4 + 3*x/4 + 1)*Dx + \ + (-3*x/2 + 7/4)*Dx**2 + (x**2 - 7*x/4 + 1/4)*Dx**3 + (x**2 + x/4 + 1/2)*Dx**4, x, 0, [2, 2, -2, 2]) assert p + q == r p = HolonomicFunction(Dx**2 + 4*x*Dx + x**2, x, 0, [3, 4]) q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1]) @@ -105,6 +105,11 @@ def test_addition_initial_condition(): r = HolonomicFunction((-x**2 - x + 1) + (x**2 + x)*Dx + (-x - 2)*Dx**3 + \ (x + 1)*Dx**4, x, 2, [4, 1, 2, -5 ]) assert p + q == r + p = from_sympy(sin(x)) + q = from_sympy(1/x) + r = HolonomicFunction((x**2 + 6) + (x**3 + 2*x)*Dx + (x**2 + 6)*Dx**2 + (x**3 + 2*x)*Dx**3, \ + x, 1, [sin(1) + 1, -1 + cos(1), -sin(1) + 2]) + assert p + q == r def test_multiplication_initial_condition(): x = symbols('x') @@ -116,12 +121,12 @@ def test_multiplication_initial_condition(): assert p * q == r p = HolonomicFunction(Dx**2 + x, x, 0, [1, 0]) q = HolonomicFunction(Dx**3 - x**2, x, 0, [3, 3, 3]) - r = HolonomicFunction((27*x**8 - 37*x**7 - 10*x**6 - 492*x**5 - 552*x**4 + 160*x**3 + \ - 1212*x**2 + 216*x + 360) + (162*x**7 - 384*x**6 - 294*x**5 - 84*x**4 + 24*x**3 + \ - 756*x**2 + 120*x - 1080)*Dx + (81*x**6 - 246*x**5 + 228*x**4 + 36*x**3 + \ - 660*x**2 - 720*x)*Dx**2 + (-54*x**6 + 128*x**5 - 18*x**4 - 240*x**2 + 600)*Dx**3 + \ - (81*x**5 - 192*x**4 - 84*x**3 + 162*x**2 - 60*x - 180)*Dx**4 + (-108*x**3 + \ - 192*x**2 + 72*x)*Dx**5 + (27*x**4 - 64*x**3 - 36*x**2 + 60)*Dx**6, x, 0, [3, 3, 3, -3, -12, -24]) + r = HolonomicFunction((x**8 - 37*x**7/27 - 10*x**6/27 - 164*x**5/9 - 184*x**4/9 + \ + 160*x**3/27 + 404*x**2/9 + 8*x + 40/3) + (6*x**7 - 128*x**6/9 - 98*x**5/9 - 28*x**4/9 + \ + 8*x**3/9 + 28*x**2 + 40*x/9 - 40)*Dx + (3*x**6 - 82*x**5/9 + 76*x**4/9 + 4*x**3/3 + \ + 220*x**2/9 - 80*x/3)*Dx**2 + (-2*x**6 + 128*x**5/27 - 2*x**4/3 -80*x**2/9 + 200/9)*Dx**3 + \ + (3*x**5 - 64*x**4/9 - 28*x**3/9 + 6*x**2 - 20*x/9 - 20/3)*Dx**4 + (-4*x**3 + 64*x**2/9 + \ + 8*x/3)*Dx**5 + (x**4 - 64*x**3/27 - 4*x**2/3 + 20/9)*Dx**6, x, 0, [3, 3, 3, -3, -12, -24]) assert p * q == r p = HolonomicFunction(Dx - 1, x, 0, [2]) q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) @@ -134,6 +139,10 @@ def test_multiplication_initial_condition(): q = HolonomicFunction(Dx**3 + 1, x, 0, [1, 2, 1]) r = HolonomicFunction(6*Dx + 3*Dx**2 + 2*Dx**3 - 3*Dx**4 + Dx**6, x, 0, [1, 5, 14, 17, 17, 2]) assert p * q == r + p = from_sympy(sin(x)) + q = from_sympy(1/x) + r = HolonomicFunction(x + 2*Dx + x*Dx**2, x, 1, [sin(1), -sin(1) + cos(1)]) + assert p * q == r def test_HolonomicFunction_composition(): x = symbols('x') @@ -168,7 +177,7 @@ def test_from_hyper(): r = from_hyper(p) assert r == q p = from_hyper(hyper([1], [S(3)/2], x**2/4)) - q = HolonomicFunction(-2*x + (-x**2 + 4)*Dx + 2*x*Dx**2, x) + q = HolonomicFunction(-x + (-x**2/2 + 2)*Dx + x*Dx**2, x) x0 = 1 y0 = '[sqrt(pi)*exp(1/4)*erf(1/2), -sqrt(pi)*exp(1/4)*erf(1/2)/2 + 1]' assert sstr(p.y0) == y0 @@ -178,14 +187,14 @@ def test_from_meijerg(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = from_meijerg(meijerg(([], [S(3)/2]), ([S(1)/2], [S(1)/2, 1]), x)) - q = HolonomicFunction(2*x - 1 + (-4*x**2 + x)*Dx + 4*x**2*Dx**2 + 4*x**3*Dx**3, x, 1, \ + q = HolonomicFunction(x/2 - 1/4 + (-x**2 + x/4)*Dx + x**2*Dx**2 + x**3*Dx**3, x, 1, \ [1/sqrt(pi), 1/(2*sqrt(pi)), -1/(4*sqrt(pi))]) assert p == q p = from_meijerg(meijerg(([], []), ([0], []), x)) q = HolonomicFunction(1 + Dx, x, 0, 1) assert p == q p = from_meijerg(meijerg(([1], []), ([S(1)/2], [0]), x)) - q = HolonomicFunction((2*x + 1)*Dx + 2*x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)]) + q = HolonomicFunction((x + 1/2)*Dx + x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)]) assert p == q p = from_meijerg(meijerg(([0], [1]), ([0], []), 2*x**2)) q = HolonomicFunction((3*x**2 - 1)*Dx + x**3*Dx**2, x, 1, [-exp(-S(1)/2) + 1, -exp(-S(1)/2)]) @@ -200,13 +209,13 @@ def test_to_Sequence(): q = (HolonomicSequence(1 + (n + 2)*Sn**2 + (n**4 + 6*n**3 + 11*n**2 + 6*n)*Sn**3), 1) assert p == q p = HolonomicFunction(x**2*Dx**4 + x**3 + Dx**2, x).to_sequence() - q = (HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5, n), 0) + q = (HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5), 0) assert p == q p = HolonomicFunction(x**3*Dx**4 + 1 + Dx**2, x).to_sequence() - q = (HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2, n), 3) + q = (HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2), 3) assert p == q p = HolonomicFunction(3*x**3*Dx**4 + 2*x*Dx + x*Dx**3, x).to_sequence() - q = (HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2, n), 3) + q = (HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2), 3) assert p == q def test_to_Sequence_Initial_Coniditons(): @@ -226,6 +235,16 @@ def test_to_Sequence_Initial_Coniditons(): p = HolonomicFunction(x**3*Dx**5 + 1 + Dx, x).to_sequence() q = (HolonomicSequence(1 + (n + 1)*Sn + (n**5 - 5*n**3 + 4*n)*Sn**2), 3) assert p == q + C_1, C_2, C_3 = symbols('C_1, C_2, C_3') + p = from_sympy(log(1+x**2)) + q = (HolonomicSequence(n**2 + (n**2 + 2*n)*Sn**2, [0, 0, C_2, 0]), 2) + assert p.to_sequence() == q + p = p.diff() + q = (HolonomicSequence((n + 1) + (n + 1)*Sn**2, [0, C_1, 0]), 1) + assert p.to_sequence() == q + p = from_sympy(erf(x) + x).to_sequence() + q = (HolonomicSequence((2*n**2 - 2*n) + (n**3 + 2*n**2 - n - 2)*Sn**2, [0, 1 + 2/sqrt(pi), 0, C_3]), 2) + assert p == q def test_series(): x = symbols('x') @@ -251,6 +270,10 @@ def test_series(): (4-6*x**3+2*x**4)*Dx**2, x, 0, [1, 0]).series(n=7) q = 1 - 3*x**2/4 - x**3/4 - 5*x**4/32 - 3*x**5/40 - 17*x**6/384 + O(x**7) assert p == q + p = from_sympy(erf(x) + x).series(n=10) + C_3 = symbols('C_3') + q = (erf(x) + x).series(n=10) + assert p.subs(C_3, -2/(3*sqrt(pi))) == q def test_evalf_euler(): x = symbols('x') @@ -410,17 +433,17 @@ def test_from_sympy(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = from_sympy((sin(x)/x)**2) - q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 1, \ - [sin(1)**2, -2*sin(1)**2 + 2*sin(1)*cos(1), -8*sin(1)*cos(1) + 2*cos(1)**2 + 4*sin(1)**2]) + q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \ + [1, 0, -2/3]) assert p == q p = from_sympy(1/(1+x**2)**2) q = HolonomicFunction(4*x + (x**2 + 1)*Dx, x, 0, 1) assert p == q p = from_sympy(exp(x)*sin(x)+x*log(1+x)) - q = HolonomicFunction((4*x**3 + 20*x**2 + 40*x + 36) + (-4*x**4 - 20*x**3 - 40*x**2 \ - - 36*x)*Dx + (4*x**5 + 12*x**4 + 14*x**3 + 16*x**2 + 20*x - 8)*Dx**2 + \ - (-4*x**5 - 10*x**4 - 4*x**3 + 4*x**2 - 2*x + 8)*Dx**3 + (2*x**5 + 4*x**4 - 2*x**3 - \ - 7*x**2 + 2*x + 5)*Dx**4, x, 0, [0, 1, 4, -1]) + q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \ + - 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \ + (-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \ + 7*x**2/2 + x + 5/2)*Dx**4, x, 0, [0, 1, 4, -1]) assert p == q p = from_sympy(x*exp(x)+cos(x)+1) q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \ @@ -431,8 +454,8 @@ def test_from_sympy(): q = HolonomicFunction(Dx + (3*x + 3)*Dx**2 + (x**2 + 2*x + 1)*Dx**3, x, 0, [1, 0, 2]) assert p == q p = from_sympy(erf(x)**2 + x) - q = HolonomicFunction((32*x**4 - 8*x**2 + 8)*Dx**2 + (24*x**3 - 2*x)*Dx**3 + \ - (4*x**2+ 1)*Dx**4, x, 0, [0, 1, 8/pi, 0]) + q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \ + (x**2+ 1/4)*Dx**4, x, 0, [0, 1, 8/pi, 0]) assert p == q p = from_sympy(cosh(x)*x) q = HolonomicFunction((-x**2 + 2) -2*x*Dx + x**2*Dx**2, x, 0, [0, 1]) @@ -441,9 +464,24 @@ def test_from_sympy(): q = HolonomicFunction((x**2 - 4) + x*Dx + x**2*Dx**2, x, 0, [0, 0]) assert p == q p = from_sympy(besselj(0, x) + exp(x)) - q = HolonomicFunction((-2*x**2 - x + 1) + (2*x**2 - x - 3)*Dx + (-2*x**2 + x + 2)*Dx**2 +\ - (2*x**2 + x)*Dx**3, x, 0, [2, 1, 1/2]) + q = HolonomicFunction((-x**2 - x/2 + 1/2) + (x**2 - x/2 - 3/2)*Dx + (-x**2 + x/2 + 1)*Dx**2 +\ + (x**2 + x/2)*Dx**3, x, 0, [2, 1, 1/2]) + assert p == q + p = from_sympy(sin(x)**2/x) + q = HolonomicFunction(4 + 4*x*Dx + 3*Dx**2 + x*Dx**3, x, 0, [0, 1, 0]) assert p == q + p = from_sympy(sin(x)**2/x, x0=2) + q = HolonomicFunction((4) + (4*x)*Dx + (3)*Dx**2 + (x)*Dx**3, x, 2, [sin(2)**2/2, + sin(2)*cos(2) - sin(2)**2/4, -3*sin(2)**2/4 + cos(2)**2 - sin(2)*cos(2)]) + assert p == q + p = from_sympy(log(x)/2 - Ci(2*x)/2 + Ci(2)/2) + q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \ + [-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0]) + assert p == q + p = p.to_sympy() + q = log(x)/2 - Ci(2*x)/2 + Ci(2)/2 + assert p == q + def test_to_hyper(): x = symbols('x') @@ -487,3 +525,51 @@ def test_to_sympy(): (x**2 - x)*Dx**2, x, 0, [1, 2]).to_sympy() q = 1/(x**2 - 2*x + 1) assert p == q + p = from_sympy(sin(x)**2/x).integrate((x, 0, x)).to_sympy() + q = (sin(x)**2/x).integrate((x, 0, x)) + assert p == q + C_1, C_2, C_3 = symbols('C_1, C_2, C_3') + p = from_sympy(log(1+x**2)).to_sympy() + q = C_2*log(x**2 + 1) + assert p == q + p = from_sympy(log(1+x**2)).diff().to_sympy() + q = C_1*x/(x**2 + 1) + assert p == q + p = from_sympy(erf(x) + x).to_sympy() + q = 3*C_3*x - 3*sqrt(pi)*C_3*erf(x)/2 + x + 2*x/sqrt(pi) + assert p == q + +def test_integrate(): + x = symbols('x') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = from_sympy(sin(x)**2/x, x0=1).integrate((x, 2, 3)) + q = '0.166270406994788' + assert sstr(p) == q + p = from_sympy(sin(x)).integrate((x, 0, x)).to_sympy() + q = 1 - cos(x) + assert p == q + p = from_sympy(sin(x)).integrate((x, 0, 3)) + q = '1.98999246812687' + assert sstr(p) == q + p = from_sympy(sin(x)/x, x0=1).integrate((x, 1, 2)) + q = '0.659329913368450' + assert sstr(p) == q + p = from_sympy(sin(x)**2/x, x0=1).integrate((x, 1, 0)) + q = '-0.423690480850035' + assert sstr(p) == q + +def test_diff(): + x, y = symbols('x, y') + R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + p = HolonomicFunction(x*Dx**2 + 1, x, 0, [0, 1]) + assert p.diff().to_sympy() == p.to_sympy().diff().simplify() + p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]) + assert p.diff(x, 2).to_sympy() == p.to_sympy() + p = from_sympy(Si(x)) + assert p.diff().to_sympy() == sin(x)/x + assert p.diff(y) == 0 + C_1, C_2, C_3 = symbols('C_1, C_2, C_3') + q = Si(x) + assert p.diff(x).to_sympy() == q.diff() + assert p.diff(x, 2).to_sympy().subs(C_1, -S(1)/3) == q.diff(x, 2).simplify() + assert p.diff(x, 3).series().subs(C_2, S(1)/10) == q.diff(x, 3).series()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 3 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mpmath>=0.19", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi exceptiongroup==1.2.2 importlib-metadata==6.7.0 iniconfig==2.0.0 mpmath==1.3.0 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 -e git+https://github.com/sympy/sympy.git@230b1bf3a3a67c0621a3b4a8f2a45e950f82393f#egg=sympy tomli==2.0.1 typing_extensions==4.7.1 zipp==3.15.0
name: sympy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - mpmath==1.3.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - tomli==2.0.1 - typing-extensions==4.7.1 - zipp==3.15.0 prefix: /opt/conda/envs/sympy
[ "sympy/holonomic/tests/test_holonomic.py::test_addition_initial_condition", "sympy/holonomic/tests/test_holonomic.py::test_multiplication_initial_condition", "sympy/holonomic/tests/test_holonomic.py::test_from_hyper", "sympy/holonomic/tests/test_holonomic.py::test_from_meijerg", "sympy/holonomic/tests/test_holonomic.py::test_to_Sequence_Initial_Coniditons", "sympy/holonomic/tests/test_holonomic.py::test_series", "sympy/holonomic/tests/test_holonomic.py::test_from_sympy", "sympy/holonomic/tests/test_holonomic.py::test_to_sympy", "sympy/holonomic/tests/test_holonomic.py::test_integrate", "sympy/holonomic/tests/test_holonomic.py::test_diff" ]
[ "sympy/holonomic/tests/test_holonomic.py::test_to_hyper" ]
[ "sympy/holonomic/tests/test_holonomic.py::test_DifferentialOperator", "sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_addition", "sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_multiplication", "sympy/holonomic/tests/test_holonomic.py::test_HolonomicFunction_composition", "sympy/holonomic/tests/test_holonomic.py::test_to_Sequence", "sympy/holonomic/tests/test_holonomic.py::test_evalf_euler", "sympy/holonomic/tests/test_holonomic.py::test_evalf_rk4" ]
[]
BSD
599
simphony__simphony-remote-21
ca4d029fe1edd54e62a20809aba651401ed6f587
2016-06-27 10:40:39
d7657fa7d4297b4c922a900ba9a8a337184113ef
diff --git a/remoteappmanager/docker/container.py b/remoteappmanager/docker/container.py index f4e8677..6123205 100644 --- a/remoteappmanager/docker/container.py +++ b/remoteappmanager/docker/container.py @@ -23,7 +23,7 @@ class Container(HasTraits): ip = Unicode() #: ...and port where the container service will be listening - port = Int() + port = Int(None, allow_none=True) @property def url(self): @@ -38,3 +38,44 @@ class Container(HasTraits): ip=self.ip, port=self.port, ) + + def __repr__(self): + return ('<Container(docker_id={0}, name={1}, image_name={2}, ' + 'image_id={3}, ip={4}, port={5}>').format( + self.docker_id, self.name, + self.image_name, self.image_id, + self.ip, self.port) + + @classmethod + def from_docker_dict(cls, docker_dict): + """Returns a Container object with the info given by a + docker Client. + + Parameters + ---------- + docker_dict : dict + One item from the result of docker.Client.containers + + Returns + ------- + container : Container + + Examples + -------- + >>> # containers is a list of dict + >>> containers = docker.Client().containers() + + >>> Container.from_docker_dict(containers[0]) + """ + if docker_dict.get('Ports'): + ip = docker_dict['Ports'][0].get('IP', "") + port = docker_dict['Ports'][0].get('PublicPort') + else: + ip = "" + port = None + + return cls(docker_id=docker_dict.get('Id', ''), + name=docker_dict.get('Names', ('',))[0], + image_name=docker_dict.get('Image', ''), + image_id=docker_dict.get('ImageID', ''), + ip=ip, port=port) diff --git a/remoteappmanager/docker/container_manager.py b/remoteappmanager/docker/container_manager.py index 19559cf..94b7b39 100644 --- a/remoteappmanager/docker/container_manager.py +++ b/remoteappmanager/docker/container_manager.py @@ -93,26 +93,44 @@ class ContainerManager(LoggingMixin): self._stop_pending.remove(container_id) @gen.coroutine - def containers_for_image(self, image_id): - """Returns the containers for a given image that are managed - by this object. + def containers_for_image(self, image_id_or_name, user_name=None): + """Returns the currently running containers for a given image. + + If `user_name` is given, only returns containers started by the + given user name. It is a coroutine because we might want to run an inquire to the docker service if not present. Parameters ---------- - image_id: str - The image id + image_id_or_name: str + The image id or name + + Optional parameters + ------------------- + user_name : str + Name of the user who started the container Return ------ A list of container objects, or an empty list if not present. """ - try: - return self._containers_for_image[image_id] - except KeyError: - return [] + if user_name: + user_labels = _get_container_labels(user_name) + if user_labels: + filters = {'label': '{0}={1}'.format(*user_labels.popitem())} + else: + filters = {} + + filters['ancestor'] = image_id_or_name + + containers = yield self.docker_client.containers(filters=filters) + return [Container.from_docker_dict(container) + for container in containers + # Require further filtering as ancestor include grandparents + if (container.get('Image') == image_id_or_name or + container.get('ImageID') == image_id_or_name)] @gen.coroutine def all_images(self): diff --git a/remoteappmanager/handlers/home_handler.py b/remoteappmanager/handlers/home_handler.py index c940fe4..a9fa728 100644 --- a/remoteappmanager/handlers/home_handler.py +++ b/remoteappmanager/handlers/home_handler.py @@ -11,6 +11,7 @@ from tornado.httpclient import AsyncHTTPClient, HTTPError from tornado.log import app_log from remoteappmanager.handlers.base_handler import BaseHandler +from remoteappmanager.docker.container import Container # FIXME: replace these with ORM objects @@ -31,7 +32,7 @@ class HomeHandler(BaseHandler): for image in all_images: containers = yield container_manager.containers_for_image( - image.docker_id) + image.docker_id, self.current_user) container = (containers[0] if len(containers) > 0 else None) # For now we assume we have only one. images_info.append({ @@ -65,37 +66,47 @@ class HomeHandler(BaseHandler): exc_info=True) return - yield handler(self.current_user, options) - - # Subhandling after post - - @gen.coroutine - def _actionhandler_start(self, user_name, options): - """Sub handling. Acts in response to a "start" request from - the user.""" - # Start the single-user server - try: - image_name = options["image_name"][0] - container = yield self._start_container(user_name, image_name) + yield handler(self.current_user, options) except Exception as e: # Create a random reference number for support ref = str(uuid.uuid1()) - self.log.exception("Failed to spawn docker image. %s " - "Ref: %s", - str(e), ref) + self.log.exception("Failed with POST action: {0}. {1} " + "Ref: {2}".format( + action, str(e), ref)) images_info = yield self._get_images_info() # Render the home page again with the error message # User-facing error message (less info) - message = ('Failed to start "{image_name}". Reason: {error_type} ' + message = ('Failed to {action} "{image_name}". ' + 'Reason: {error_type} ' '(Ref: {ref})') self.render('home.html', images_info=images_info, error_message=message.format( - image_name=image_name, + action=action, + image_name=options["image_name"][0], error_type=type(e).__name__, ref=ref)) + + # Subhandling after post + + @gen.coroutine + def _actionhandler_start(self, user_name, options): + """Sub handling. Acts in response to a "start" request from + the user.""" + # Start the single-user server + + try: + # FIXME: too many operations in one try block, should be separated + # for better error handling + image_name = options["image_name"][0] + container = yield self._start_container(user_name, image_name) + yield self._wait_for_container_ready(container) + except Exception as e: + # Clean up, if the container is running + yield self._stop_and_remove_container(user_name, image_name) + raise e else: # The server is up and running. Now contact the proxy and add # the container url to it. @@ -112,10 +123,16 @@ class HomeHandler(BaseHandler): It is not different from pasting the appropriate URL in the web browser, but we validate the container id first. """ - container = self._container_from_options(options) + container = yield self._container_from_options(options) if not container: + self.finish("Unable to view the application") return + yield self._wait_for_container_ready(container) + + # in case the reverse proxy is not already set up + yield self.application.reverse_proxy_add_container(container) + url = self.application.container_url_abspath(container) self.log.info('Redirecting to ' + url) self.redirect(url) @@ -127,11 +144,18 @@ class HomeHandler(BaseHandler): app = self.application container_manager = app.container_manager - container = self._container_from_options(options) + container = yield self._container_from_options(options) if not container: + self.finish("Unable to view the application") return - yield app.reverse_proxy_remove_container(container) + try: + yield app.reverse_proxy_remove_container(container) + except HTTPError as http_error: + # The reverse proxy may be absent to start with + if http_error.code != 404: + raise http_error + yield container_manager.stop_and_remove_container(container.docker_id) # We don't have fancy stuff at the moment to change the button, so @@ -140,31 +164,35 @@ class HomeHandler(BaseHandler): # private + @gen.coroutine def _container_from_options(self, options): """Support routine to reduce duplication. Retrieves and returns the container if valid and present. - If not present, performs the http response and returns None. + + If not present, returns None """ container_manager = self.application.container_manager + try: container_id = options["container_id"][0] except (KeyError, IndexError): self.log.exception( "Failed to retrieve valid container_id from form" ) - self.finish("Unable to retrieve valid container_id value") return None - try: - container = container_manager.containers[container_id] - except KeyError: - self.log.error("Unable to find container_id {} in manager".format( - container_id)) - self.finish("Unable to find specified container_id") - return None + container_dict = yield container_manager.docker_client.containers( + filters={'id': container_id}) - return container + if container_dict: + return Container.from_docker_dict(container_dict[0]) + else: + self.log.exception( + "Failed to retrieve valid container from container id: %s", + container_id + ) + return None @gen.coroutine def _start_container(self, user_name, image_name): @@ -212,46 +240,21 @@ class HomeHandler(BaseHandler): e.reason = 'error' raise e - # Note, we use the jupyterhub ORM server, but we don't use it for - # any database activity. - # Note: the end / is important. We want to get a 200 from the actual - # websockify server, not the nginx (which presents the redirection - # page). - server_url = "http://{}:{}{}/".format( - container.ip, - container.port, - self.application.container_url_abspath(container)) + return container - try: - yield _wait_for_http_server_2xx( - server_url, - self.application.config.network_timeout) - except TimeoutError as e: - # Note: Using TimeoutError instead of gen.TimeoutError as above - # is not a mistake. - self.log.warning( - "{user}'s container never showed up at {url} " - "after {http_timeout} seconds. Giving up.".format( - user=user_name, - url=server_url, - http_timeout=self.application.config.network_timeout, - ) - ) - e.reason = 'timeout' - raise e - except Exception as e: - self.log.exception( - "Unhandled error waiting for {user}'s server " - "to show up at {url}: {error}".format( - user=user_name, - url=server_url, - error=e, - ) - ) - e.reason = 'error' - raise e + @gen.coroutine + def _stop_and_remove_container(self, user_name, image_name): + """ Stop and remove the container associated with the given + user name and image name, if exists. + """ + container_manager = self.application.container_manager + containers = yield container_manager.containers_for_image( + image_name, user_name) - return container + # Assume only one container per image + if containers: + container_id = containers[0].docker_id + yield container_manager.stop_and_remove_container(container_id) def _parse_form(self): """Extract the form options from the form and return them @@ -262,6 +265,29 @@ class HomeHandler(BaseHandler): return form_options + @gen.coroutine + def _wait_for_container_ready(self, container): + """ Wait until the container is ready to be connected + + Parameters + ---------- + container: Container + The container to be connected + """ + # Note, we use the jupyterhub ORM server, but we don't use it for + # any database activity. + # Note: the end / is important. We want to get a 200 from the actual + # websockify server, not the nginx (which presents the redirection + # page). + server_url = "http://{}:{}{}/".format( + container.ip, + container.port, + self.application.container_url_abspath(container)) + + yield _wait_for_http_server_2xx( + server_url, + self.application.config.network_timeout) + @gen.coroutine def _wait_for_http_server_2xx(url, timeout=10):
Running containers not in cache when container is started without a public port Start any incompatible image not exposing a port (e.g. `quay.io/travisci/travis-python:latest`), the container is up and running but we do not keep it in our cache of running containers because the port is unavailable (an exception is raised). From the user point of view, there is no View/Stop button which makes sense. From the admin point of view, the container has to be stopped and removed automatically. Needed for #6
simphony/simphony-remote
diff --git a/tests/docker/test_container.py b/tests/docker/test_container.py index 7d1cbae..faea36f 100644 --- a/tests/docker/test_container.py +++ b/tests/docker/test_container.py @@ -1,6 +1,7 @@ from unittest import TestCase from remoteappmanager.docker.container import Container +from tests.utils import assert_containers_equal class TestContainer(TestCase): @@ -18,3 +19,64 @@ class TestContainer(TestCase): ) self.assertEqual(container.host_url, "http://123.45.67.89:31337") + + def test_from_docker_dict_with_public_port(self): + '''Test convertion from "docker ps" to Container with public port''' + # With public port + container_dict = { + 'Command': '/startup.sh', + 'Created': 1466756760, + 'HostConfig': {'NetworkMode': 'default'}, + 'Id': '248e45e717cd740ae763a1c565', + 'Image': 'empty-ubuntu:latest', + 'ImageID': 'sha256:f4610c7580b8f0a9a25086b6287d0069fb8a', + 'Labels': {'eu.simphony-project.docker.ui_name': 'Empty Ubuntu', + 'eu.simphony-project.docker.user': 'user'}, + 'Names': ['/remoteexec-user-empty-ubuntu_3Alatest'], + 'Ports': [{'IP': '0.0.0.0', + 'PrivatePort': 8888, + 'PublicPort': 32823, + 'Type': 'tcp'}], + 'State': 'running', + 'Status': 'Up 56 minutes'} + + # Container with public port + actual = Container.from_docker_dict(container_dict) + expected = Container( + docker_id='248e45e717cd740ae763a1c565', + name='/remoteexec-user-empty-ubuntu_3Alatest', + image_name='empty-ubuntu:latest', + image_id='sha256:f4610c7580b8f0a9a25086b6287d0069fb8a', + ip='0.0.0.0', port=32823) + + assert_containers_equal(self, actual, expected) + + def test_from_docker_dict_without_public_port(self): + '''Test convertion from "docker ps" to Container with public port''' + # With public port + container_dict = { + 'Command': '/startup.sh', + 'Created': 1466756760, + 'HostConfig': {'NetworkMode': 'default'}, + 'Id': '812c765d0549be0ab831ae8348', + 'Image': 'novnc-ubuntu:latest', + 'ImageID': 'sha256:f4610c75d3c0dfa25d3c0dfa25d3c0dfa2', + 'Labels': {'eu.simphony-project.docker.ui_name': 'Empty Ubuntu', + 'eu.simphony-project.docker.user': 'user'}, + 'Names': ['/remoteexec-user-empty-ubuntu_3Alatest'], + 'Ports': [{'IP': '0.0.0.0', + 'PrivatePort': 8888, + 'Type': 'tcp'}], + 'State': 'running', + 'Status': 'Up 56 minutes'} + + # Container without public port + actual = Container.from_docker_dict(container_dict) + expected = Container( + docker_id='812c765d0549be0ab831ae8348', + name='/remoteexec-user-empty-ubuntu_3Alatest', + image_name='novnc-ubuntu:latest', + image_id='sha256:f4610c75d3c0dfa25d3c0dfa25d3c0dfa2', + ip='0.0.0.0', port=None) + + assert_containers_equal(self, actual, expected) diff --git a/tests/docker/test_container_manager.py b/tests/docker/test_container_manager.py index f878bb1..5ed4774 100644 --- a/tests/docker/test_container_manager.py +++ b/tests/docker/test_container_manager.py @@ -33,24 +33,63 @@ class TestContainerManager(AsyncTestCase): self.assertTrue(mock_client.remove_container.called) @gen_test - def test_container_for_image(self): - result = yield self.manager.containers_for_image("imageid") - self.assertEqual(len(result), 0) + def test_containers_for_image_results(self): + ''' Test containers_for_image returns a list of Container ''' + # The mock client mocks the output of docker Client.containers + docker_client = utils.mock_docker_client_with_running_containers() + self.mock_docker_client = docker_client + self.manager.docker_client.client = docker_client + + # The output should be a list of Container + results = yield self.manager.containers_for_image("imageid") + expected = [Container(docker_id='someid', + name='/remoteexec-image_3Alatest_user', + image_name='simphony/mayavi-4.4.4:latest', # noqa + image_id='imageid', ip='0.0.0.0', port=None), + Container(docker_id='someid', + name='/remoteexec-image_3Alatest_user2', + image_name='simphony/mayavi-4.4.4:latest', # noqa + image_id='imageid', ip='0.0.0.0', port=None), + Container(docker_id='someid', + name='/remoteexec-image_3Alatest_user3', + image_name='simphony/mayavi-4.4.4:latest', # noqa + image_id='imageid', ip='', port=None)] + + for result, expected_container in zip(results, expected): + utils.assert_containers_equal(self, result, expected_container) - yield self.manager.start_container("username", "imageid") + @gen_test + def test_containers_for_image_client_api_without_user(self): + ''' Test containers_for_images(image_id) use of Client API''' + # The mock client mocks the output of docker Client.containers + docker_client = utils.mock_docker_client_with_running_containers() + self.manager.docker_client.client = docker_client - result = yield self.manager.containers_for_image("imageid") - self.assertEqual(len(result), 1) + # We assume the client.containers(filters=...) is tested by docker-py + # Instead we test if the correct arguments are passed to the Client API + yield self.manager.containers_for_image("imageid") + call_args = self.manager.docker_client.client.containers.call_args - expected = {'name': 'remoteexec-username-imageid', - 'image_id': 'imageid', - 'image_name': 'imageid', - 'ip': '127.0.0.1', - 'port': 666, - 'docker_id': 'containerid'} + # filters is one of the keyword argument + self.assertIn('filters', call_args[1]) + self.assertEqual(call_args[1]['filters']['ancestor'], "imageid") - for key, value in expected.items(): - self.assertEqual(getattr(result[0], key), value) + @gen_test + def test_containers_for_image_client_api_with_user(self): + ''' Test containers_for_images(image_id, user) use of Client API''' + # The mock client mocks the output of docker Client.containers + docker_client = utils.mock_docker_client_with_running_containers() + self.manager.docker_client.client = docker_client + + # We assume the client.containers(filters=...) is tested by docker-py + # Instead we test if the correct arguments are passed to the Client API + yield self.manager.containers_for_image("imageid", "userABC") + call_args = self.manager.docker_client.client.containers.call_args + + # filters is one of the keyword argument + self.assertIn('filters', call_args[1]) + self.assertEqual(call_args[1]['filters']['ancestor'], "imageid") + self.assertIn("userABC", call_args[1]['filters']['label']) @gen_test def test_race_condition_spawning(self): diff --git a/tests/utils.py b/tests/utils.py index ed44914..f957a35 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -47,6 +47,56 @@ def mock_docker_client(): return docker_client +def mock_docker_client_with_running_containers(): + """Same as above, but it behaves as if one of the images have two + containers running for different users.""" + client = mock_docker_client() + client.containers.return_value = [ + # user + {'Command': '/sbin/init -D', + 'Created': 1466766499, + 'HostConfig': {'NetworkMode': 'default'}, + 'Id': 'someid', + 'Image': 'simphony/mayavi-4.4.4:latest', + 'ImageID': 'imageid', + 'Labels': {'eu.simphony-project.docker.user': 'user'}, + 'Names': ['/remoteexec-image_3Alatest_user'], + 'Ports': [{'IP': '0.0.0.0', + 'PublicIP': 34567, + 'PrivatePort': 22, + 'Type': 'tcp'}], + 'State': 'running', + 'Status': 'Up About an hour'}, + # user2 + {'Command': '/sbin/init -D', + 'Created': 1466766499, + 'HostConfig': {'NetworkMode': 'default'}, + 'Id': 'someid', + 'Image': 'simphony/mayavi-4.4.4:latest', + 'ImageID': 'imageid', + 'Labels': {'eu.simphony-project.docker.user': 'user2'}, + 'Names': ['/remoteexec-image_3Alatest_user2'], + 'Ports': [{'IP': '0.0.0.0', + 'PublicIP': 34567, + 'PrivatePort': 22, + 'Type': 'tcp'}], + 'State': 'running', + 'Status': 'Up About an hour'}, + # user3 (somehow there is no port + {'Command': '/sbin/init -D', + 'Created': 1466766499, + 'HostConfig': {'NetworkMode': 'default'}, + 'Id': 'someid', + 'Image': 'simphony/mayavi-4.4.4:latest', + 'ImageID': 'imageid', + 'Labels': {'eu.simphony-project.docker.user': 'user3'}, + 'Names': ['/remoteexec-image_3Alatest_user3'], + 'State': 'running', + 'Status': 'Up About an hour'}] + + return client + + def mock_docker_client_with_existing_stopped_container(): """Same as above, but it behaves as if one of the containers is already started.""" @@ -167,3 +217,14 @@ def invocation_argv(): yield sys.argv[:] = saved_argv + + +def assert_containers_equal(test_case, actual, expected): + if (expected.docker_id != actual.docker_id or + expected.name != actual.name or + expected.image_name != actual.image_name or + expected.image_id != actual.image_id or + expected.ip != actual.ip or + expected.port != actual.port): + message = '{!r} is not identical to the expected {!r}' + test_case.fail(message.format(actual, expected))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "flake8", "sphinx", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y docker.io" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 alembic==1.15.2 annotated-types==0.7.0 arrow==1.3.0 async-generator==1.10 attrs==25.3.0 babel==2.17.0 certifi==2025.1.31 certipy==0.2.2 cffi==1.17.1 charset-normalizer==3.4.1 cryptography==44.0.2 docker-py==1.10.6 docker-pycreds==0.4.0 docutils==0.21.2 escapism==1.0.1 exceptiongroup==1.2.2 flake8==7.2.0 fqdn==1.5.1 greenlet==3.1.1 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 isoduration==20.11.0 Jinja2==3.1.6 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyterhub==5.2.1 Mako==1.3.9 MarkupSafe==3.0.2 mccabe==0.7.0 oauthlib==3.2.2 packaging==24.2 pamela==1.2.0 platformdirs==4.3.7 pluggy==1.5.0 prometheus_client==0.21.1 pycodestyle==2.13.0 pycparser==2.22 pydantic==2.11.1 pydantic_core==2.33.0 pyflakes==3.3.1 Pygments==2.19.1 pytest==8.3.5 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 PyYAML==6.0.2 pyzmq==26.3.0 referencing==0.36.2 -e git+https://github.com/simphony/simphony-remote.git@ca4d029fe1edd54e62a20809aba651401ed6f587#egg=remoteappmanager requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 SQLAlchemy==2.0.40 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing-inspection==0.4.0 typing_extensions==4.13.0 uri-template==1.3.0 urllib3==2.3.0 webcolors==24.11.1 websocket-client==1.8.0 zipp==3.21.0
name: simphony-remote channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - alembic==1.15.2 - annotated-types==0.7.0 - arrow==1.3.0 - async-generator==1.10 - attrs==25.3.0 - babel==2.17.0 - certifi==2025.1.31 - certipy==0.2.2 - cffi==1.17.1 - charset-normalizer==3.4.1 - cryptography==44.0.2 - docker-py==1.10.6 - docker-pycreds==0.4.0 - docutils==0.21.2 - escapism==1.0.1 - exceptiongroup==1.2.2 - flake8==7.2.0 - fqdn==1.5.1 - greenlet==3.1.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - isoduration==20.11.0 - jinja2==3.1.6 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyterhub==5.2.1 - mako==1.3.9 - markupsafe==3.0.2 - mccabe==0.7.0 - oauthlib==3.2.2 - packaging==24.2 - pamela==1.2.0 - platformdirs==4.3.7 - pluggy==1.5.0 - prometheus-client==0.21.1 - pycodestyle==2.13.0 - pycparser==2.22 - pydantic==2.11.1 - pydantic-core==2.33.0 - pyflakes==3.3.1 - pygments==2.19.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pyyaml==6.0.2 - pyzmq==26.3.0 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - sqlalchemy==2.0.40 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - typing-inspection==0.4.0 - uri-template==1.3.0 - urllib3==2.3.0 - webcolors==24.11.1 - websocket-client==1.8.0 - zipp==3.21.0 prefix: /opt/conda/envs/simphony-remote
[ "tests/docker/test_container.py::TestContainer::test_from_docker_dict_with_public_port", "tests/docker/test_container.py::TestContainer::test_from_docker_dict_without_public_port", "tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_client_api_with_user", "tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_client_api_without_user", "tests/docker/test_container_manager.py::TestContainerManager::test_containers_for_image_results" ]
[]
[ "tests/docker/test_container.py::TestContainer::test_host_url", "tests/docker/test_container.py::TestContainer::test_url", "tests/docker/test_container_manager.py::TestContainerManager::test_instantiation", "tests/docker/test_container_manager.py::TestContainerManager::test_race_condition_spawning", "tests/docker/test_container_manager.py::TestContainerManager::test_start_already_present_container", "tests/docker/test_container_manager.py::TestContainerManager::test_start_container_with_nonexisting_volume_source", "tests/docker/test_container_manager.py::TestContainerManager::test_start_stop" ]
[]
BSD 3-Clause "New" or "Revised" License
600