foo(); bar(); return 0; } """ def get_testdirectory_name(test_directory): return os.path.join(os.path.dirname(__file__), 'test_files', test_directory) CPPCleanBearTest = verify_local_bear(CPPCleanBear, valid_files=(good_file, ), invalid_files=( bad_file, test_include_paths_file, ), tempfile_kwargs={'suffix': '.cpp'}) CPPCleanBearValidIncludeMultiplePathTest = verify_local_bear( CPPCleanBear, valid_files=(test_include_paths_file, ), invalid_files=(), settings={ 'include_paths': escape(get_testdirectory_name('headers1'), '\\') + ',' + escape(get_testdirectory_name('headers2'), '\\') }, tempfile_kwargs={'suffix': '.cpp'})
from bears.ruby.RubySyntaxBear import RubySyntaxBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = """ class HelloWorld def initialize(name) @name = name.capitalize end def sayHi puts "Hello #{@name}!" end end """ bad_file = """ class HelloWorld def initialize(name) @name = name.capitalize end def sayHi x = 1 # unused variables invoke a warning puts "Hello #{@name}!" end """ RubySyntaxBearTest = verify_local_bear(RubySyntaxBear, valid_files=(good_file,), invalid_files=(bad_file,))
done """ trigger_sc2060 = """ #!/usr/bin/env sh tr -cd [:digit:] """ good_zero_byte = '' good_only_eol = '\n' good_only_eol_eol = '\n\n' good_only_comment = '# this is a bash comment' invalid_file_list = (invalid_file, trigger_sc2164, trigger_sc2060,) ShellCheckBearTest = verify_local_bear(ShellCheckBear, valid_files=(valid_file,), invalid_files=invalid_file_list, ) small_files = (good_zero_byte, good_only_eol, good_only_eol_eol, good_only_comment,) SmallFileTest = verify_local_bear(ShellCheckBear, valid_files=small_files, invalid_files=(), ) IgnoreSC2164Test = verify_local_bear(ShellCheckBear, valid_files=(trigger_sc2164,), invalid_files=(), settings={ 'shellcheck_ignore': ['SC2164']}, )
bad_file_undef = """ console.log(a) """ bad_file_ifelse = """ var a = 1 if (a) { console.log(a) } else { console.log(0) } """ bad_file_func_name = """ function my_function (a) { return a } """ JSStandardBearTest = verify_local_bear(JSStandardBear, valid_files=(good_file,), invalid_files=(bad_file_indent, bad_file_quote, bad_file_semicolon, bad_file_infix, bad_file_undef, bad_file_ifelse, bad_file_func_name,))
''' bad_file = ''' """ example module level docstring """ def hello(): print("hello world") ''' PyDocStyleBearTest = verify_local_bear( PyDocStyleBear, valid_files=(good_file,), invalid_files=(bad_file,), tempfile_kwargs={'suffix': '.py'}) PyDocStyleBearIgnoreAllTest = verify_local_bear( PyDocStyleBear, valid_files=(good_file, bad_file,), invalid_files=(), settings={'pydocstyle_ignore': 'D400, D200, D103, D212'}, tempfile_kwargs={'suffix': '.py'}) # Checks if an invalid file yields results when only some errors are ignored. PyDocStyleBearIgnoreSomeTest = verify_local_bear( PyDocStyleBear, valid_files=(good_file,), invalid_files=(bad_file,),
long_length_test_file = """<?php /** * PHP_CodeSniffer tokenizes PHP code and detects violations of a defined set \ of coding.This is to test that the absoluteLineLength is violated or not. * PHP version 5 * * @category PHP * @package Your_Package * @author John Snow <*****@*****.**> * @license https://licence.txt LICENSE * @link http://somelink */ > """ PHPCodeSnifferBearTest = verify_local_bear( PHPCodeSnifferBear, valid_files=(good_file,), invalid_files=(bad_file,), tempfile_kwargs={'suffix': '.php'}) PHPCodeSnifferBearLineLengthTest = verify_local_bear( PHPCodeSnifferBear, valid_files=(long_length_test_file,), invalid_files=(), settings={'max_line_length': '160'}, tempfile_kwargs={'suffix': '.php'})
from bears.shell.ShellCheckBear import ShellCheckBear from coalib.testing.LocalBearTestHelper import verify_local_bear valid_file = """ #!/usr/bin/env sh echo "Path is $PATH" echo "$P" """ invalid_file = """ #!/usr/bin/env sh echo 'Path is $PATH' echo $P X = 24 X+=2 # += operator is supported by bash and not by sh echo $X """ ShellCheckBearTest = verify_local_bear(ShellCheckBear, valid_files=(valid_file,), invalid_files=(invalid_file,))
''' bad_file = ''' import something def hello(): print("hello world") ''' file_with_very_long_line = ('def ' + 'h' * 1000 + '():\n' + ' print("hello")') PycodestyleBearTest = verify_local_bear(PycodestyleBear, valid_files=(good_file, ), invalid_files=(bad_file, )) PycodestyleBearNoIgnoreTest = verify_local_bear( PycodestyleBear, valid_files=(good_file, ), invalid_files=(bad_file, ), settings={'pycodestyle_ignore': ''}) PycodestyleBearConfigIgnoreTest = verify_local_bear( PycodestyleBear, valid_files=(good_file, bad_file), invalid_files=[], settings={'pycodestyle_ignore': 'E303'}) PycodestyleBearConfigSelectTest = verify_local_bear(
dtd_file = os.path.join(os.path.dirname(__file__), 'test_files', 'note.dtd') schema_file = os.path.join(os.path.dirname(__file__), 'test_files', 'note.xsd') valid_xml_path = load_testdata('note.xml') valid_xml_url = load_testdata('concept-valid.xml') invalid_xml_schema = load_testdata('xsd-error.xml') invalid_xml_dtd = load_testdata('dtd-error.xml') invalid_xml_url = load_testdata('concept-invalid.xml') dtd_url = 'http://docs.oasis-open.org/dita/v1.0.1/dtd/concept.dtd' XMLBearCorrectedTest = verify_local_bear(XMLBear, valid_files=(valid_xml_file, valid_xml_chars), invalid_files=(invalid_xml_file, invalid_xml_chars), tempfile_kwargs={'suffix': '.xml'}) XMLBearSchemaTest = verify_local_bear(XMLBear, valid_files=(valid_xml_path, ), invalid_files=(invalid_xml_schema, ), settings={'xml_schema': schema_file}, tempfile_kwargs={'suffix': '.xml'}) XMLBearDTDPathTest = verify_local_bear(XMLBear, valid_files=(valid_xml_path, ), invalid_files=(invalid_xml_dtd, ), settings={'xml_dtd': dtd_file}, tempfile_kwargs={'suffix': '.xml'})
from tests.test_bears.LineCountTestBear import LineCountTestBear from coala_utils.ContextManagers import prepare_file from coalib.results.Result import Result from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY from coalib.settings.Section import Section from coalib.settings.Setting import Setting from coalib.testing.LocalBearTestHelper import verify_local_bear, execute_bear from coalib.testing.LocalBearTestHelper import LocalBearTestHelper as Helper from coalib.bearlib.aspects import ( AspectList, get as get_aspect, ) files = ('Everything is invalid/valid/raises error', ) invalidTest = verify_local_bear(TestBear, valid_files=(), invalid_files=files, settings={'result': True}) validTest = verify_local_bear(TestBear, valid_files=files, invalid_files=()) min_files = ('This is valid.', ) max_files = ('This is particularly an invalid file', ) AspectTest = verify_local_bear( AspectsGeneralTestBear, valid_files=min_files, invalid_files=max_files, aspects=AspectList([ get_aspect('LineLength')('Unknown', max_line_length=20), ]), ) PriorityAspectsTest = verify_local_bear( AspectsGeneralTestBear, valid_files=min_files,
from bears.general.KeywordBear import KeywordBear from coalib.results.HiddenResult import HiddenResult from coalib.results.SourceRange import SourceRange from coalib.settings.Section import Section from coalib.settings.Setting import Setting from coalib.testing.LocalBearTestHelper import verify_local_bear, execute_bear test_file = """ test line fix me to do error fixme """ KeywordBearTest = verify_local_bear(KeywordBear, valid_files=(test_file, ), invalid_files=('test line todo', 'test line warNING'), settings={'keywords': 'todo, warning'}) class KeywordBearDiffTest(unittest.TestCase): def setUp(self): self.section = Section('') self.section.append(Setting('language', 'python3')) self.section.append(Setting('keywords', 'TODO')) self.uut = KeywordBear(self.section, Queue()) self.annotation_bear_result_type = namedtuple('result', ['contents']) self.dep_results = { 'AnnotationBear': HiddenResult('AnnotationBear', {'comments': ()}) }
function b(object, key) { return object["key"]; }""" bad_quotes = """const a = () => 'Foo bar';""" bad_parentheses = """function b(){ """ good_parentheses = """function b() {} """ bad_indent = """if (x) { x = 0 }""" good_indent = """if (x) { x = 0; }""" PrettierLintBear = verify_local_bear(PrettierLintBear, valid_files=(good_quotes, good_file, good_parentheses, good_indent,), invalid_files=(bad_file, bad_quotes, bad_parentheses, bad_indent,))
import platform import unittest from bears.natural_language.SpellCheckBear import SpellCheckBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = 'This is correct spelling.' bad_file = 'tihs si surly som incoreclt speling.' SpellCheckLintBearTest = unittest.skipIf( platform.system() == 'Windows', "SpellCheckBear doesn't work on windows")( verify_local_bear(SpellCheckBear, valid_files=(good_file, ), invalid_files=(bad_file, )))
bad_file = """function findTitle(title) { let titleElement = 'hello'; return title; } let t = findTitle('mytitle'); t.innerHTML = 'New title'; """ tslint_config_dir = os.path.join(os.path.dirname(__file__), 'test_files') tslintconfig = os.path.join(tslint_config_dir, 'tslint.json') tslintconfig_single = os.path.join(tslint_config_dir, 'tslint-single.json') TSLintDoubleQuotesTest = verify_local_bear(TSLintBear, valid_files=(good_file, ), invalid_files=(bad_file, ), settings={ 'tslint_config': tslintconfig, 'rules_dir': tslint_config_dir, }, tempfile_kwargs={'suffix': '.ts'}) TSLintSingleQuotesTest = verify_local_bear( TSLintBear, valid_files=(bad_file, ), invalid_files=(good_file, ), settings={'tslint_config': tslintconfig_single}, tempfile_kwargs={'suffix': '.ts'})
if(TRUE){ x=1 # inline comments }else{ x=2;print("Oh no... ask the right bracket to go away!")} """ bad_file_3 = """x=(1+1+1+1+1+1+1+1+1) if(TRUE){ x=1 # inline comments }else{x=2;print("Oh no... ask the right bracket to go away!")} """ FormatRBearTest = verify_local_bear(FormatRBear, valid_files=(good_file_1,), invalid_files=(bad_file_1,)) FormatRBearRArrowToEqualTest = verify_local_bear( FormatRBear, valid_files=(good_file_2,), invalid_files=(bad_file_1,), settings={"r_use_arrows": "true"} ) FormatRBearRKeepCommentsTest = verify_local_bear( FormatRBear, valid_files=(good_file_3,), invalid_files=(good_file_1,), settings={"r_keep_comments": "false"} ) FormatRBearRBraceToNewlineTest = verify_local_bear( FormatRBear, valid_files=(good_file_4,), invalid_files=(bad_file_1,), settings={"r_braces_on_next_line": "true"} )
} """ bad_file = """ printNumber(num aNumber) { print('The number is $aNumber.') } main() { var answer = 42; // The meaning of life. printNumber(answer) } """ DartLintBearTest = verify_local_bear(DartLintBear, valid_files=(good_file, ), invalid_files=(bad_file, ), tempfile_kwargs={'suffix': '.dart'}) @generate_skip_decorator(DartLintBear) class DartLintBearConfigTest(LocalBearTestHelper): DART_VALUE_ERROR_RE = ('ValueError: DartLintBear only supports ' '`use_spaces=True` and `indent_size=2`') def test_config_failure_use_spaces(self): section = Section('name') section.append(Setting('use_spaces', False)) bear = DartLintBear(section, Queue()) with self.assertRaisesRegex(AssertionError, self.DART_VALUE_ERROR_RE):
from coalib.testing.LocalBearTestHelper import verify_local_bear test_file = """ int main() { return 0; } """ test_file2 = ('int main() {\n' + ' int x;\n' + ' x = 3;' * 100 + '\n' ' return 0;\n' + '}\n') CPPLintBearTest = verify_local_bear(CPPLintBear, valid_files=(), invalid_files=(test_file,), tempfile_kwargs={'suffix': '.cpp'}) CPPLintBearIgnoreConfigTest = verify_local_bear( CPPLintBear, valid_files=(test_file,), invalid_files=(), settings={'cpplint_ignore': 'legal/copyright'}, tempfile_kwargs={'suffix': '.cpp'}) CPPLintBearLineLengthConfigTest = verify_local_bear( CPPLintBear, valid_files=(), invalid_files=(test_file,), settings={'cpplint_ignore': 'legal/copyright', 'max_line_length': '13'},
from bears.c_languages.ClangBear import ClangBear from coalib.testing.LocalBearTestHelper import verify_local_bear ClangBearTest = verify_local_bear( ClangBear, ('int main() {}', ), ('bad things, this is no C code', # Has no fixit # Has a fixit and no range 'struct { int f0; } x = { f0 :1 };', 'int main() {int *b; return b}'), # Has a fixit and a range 'test.c') ClangBearIgnoreTest = verify_local_bear( ClangBear, # Should ignore the warning, valid! ('struct { int f0; } x = { f0 :1 };',), (), 'test.c', settings={'clang_cli_options': '-w'})
from bears.configfiles.DockerfileLintBear import DockerfileLintBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = """ FROM ubuntu:14.04 MAINTAINER coala LABEL Name coala-docker LABEL Version 0.1 # Install basic tools RUN apt-get -y -qq update RUN apt-get -y -qq upgrade EXPOSE 5432 CMD ["/bin/bash", "coala"] """ bad_file = """ FROM ubuntu:14.04 # Install basic tools apt-get -y -qq update apt-get -y -qq upgrade """ DockerfileLintBearTest = verify_local_bear(DockerfileLintBear, valid_files=(good_file,), invalid_files=(bad_file,))
from bears.shell.ShellCheckBear import ShellCheckBear from coalib.testing.LocalBearTestHelper import verify_local_bear valid_file = """ #!/usr/bin/env sh echo "Path is $PATH" echo "$P" """ invalid_file = """ #!/usr/bin/env sh echo 'Path is $PATH' echo $P X = 24 X+=2 # += operator is supported by bash and not by sh echo $X """ ShellCheckBearTest = verify_local_bear(ShellCheckBear, valid_files=(valid_file, ), invalid_files=(invalid_file, ))
use strict; use warnings; use vars qw/ $VERSION /; $VERSION = '1.00'; exit 1 if !print "Hello, world!\n"; """ bad_file = """ #!/usr/bin/perl print "Hello World\n"; """ conf_file = os.path.abspath(os.path.join( os.path.dirname(os.path.realpath(__file__)), 'testfiles', '.perlcriticrc')) PerlCriticBearTest = verify_local_bear(PerlCriticBear, valid_files=(good_file,), invalid_files=(bad_file,)) PerlCriticBearConfigTest = verify_local_bear( PerlCriticBear, valid_files=(good_file, bad_file), invalid_files=(), settings={'perlcritic_profile': conf_file})
print("hello world") ''' bad_file = ''' """ example module level docstring """ def hello(): print("hello world") ''' PyDocStyleBearTest = verify_local_bear(PyDocStyleBear, valid_files=(good_file, ), invalid_files=(bad_file, ), tempfile_kwargs={'suffix': '.py'}) PyDocStyleBearIgnoreAllTest = verify_local_bear( PyDocStyleBear, valid_files=( good_file, bad_file, ), invalid_files=(), settings={'pydocstyle_ignore': 'D400, D200, D103, D212'}, tempfile_kwargs={'suffix': '.py'}) # Checks if an invalid file yields results when only some errors are ignored. PyDocStyleBearIgnoreSomeTest = verify_local_bear( PyDocStyleBear,
from bears.go.GofmtBear import GofmtBear from coalib.testing.LocalBearTestHelper import verify_local_bear GofmtBear = verify_local_bear( GofmtBear, ('package main\n\nfunc main() {\n\treturn 1\n}',), ('package main\nfunc main() {\n\treturn 1\n}',))
confidence=90) ]) # The following test will ignore some error codes, so "good" and "bad" doesn't # reflect the actual code quality. good_files = ('good_file.py', 'assert.py') bad_files = ('exec-py2.py', 'httpoxy_cgihandler.py', 'jinja2_templating.py', 'skip.py') skipped_error_codes = ['B105', 'B106', 'B107', 'B404', 'B606', 'B607', 'B101'] BanditBearSkipErrorCodesTest1 = verify_local_bear( BanditBear, valid_files=tuple(load_testfile(file) for file in good_files), invalid_files=tuple(load_testfile(file) for file in bad_files), settings={'bandit_skipped_tests': ','.join(skipped_error_codes)}, tempfile_kwargs={'suffix': '.py'}) good_files = ('good_file.py', ) bad_files = ('exec-py2.py', 'httpoxy_cgihandler.py', 'jinja2_templating.py', 'skip.py', 'assert.py') BanditBearSkipErrorCodesTest2 = verify_local_bear( BanditBear, valid_files=tuple(load_testfile(file) for file in good_files), invalid_files=tuple(load_testfile(file) for file in bad_files), settings={'bandit_skipped_tests': ''}, tempfile_kwargs={'suffix': '.py'})
class theGangster wasItAGoodDay : () -> yes """ invalid_file = """ # Coffeelint is buggy here and will generate an error with invalid CSV on this var test """ CoffeeLintBearTest = verify_local_bear(CoffeeLintBear, valid_files=(good_file,), invalid_files=(warning_file, error_file, invalid_file)) CoffeeLintBearUseEnglishOperatorTest = verify_local_bear( CoffeeLintBear, valid_files=(good_file_use_english_operator,), invalid_files=(bad_file_use_english_operator,), settings={'allow_bitwise_operators': 'false', 'consistent_line_endings_style': 'unix'}) CoffeeLintBearTabWidthTest = verify_local_bear( CoffeeLintBear, valid_files=(good_file_tab_width,),
from bears.css.CSSAutoPrefixBear import CSSAutoPrefixBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = """ .example { display: -webkit-box; display: -ms-flexbox; display: flex; } """ bad_file = """ .example { display: flex; } """ CSSAutoPrefixBear = verify_local_bear(CSSAutoPrefixBear, valid_files=(good_file, ), invalid_files=(bad_file, ))
from bears.natural_language.LanguageToolBear import LanguageToolBear from coalib.testing.BearTestHelper import generate_skip_decorator from coalib.testing.LocalBearTestHelper import verify_local_bear try: import language_check import guess_language language_check guess_language except ImportError as err: raise SkipTest(str(err)) LanguageToolBearTest = verify_local_bear( LanguageToolBear, valid_files=('A correct English sentence sounds nice to everyone.', 'Ein korrekter englischer Satz klingt für alle gut.'), invalid_files=(' ', 'asdgaasdfgahsadf', '"quoted"')) LanguageToolBearLanguageTest = verify_local_bear( LanguageToolBear, valid_files=('A correct English sentence sounds nice to everyone.',), invalid_files=('Ein korrekter englischer Satz klingt für alle gut.',), settings={'language': 'en-US'}) LanguageToolBearDisableRulesTest = verify_local_bear( LanguageToolBear, valid_files=('Line without unnecessary spaces at the start.',
import os from bears.cmake.CMakeLintBear import CMakeLintBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = 'project(FooBar C)\nset(VERSION 0)\n' bad_file_mixes_case = 'ProJeCt(FooBar C)\nseT(VERSION 0)\n' conf_file = os.path.join(os.path.dirname(__file__), 'test_files', 'cmake_config.txt') CMakeLintBearTest = verify_local_bear( CMakeLintBear, valid_files=(good_file,), invalid_files=(bad_file_mixes_case,), tempfile_kwargs={'suffix': '.cmake'}) CMakeLintBearConfigTest = verify_local_bear( CMakeLintBear, valid_files=(good_file, bad_file_mixes_case), invalid_files=(), tempfile_kwargs={'suffix': '.cmake'}, settings={'cmakelint_config': conf_file})
} ''' good_file2 = ''' $value: 5px; .foo { padding: $value; } .bar { margin: $value; } .new-class { display: block; } ''' SCSSLintBearTest = verify_local_bear(SCSSLintBear, valid_files=(good_file, good_file2), invalid_files=(bad_file, bad_file2)) SCSSLintBearChainedClassesTest = verify_local_bear( SCSSLintBear, valid_files=(bad_file2, good_file2), invalid_files=(bad_file,), settings={'allow_chained_classes': True})
bad_file = """class lowerCamelCase { var x: Int } """ long_class_file = """class LongClass { var x: Int var y: Int var z: Int } """ TailorBearWithoutConfig = verify_local_bear(TailorBear, valid_files=(good_file,), invalid_files=(bad_file,), tempfile_kwargs={ 'suffix': '.swift'}) TailorBearWithConfig = verify_local_bear(TailorBear, valid_files=(bad_file,), invalid_files=(), settings={ 'tailor_config': tailorconfig}, tempfile_kwargs={'suffix': '.swift'}) TailorBearWithSetting = verify_local_bear(TailorBear, valid_files=(), invalid_files=(long_class_file,), settings={ 'max_class_length': 2},
ignorepkg_file = """package main import ( "io" "log" "os" ) func main() { f, _ := os.Open("foo") log.Println("opened file") io.Copy(os.Stdout, f) }""" GoErrCheckBearTest = verify_local_bear(GoErrCheckBear, valid_files=( good_file, assert_file, blank_file), invalid_files=(bad_file,), tempfile_kwargs={'suffix': '.go'}) GoErrCheckBearWithIgnoreTest = verify_local_bear(GoErrCheckBear, valid_files=( good_file, assert_file, blank_file), invalid_files=(bad_file,), settings={ 'ignore': "'[rR]ead|[wW]rite'"}, tempfile_kwargs={'suffix': '.go'}) GoErrCheckBearWithIgnorePkgTest = verify_local_bear(GoErrCheckBear,
""" def get_testfile_path(filename): return os.path.join(os.path.dirname(__file__), 'dockerfile_lint_test_files', filename) default_rule = get_testfile_path('default_rule.yaml') sample_rule = get_testfile_path('sample_rule.yaml') DockerfileLintBearTest = verify_local_bear(DockerfileLintBear, valid_files=(good_file,), invalid_files=(bad_file,)) DockerfileLintBearDefaultRuleTest = verify_local_bear( DockerfileLintBear, valid_files=(good_file2,), invalid_files=(bad_file2,), settings={'dockerfile_lint_rule_file': default_rule}) DockerfileLintBearCustomRuleTest = verify_local_bear( DockerfileLintBear, valid_files=(good_file3,), invalid_files=(bad_file3,), settings={'dockerfile_lint_rule_file': sample_rule})
from bears.julia.JuliaLintBear import JuliaLintBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = """ a = 2 println(2) """ bad_file = """ println(hello) """ JuliaLintBearTest = verify_local_bear(JuliaLintBear, valid_files=(good_file,), invalid_files=(bad_file,), tempfile_kwargs={'suffix': '.jl'}, timeout=45)
from bears.markdown.MarkdownBear import MarkdownBear from coalib.testing.LocalBearTestHelper import verify_local_bear test_file1 = """1. abc 1. def """ test_file2 = """1. abc 2. def """ test_file3 = """1. abcdefghijklm 2. nopqrstuvwxyz """ MarkdownBearTest = verify_local_bear(MarkdownBear, valid_files=(test_file2, ), invalid_files=(test_file1, )) MarkdownBearConfigsTest = verify_local_bear(MarkdownBear, valid_files=(test_file1, ), invalid_files=(test_file2, ), settings={'list_increment': False}) MarkdownBearMaxLineLengthSettingTest = verify_local_bear( MarkdownBear, valid_files=(test_file2, ), invalid_files=(test_file3, ), settings={'max_line_length': 10})
filename='default') def test_exception_empty_file(self): self.check_results( self.uut, [], [Result.from_values('JSONFormatBear', 'This file is empty.', file='default')], filename='default') JSONFormatBearTest = verify_local_bear(JSONFormatBear, valid_files=(test_file1, test_file2), invalid_files=(test_file3, unicode_file, '', 'random stuff', '{"a":5,"b":5}')) JSONFormatBearSortTest = verify_local_bear(JSONFormatBear, valid_files=(test_file1,), invalid_files=(test_file2,), settings={'json_sort': 'true'}) JSONFormatBearTabWidthTest = verify_local_bear(JSONFormatBear, valid_files=(test_file3,), invalid_files=(test_file2,), settings={
from bears.rest.RSTcheckBear import RSTcheckBear from coalib.testing.LocalBearTestHelper import verify_local_bear rst_syntax_good = '====\ntest\n====\n' rst_syntax_bad = '====\ntest\n===\n' python_block_good = '====\nTest\n====\n.. code-block:: python\n\n print()' python_block_bad = '====\nTest\n====\n.. code-block:: python\n\n print(\n' RSTcheckBearTest_ignore_no_code_block = verify_local_bear( RSTcheckBear, (rst_syntax_good, python_block_good), (rst_syntax_bad, python_block_bad), ) RSTcheckBearTest_ignore_python_code_block = verify_local_bear( RSTcheckBear, (rst_syntax_good, python_block_bad, python_block_good), (rst_syntax_bad,), settings={'code_block_language_ignore': 'python'})
import unittest from unittest.mock import patch from bears.natural_language.AlexBear import AlexBear from coalib.testing.BearTestHelper import generate_skip_decorator from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = 'Their network looks good.' bad_file = 'His network looks good.' AlexBearTest = verify_local_bear(AlexBear, valid_files=(good_file,), invalid_files=(bad_file,)) @generate_skip_decorator(AlexBear) @patch('bears.natural_language.AlexBear.subprocess.check_output') class AlexBearPrereqTest(unittest.TestCase): def test_unverified_alex_installed(self, check_output_mock): check_output_mock.side_effect = OSError self.assertIn('The `alex` package could not be verified', AlexBear.check_prerequisites()) def test_wrong_alex_installed(self, check_output_mock): check_output_mock.return_value = b'Unexpected output from package' self.assertIn("The `alex` package that's been installed seems to " 'be incorrect', AlexBear.check_prerequisites())
if(TRUE){ x=1 # inline comments }else{ x=2;print("Oh no... ask the right bracket to go away!")} """ bad_file_3 = """x=(1+1+1+1+1+1+1+1+1) if(TRUE){ x=1 # inline comments }else{x=2;print("Oh no... ask the right bracket to go away!")} """ FormatRBearTest = verify_local_bear(FormatRBear, valid_files=(good_file_1, ), invalid_files=(bad_file_1, )) FormatRBearRArrowToEqualTest = verify_local_bear( FormatRBear, valid_files=(good_file_2, ), invalid_files=(bad_file_1, ), settings={'r_use_arrows': 'true'}) FormatRBearRKeepCommentsTest = verify_local_bear( FormatRBear, valid_files=(good_file_3, ), invalid_files=(good_file_1, ), settings={'r_keep_comments': 'false'}) FormatRBearRBraceToNewlineTest = verify_local_bear(
from bears.r.RLintBear import RLintBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = """ fun <- function(one){ one_plus_one <- one + 1 four <- matrix(1:10, nrow = 2) print(one_plus_one, four) }""" bad_file = """ fun = function(one) { one.plus.one <- one + 1 four <- matrix(1:10,nrow =2) print(one_plus_one , four) } """ RLintBearTest = verify_local_bear(RLintBear, invalid_files=(bad_file,), valid_files=(good_file,), tempfile_kwargs={'suffix': '.R'})
int test() { String s = null; return s.length(); } } """ class JavaPMDBearPrerequisiteTest(TestCase): def test_check_prerequisites(self): with mock.patch('bears.java.JavaPMDBear.which') as mock_which: mock_which.side_effect = [None, None, None] self.assertEqual(JavaPMDBear.check_prerequisites(), 'bash is not installed.') mock_which.side_effect = ['path/to/bash', None, None] self.assertEqual(JavaPMDBear.check_prerequisites(), ('PMD is missing. Make sure to install it from ' '<https://pmd.github.io/>')) mock_which.side_effect = [ 'path/to/bash', 'path/to/pmd', 'path/to/run' ] self.assertEqual(JavaPMDBear.check_prerequisites(), True) JavaPMDBearTest = verify_local_bear(JavaPMDBear, valid_files=(good_file, ), invalid_files=(bad_file, ), tempfile_kwargs={'suffix': '.java'})
test_file1 = """ def simple(): pass """ test_file2 = """ class class1(): pass """ test_file3 = 'def f():\n' + (' assert True\n' * 50) RadonBearDefaultsTest = verify_local_bear( RadonBear, valid_files=(test_file1, test_file2), invalid_files=(test_file3,)) RadonBearNoReportsTest = verify_local_bear( RadonBear, valid_files=(test_file1, test_file2, test_file3), invalid_files=(), settings={'radon_ranks_info': '', 'radon_ranks_normal': '', 'radon_ranks_major': ''}) RadonBearReportsTest = verify_local_bear( RadonBear, valid_files=(),
ignorepkg_file = """package main import ( "io" "log" "os" ) func main() { f, _ := os.Open("foo") log.Println("opened file") io.Copy(os.Stdout, f) }""" GoErrCheckBearTest = verify_local_bear(GoErrCheckBear, valid_files=(good_file, assert_file, blank_file), invalid_files=(bad_file, ), tempfile_kwargs={'suffix': '.go'}) GoErrCheckBearWithIgnoreTest = verify_local_bear( GoErrCheckBear, valid_files=(good_file, assert_file, blank_file), invalid_files=(bad_file, ), settings={'ignore': "'[rR]ead|[wW]rite'"}, tempfile_kwargs={'suffix': '.go'}) GoErrCheckBearWithIgnorePkgTest = verify_local_bear( GoErrCheckBear, valid_files=(good_file, assert_file, blank_file), invalid_files=(ignorepkg_file, ), settings={'ignorepkg': "'io'"}, tempfile_kwargs={'suffix': '.go'})
bad_file = """ printNumber(num aNumber) { print('The number is $aNumber.') } main() { var answer = 42; // The meaning of life. printNumber(answer) } """ DartLintBearTest = verify_local_bear(DartLintBear, valid_files=(good_file,), invalid_files=(bad_file,), tempfile_kwargs={'suffix': '.dart'}) @generate_skip_decorator(DartLintBear) class DartLintBearConfigTest(LocalBearTestHelper): DART_VALUE_ERROR_RE = ('ValueError: DartLintBear only supports ' '`use_spaces=True` and `indent_size=2`') def test_config_failure_use_spaces(self): section = Section('name') section.append(Setting('use_spaces', False)) bear = DartLintBear(section, Queue()) with self.assertRaisesRegex(AssertionError, self.DART_VALUE_ERROR_RE):
wasItAGoodDay : () -> yes """ invalid_file = """ # Coffeelint is buggy here and will generate an error with invalid CSV on this var test """ infinite_line_length_file = """# File to check long line length support """ + 'number = 42; ' * 1000 + """number = 42 console.log number """ CoffeeLintBearTest = verify_local_bear(CoffeeLintBear, valid_files=(good_file, ), invalid_files=(warning_file, error_file, invalid_file)) CoffeeLintBearUseEnglishOperatorTest = verify_local_bear( CoffeeLintBear, valid_files=(good_file_use_english_operator, ), invalid_files=(bad_file_use_english_operator, ), settings={ 'allow_bitwise_operators': 'false', 'consistent_line_endings_style': 'unix' }) CoffeeLintBearTabWidthTest = verify_local_bear( CoffeeLintBear, valid_files=(good_file_tab_width, ), invalid_files=(good_file, ),
# actually parsing a complete C file. ClangRange = namedtuple('ClangRange', 'start end') ClangPosition = namedtuple('ClangPosition', 'file line column') ClangFile = namedtuple('ClangFile', 'name') file = ClangFile('t.c') start = ClangPosition(file, 1, 2) end = ClangPosition(file, 3, 4) uut = sourcerange_from_clang_range(ClangRange(start, end)) compare = SourceRange.from_values('t.c', 1, 2, 3, 4) self.assertEqual(uut, compare) ClangBearTest = verify_local_bear( ClangBear, ('int main() {}', ), ('bad things, this is no C code', # Has no fixit # Has a fixit and no range 'struct { int f0; } x = { f0 :1 };', 'int main() {int *b; return b}'), # Has a fixit and a range 'test.c') ClangBearIgnoreTest = verify_local_bear( ClangBear, # Should ignore the warning, valid! ('struct { int f0; } x = { f0 :1 };',), (), 'test.c', settings={'clang_cli_options': '-w'})
test_file10 = """ int main() { return 0; }""" test_file11 = ('int\nmain ()\n' + '{\n' + ' ' * 1000 + 'return 0;\n' + '}') GNUIndentBearTest = verify_local_bear( GNUIndentBear, valid_files=(test_file1,), invalid_files=(test_file2, test_file3, test_file4), settings={'use_spaces': 'true', 'max_line_length': '79'}) GNUIndentBearWithTabTest = verify_local_bear( GNUIndentBear, valid_files=(test_file3,), invalid_files=(test_file1, test_file2, test_file4), settings={'use_spaces': 'nope', 'max_line_length': '79'}) GNUIndentBearWidthTest = verify_local_bear( GNUIndentBear, valid_files=(test_file2,), invalid_files=(test_file1, test_file3, test_file4),
from bears.js.HappinessLintBear import HappinessLintBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = """ var x = 2; if (6 > 7 !== true) console.log('done'); console.log(x); """ bad_file = """ if (options.quiet !== true) console.log('done') var x=2 """ HappinessLintBear = verify_local_bear(HappinessLintBear, valid_files=(good_file,), invalid_files=(bad_file,))
line=2, column=5) ], filename='default') def test_exception_empty_file(self): self.check_results(self.uut, [], [ Result.from_values( 'JSONFormatBear', 'This file is empty.', file='default') ], filename='default') JSONFormatBearTest = verify_local_bear(JSONFormatBear, valid_files=(test_file1, test_file2), invalid_files=(test_file3, unicode_file, '', 'random stuff', '{"a":5,"b":5}')) JSONFormatBearSortTest = verify_local_bear(JSONFormatBear, valid_files=(test_file1, ), invalid_files=(test_file2, ), settings={'json_sort': 'true'}) JSONFormatBearTabWidthTest = verify_local_bear(JSONFormatBear, valid_files=(test_file3, ), invalid_files=(test_file2, ), settings={'indent_size': '3'}) JSONFormatBearUnicodeTest = verify_local_bear( JSONFormatBear,
'jshintconfig.json') settings = { 'max_statements': 'False', 'max_parameters': 10, 'allow_unused_variables': 'True', 'shadow': 'False', 'allow_last_semicolon': 'True', 'es_version': 3, 'allow_latedef': 'no_func', 'javascript_strictness': 'False'} JSHintBearTest = verify_local_bear(JSHintBear, valid_files=(), invalid_files=(test_file1, test_file2, test_file3)) JSHintBearConfigFileTest = verify_local_bear( JSHintBear, valid_files=(test_file1,), invalid_files=(test_file2,), settings={'jshint_config': jshintconfig}) JSHintBearCoafileTest = verify_local_bear( JSHintBear, invalid_files=(), valid_files=(test_file3, ), settings=settings)
test_file = """ test too er e """ invalid_general_file = 'C' * (79 + 1) invalid_VB_file = 'C' * (65535 + 1) LineLengthBearTest = verify_local_bear(LineLengthBear, valid_files=(test_file,), invalid_files=('testa', 'test line'), settings={'max_line_length': '4'}) LineLengthBearIgnoreRegexTest = verify_local_bear( LineLengthBear, valid_files=(test_file, 'http://a.domain.de', 'ftp://a.domain.de', 'hi there ftp://!'), invalid_files=('http not a link',), settings={ 'max_line_length': '4', 'ignore_length_regex': 'http://, https://, ftp://'})
'False. Consider using autoescape=True to ' 'mitigate XSS vulnerabilities.', get_testfile_path('jinja2_templating.py'), 15, end_line=16, severity=RESULT_SEVERITY.MAJOR, confidence=90)]) # The following test will ignore some error codes, so "good" and "bad" doesn't # reflect the actual code quality. good_files = ('good_file.py', 'assert.py') bad_files = ('exec-py2.py', 'httpoxy_cgihandler.py', 'jinja2_templating.py', 'skip.py') skipped_error_codes = ['B105', 'B106', 'B107', 'B404', 'B606', 'B607', 'B101'] BanditBearSkipErrorCodesTest1 = verify_local_bear( BanditBear, valid_files=tuple(load_testfile(file) for file in good_files), invalid_files=tuple(load_testfile(file) for file in bad_files), settings={'bandit_skipped_tests': ','.join(skipped_error_codes)}, tempfile_kwargs={'suffix': '.py'}) good_files = ('good_file.py',) bad_files = ('exec-py2.py', 'httpoxy_cgihandler.py', 'jinja2_templating.py', 'skip.py', 'assert.py') BanditBearSkipErrorCodesTest2 = verify_local_bear( BanditBear, valid_files=tuple(load_testfile(file) for file in good_files), invalid_files=tuple(load_testfile(file) for file in bad_files), settings={'bandit_skipped_tests': ''}, tempfile_kwargs={'suffix': '.py'})
from tests.test_bears.TestBearDep import (TestDepBearBDependsA, TestDepBearCDependsB, TestDepBearDependsAAndAA) from coalib.bearlib.abstractions.Linter import linter from tests.test_bears.LineCountTestBear import LineCountTestBear from coala_utils.ContextManagers import prepare_file from coalib.results.Result import Result from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY from coalib.settings.Section import Section from coalib.settings.Setting import Setting from coalib.testing.LocalBearTestHelper import verify_local_bear, execute_bear from coalib.testing.LocalBearTestHelper import LocalBearTestHelper as Helper files = ('Everything is invalid/valid/raises error', ) invalidTest = verify_local_bear(TestBear, valid_files=(), invalid_files=files, settings={'result': True}) validTest = verify_local_bear(TestBear, valid_files=files, invalid_files=()) class LocalBearCheckResultsTest(Helper): def setUp(self): section = Section('') section.append(Setting('result', 'a, b')) self.uut = TestBear(section, Queue()) def test_order_ignored(self): self.check_results(self.uut, ['a', 'b'], ['b', 'a'], check_order=False) def test_require_order(self): with self.assertRaises(AssertionError):
from bears.matlab.MatlabIndentationBear import MatlabIndentationBear from coalib.testing.LocalBearTestHelper import verify_local_bear MatlabIndentationBearTest = verify_local_bear( MatlabIndentationBear, valid_files=("if a ~= b\n a\nendif\n", "if a ~= b\n a\nendif\n", "if a ~= b\n a\n \nelse\n a\nendif\n"), invalid_files=( " A", "if a ~= b\na\nendif\n", "if a ~= b\n a\nendif\n", "if a ~= b\n a\nendif\n", "if a ~= b\n a\n else\n a\nendif\n", ), )
bad_max_line_length = """--- receipt: Oz-Ware This line-length is beyond 50 chars ...""" config_file = """ extends: default rules: colons: max-spaces-after: -1 indentation: disable empty-lines: disable """ YAMLLintBear1Test = verify_local_bear(YAMLLintBear, valid_files=(), invalid_files=(test_file, )) with prepare_file(config_file, filename=None, force_linebreaks=True, create_tempfile=True) as (conf_lines, conf_file): YAMLLintBear2Test = verify_local_bear( YAMLLintBear, valid_files=(test_file, ), invalid_files=(), settings={'yamllint_config': conf_file}) YAMLLintBear3Test = verify_local_bear(YAMLLintBear, valid_files=( no_start_yaml_file,
"name": "stdout", "output_type": "stream", "text": [ "1\n" ] } ], "source": [ "print(x) # <-- here everything is fine\n" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 0 } """ PEP8NotebookBearTest = \ verify_local_bear(PEP8NotebookBear, valid_files=(good_file,), invalid_files=(bad_file,) ) PEP8NotebookBearWithoutTrailingNewlineTest = \ verify_local_bear(PEP8NotebookBear, valid_files=(good_file[:-1],), invalid_files=(bad_file[:-1],), force_linebreaks=False, )
import unittest from queue import Queue from coalib.settings.Section import Section from bears.jinja2.Jinja2Bear import Jinja2Bear from coalib.testing.LocalBearTestHelper import verify_local_bear, execute_bear Jinja2BearVariableSpacingTest = verify_local_bear( Jinja2Bear, valid_files=(r'foo {{ var }}', r'foo {{ var1|filter }} bar {{ var2 }}'), invalid_files=(r'foo {{var }}', r'foo {{ var}} bar', r'{{ var }}', r'{{ good_var }} foo {{bad_var }}')) Jinja2BearCustomVariableSpacingTest = verify_local_bear( Jinja2Bear, valid_files=(r'foo {{var}}', r'foo {{var1|filter}} bar {{var2}}'), invalid_files=(r'foo {{ var }}', r'foo {{ var}} bar', r'{{ var }}'), settings={'variable_spacing': '0'}) class Jinja2BearSpacingDiffTest(unittest.TestCase): def setUp(self): self.uut = Jinja2Bear(Section(''), Queue()) def test_variable_spacing(self): content = (r'foo {{var }} bar', ) with execute_bear(self.uut, 'F', content) as result: self.assertEqual( result[0].diffs['F'].unified_diff, '--- \n' '+++ \n' '@@ -1 +1 @@\n' '-foo {{var }} bar\n'
import unittest from queue import Queue from coalib.settings.Section import Section from bears.jinja2.Jinja2Bear import Jinja2Bear from coalib.testing.LocalBearTestHelper import verify_local_bear, execute_bear Jinja2BearVariableSpacingTest = verify_local_bear( Jinja2Bear, valid_files=(r'foo {{ var }}', r'foo {{ var1|filter }} bar {{ var2 }}'), invalid_files=(r'foo {{var }}', r'foo {{ var}} bar', r'{{ var }}', r'{{ good_var }} foo {{bad_var }}')) Jinja2BearCustomVariableSpacingTest = verify_local_bear( Jinja2Bear, valid_files=(r'foo {{var}}', r'foo {{var1|filter}} bar {{var2}}'), invalid_files=(r'foo {{ var }}', r'foo {{ var}} bar', r'{{ var }}'), settings={'variable_spacing': '0'}) class Jinja2BearSpacingDiffTest(unittest.TestCase): def setUp(self): self.uut = Jinja2Bear(Section(''), Queue())
</head> <body> <button>No type set</button> <div> <div class="panel-body"> <p>Something</p> </div> </div> <div id="qunit"></div> <ol id="bootlint"> <li data-lint="Found one or more `<button>`s missing a `type` attribute."></li> </ol> </body> </html> """ # There's a missing type in <button> tag, missing DOCTYPE # and panel has no body. BootLintBearTest = verify_local_bear(BootLintBear, valid_files=(good_file,), invalid_files=(bad_file,)) BootLintBearDisableTest = verify_local_bear( BootLintBear, valid_files=(good_file, bad_file), invalid_files=(), settings={'bootlint_ignore': 'W001,W007,E001,E023'})
from bears.ruby.RuboCopBear import RuboCopBear from coalib.testing.LocalBearTestHelper import verify_local_bear good_file = """def good_name test if something end """ bad_file = """def badName test if something end """ RuboCopBearTest = verify_local_bear(RuboCopBear, invalid_files=(bad_file,), valid_files=(good_file,)) # Testing Config rubocop_config = os.path.join(os.path.dirname(__file__), 'test_files', 'rubocop_config.yaml') # bad file becomes good and vice-versa RuboCopBearConfigFileTest = verify_local_bear( RuboCopBear, valid_files=(bad_file,), invalid_files=(good_file,), settings={'rubocop_config': rubocop_config})
dtd_file_path = get_testfile_path('note.dtd') schema_file_path = get_testfile_path('note.xsd') relaxng_file_path = get_testfile_path('note.rng') valid_xml_path = load_testdata('note.xml') valid_xml_url = load_testdata('concept-valid.xml') invalid_xml_schema = load_testdata('xsd-error.xml') invalid_xml_dtd = load_testdata('dtd-error.xml') invalid_xml_relaxng = load_testdata('rng-error.xml') invalid_xml_url = load_testdata('concept-invalid.xml') dtd_url = 'http://docs.oasis-open.org/dita/v1.0.1/dtd/concept.dtd' XMLBearCorrectedTest = verify_local_bear(XMLBear, valid_files=(valid_xml_file, valid_xml_chars), invalid_files=(invalid_xml_file, invalid_xml_chars), tempfile_kwargs={'suffix': '.xml'}) XMLBearSchemaTest = verify_local_bear( XMLBear, valid_files=(valid_xml_path, ), invalid_files=(invalid_xml_schema, ), settings={'xml_schema': escape(schema_file_path, '\\')}, tempfile_kwargs={'suffix': '.xml'}) XMLBearDTDPathTest = verify_local_bear( XMLBear, valid_files=(valid_xml_path, ), invalid_files=(invalid_xml_dtd, ), settings={'xml_dtd': escape(dtd_file_path, '\\')},