desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns an unsigned short in packed big-endian (network) form'
| @staticmethod
def packed_ushort_big_endian(num):
| return pack('>H', num)
|
'Returns an unsigned short from a packed big-endian (network) byte
array'
| @staticmethod
def unpacked_ushort_big_endian(bytes):
| return unpack('>H', bytes)[0]
|
'Returns an unsigned int in packed big-endian (network) form'
| @staticmethod
def packed_uint_big_endian(num):
| return pack('>I', num)
|
'Returns an unsigned int from a packed big-endian (network) byte array'
| @staticmethod
def unpacked_uint_big_endian(bytes):
| return unpack('>I', bytes)[0]
|
'Returns an unsigned char from a packed big-endian (network) byte array'
| @staticmethod
def unpacked_char_big_endian(bytes):
| return unpack('c', bytes)[0]
|
'Returns the payload as a regular Python dictionary'
| def dict(self):
| d = {}
if self.alert:
if isinstance(self.alert, PayloadAlert):
d['alert'] = self.alert.dict()
else:
d['alert'] = self.alert
if self.sound:
d['sound'] = self.sound
if (self.badge is not None):
d['badge'] = int(self.badge)
if self.category:
... |
'Add a notification message to the frame'
| def add_item(self, token_hex, payload, identifier, expiry, priority):
| item_len = 0
self.frame_data.extend(('\x02' + APNs.packed_uint_big_endian(item_len)))
token_bin = a2b_hex(token_hex)
token_length_bin = APNs.packed_ushort_big_endian(len(token_bin))
token_item = (('\x01' + token_length_bin) + token_bin)
self.frame_data.extend(token_item)
item_len += len(toke... |
'Get the frame buffer'
| def __str__(self):
| return str(self.frame_data)
|
'A generator that yields (token_hex, fail_time) pairs retrieved from
the APNs feedback server'
| def items(self):
| buff = ''
for chunk in self._chunks():
buff += chunk
if (not buff):
break
if (len(buff) < 6):
break
while (len(buff) > 6):
token_length = APNs.unpacked_ushort_big_endian(buff[4:6])
bytes_to_read = (6 + token_length)
if (... |
'Takes a token as a hex string and a payload as a Python dict and sends
the notification'
| def _get_notification(self, token_hex, payload):
| token_bin = a2b_hex(token_hex)
token_length_bin = APNs.packed_ushort_big_endian(len(token_bin))
payload_json = payload.json()
payload_length_bin = APNs.packed_ushort_big_endian(len(payload_json))
zero_byte = '\x00'
if (sys.version_info[0] != 2):
zero_byte = bytes(zero_byte, 'utf-8')
... |
'form notification data in an enhanced format'
| def _get_enhanced_notification(self, token_hex, payload, identifier, expiry):
| token = a2b_hex(token_hex)
payload = payload.json()
fmt = (ENHANCED_NOTIFICATION_FORMAT % len(payload))
notification = pack(fmt, ENHANCED_NOTIFICATION_COMMAND, identifier, expiry, TOKEN_LENGTH, token, len(payload), payload)
return notification
|
'in enhanced mode, send_notification may return error response from APNs if any'
| def send_notification(self, token_hex, payload, identifier=0, expiry=0):
| if self.enhanced:
self._last_activity_time = time.time()
message = self._get_enhanced_notification(token_hex, payload, identifier, expiry)
for i in range(WRITE_RETRY):
try:
with self._send_lock:
self._make_sure_error_response_handler_worker_ali... |
':param session: å建å
šå±çsession对象ïŒä¿è¯äŒè¯çäžèŽæ§ïŒæææ§ã
:param headers: 鲿¢æå¡åšç«¯åç¬è«ïŒæ·»å 䌪è£
倎éšä¿¡æ¯'
| def __init__(self, headers):
| self.session = requests.Session()
self.headers = headers
|
':param account: çšæ·å
:param passwd: å¯ç
:return:'
| def login(self, account, passwd):
| self.username = account
self.password = passwd
(lt, execution) = self.get_webflow()
postdata = {'username': account, 'password': passwd, 'lt': lt, 'execution': execution, '_eventId': 'submit'}
loginurl = 'https://passport.csdn.net/account/login'
response = self.session.post(url=loginurl, headers... |
'æµæ°Žå·webflowè·åãé䟿访é®å
å«ç»éé¡µéŸæ¥çCSDNçœé¡µå°±å¯ä»¥åŸå°è¿äž²æ°æ®ãåºäžºæ¯åšæååç
:return:'
| def get_webflow(self):
| url = 'https://passport.csdn.net/account/login?ref=toolbar'
response = self.session.get(url=url, headers=self.headers)
soup = BeautifulSoup(response.text, 'html.parser')
lt = soup.find('input', {'name': 'lt'})['value']
execution = soup.find('input', {'name': 'execution'})['value']
soup.clear()
... |
'æç»å®çæç« è·¯åŸ http://blog.csdn.net/marksinoberg/article/details/69569353
å
蜬åäžäžäžºïŒ http://blog.csdn.net/marksinoberg/article/digg?ArticleId=69569353
:param articleurl åŸ
æäœçæç« è·¯åŸ
:param digg: ç»æç« ç¹èµè¿æ¯èž©äžäž
:return:'
| def digg(self, articleurl, digg=True):
| try:
(bloguser, blogid) = (articleurl.split('/')[3], articleurl.split('/')[(-1)])
if (digg == True):
diggurl = 'http://blog.csdn.net/{}/article/digg?ArticleId={}'.format(bloguser, blogid)
else:
diggurl = 'http://blog.csdn.net/{}/article/bury?ArticleId={}'.format(blogu... |
'ç»å®äžäžªæç« çè·¯åŸhttp://blog.csdn.net/marksinoberg/article/details/69569353ïŒ
éèŠèœ¬å䞺圢åŠïŒ http://blog.csdn.net/Marksinoberg/comment/submit?id=69569353
:param articleurl:
:param content:
:return:'
| def comment(self, articleurl, content):
| try:
(bloguser, blogid) = (articleurl.split('/')[3], articleurl.split('/')[(-1)])
commenturl = 'http://blog.csdn.net/{}/comment/submit?id={}'.format(bloguser, blogid)
except:
print (commenturl, ' \xe4\xb8\x8d\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe5\x90\x88\xe6\xb3\x95\xe7\x9a\x84\xe8\... |
''
| def get_info(self):
| try:
page = self.session.get(self.login_url, headers=self.headers)
soup = BeautifulSoup(page.text)
input_list = soup.select('.form input')
data = {}
data['uuid'] = input_list[0]['value']
data['eid'] = input_list[4]['value']
data['fp'] = input_list[5]['value... |
'The goal of this test is to validate that the plugin_info returned by
ModuleRegistry.get_plugin_info is a dictionary whose key \'shortName\' is
the same value as the string argument passed to
ModuleRegistry.get_plugin_info.'
| def test_get_plugin_info_dict(self):
| plugin_name = 'JankyPlugin1'
plugin_info = self.registry.get_plugin_info(plugin_name)
self.assertIsInstance(plugin_info, dict)
self.assertEqual(plugin_info['shortName'], plugin_name)
|
'The goal of this test is to validate that the plugin_info returned by
ModuleRegistry.get_plugin_info is a dictionary whose key \'longName\' is
the same value as the string argument passed to
ModuleRegistry.get_plugin_info.'
| def test_get_plugin_info_dict_using_longName(self):
| plugin_name = 'Blah Blah Blah Plugin'
plugin_info = self.registry.get_plugin_info(plugin_name)
self.assertIsInstance(plugin_info, dict)
self.assertEqual(plugin_info['longName'], plugin_name)
|
'The goal of this test case is to validate the behavior of
ModuleRegistry.get_plugin_info when the given plugin cannot be found in
ModuleRegistry\'s internal representation of the plugins_info.'
| def test_get_plugin_info_dict_no_plugin(self):
| plugin_name = 'PluginDoesNotExist'
plugin_info = self.registry.get_plugin_info(plugin_name)
self.assertIsInstance(plugin_info, dict)
self.assertEqual(plugin_info, {})
|
'The goal of this test case is to validate the behavior of
ModuleRegistry.get_plugin_info when the given plugin shortName returns
plugin_info dict that has no version string. In a sane world where
plugin frameworks like Jenkins\' are sane this should never happen, but
I am including this test and the corresponding defa... | def test_get_plugin_info_dict_no_version(self):
| plugin_name = 'HerpDerpPlugin'
plugin_info = self.registry.get_plugin_info(plugin_name)
self.assertIsInstance(plugin_info, dict)
self.assertEqual(plugin_info['shortName'], plugin_name)
self.assertEqual(plugin_info['version'], '0')
|
'The goal of this test case is to validate that valid tuple versions are
ordinally correct. That is, for each given scenario, v1.op(v2)==True
where \'op\' is the equality operator defined for the scenario.'
| def test_plugin_version_comparison(self):
| plugin_name = 'JankyPlugin1'
plugin_info = self.registry.get_plugin_info(plugin_name)
v1 = plugin_info.get('version')
op = getattr(pkg_resources.parse_version(v1), self.op)
test = op(pkg_resources.parse_version(self.v2))
self.assertTrue(test, msg='Unexpectedly found {0} {2} {1} ==... |
'Test that the cache is saved on normal object deletion'
| @mock.patch('jenkins_jobs.builder.JobCache.get_cache_dir', (lambda x: '/bad/file'))
def test_save_on_exit(self):
| with mock.patch('jenkins_jobs.builder.JobCache.save') as save_mock:
with mock.patch('os.path.isfile', return_value=False):
with mock.patch('jenkins_jobs.builder.JobCache._lock'):
jenkins_jobs.builder.JobCache('dummy')
save_mock.assert_called_with()
|
'Test providing a cachefile.'
| @mock.patch('jenkins_jobs.builder.JobCache.get_cache_dir', (lambda x: '/bad/file'))
def test_cache_file(self):
| test_file = os.path.abspath(__file__)
with mock.patch('os.path.join', return_value=test_file):
with mock.patch('yaml.load'):
with mock.patch('jenkins_jobs.builder.JobCache._lock'):
jenkins_jobs.builder.JobCache('dummy').data = None
|
'Tests the test_convert_mapping_to_xml_fail_required function'
| def test_convert_mapping_to_xml(self):
| default_root = XML.Element('testdefault')
default_data = yaml.load('string: hello')
default_mappings = [('default-string', 'defaultString', 'default')]
convert_mapping_to_xml(default_root, default_data, default_mappings, fail_required=True)
result = default_root.find('defaultString').text
sel... |
'Verify that anchors/aliases only span use of \'!include\' tag
To ensure that any yaml loaded by the include tag is in the same
space as the top level file, but individual top level yaml definitions
are treated by the yaml loader as independent.'
| def test_multiple_same_anchor_in_multiple_toplevel_yaml(self):
| files = ['custom_same_anchor-001-part1.yaml', 'custom_same_anchor-001-part2.yaml']
jjb_config = JJBConfig()
jjb_config.jenkins['url'] = 'http://example.com'
jjb_config.jenkins['user'] = 'jenkins'
jjb_config.jenkins['password'] = 'password'
jjb_config.builder['plugins_info'] = []
jjb_config.v... |
'Verify that JJB uses the global config file by default'
| def test_use_global_config(self):
| args = ['test', 'foo']
conffp = io.open(self.default_config_file, 'r', encoding='utf-8')
with patch('os.path.isfile', return_value=True) as m_isfile:
def side_effect(path):
if (path == self.global_conf):
return True
return False
m_isfile.side_effect = ... |
'Verify that JJB uses config file in user home folder'
| def test_use_config_in_user_home(self):
| args = ['test', 'foo']
conffp = io.open(self.default_config_file, 'r', encoding='utf-8')
with patch('os.path.isfile', return_value=True) as m_isfile:
def side_effect(path):
if (path == self.user_conf):
return True
return False
m_isfile.side_effect = si... |
'Run test mode and pass a non-existing configuration directory'
| def test_non_existing_config_dir(self):
| args = ['--conf', self.default_config_file, 'test', 'foo']
jenkins_jobs = entry.JenkinsJobs(args)
self.assertRaises(IOError, jenkins_jobs.execute)
|
'Run test mode and pass a non-existing configuration file'
| def test_non_existing_config_file(self):
| args = ['--conf', self.default_config_file, 'test', 'non-existing.yaml']
jenkins_jobs = entry.JenkinsJobs(args)
self.assertRaises(IOError, jenkins_jobs.execute)
|
'Run test mode and check config settings from conf file retained
when non of the global CLI options are set.'
| def test_config_options_not_replaced_by_cli_defaults(self):
| config_file = os.path.join(self.fixtures_path, 'settings_from_config.ini')
args = ['--conf', config_file, 'test', 'dummy.yaml']
jenkins_jobs = entry.JenkinsJobs(args)
jjb_config = jenkins_jobs.jjb_config
self.assertEqual(jjb_config.jenkins['user'], 'jenkins_user')
self.assertEqual(jjb_config.jen... |
'Run test mode and check config settings from conf file retained
when non of the global CLI options are set.'
| def test_config_options_overriden_by_cli(self):
| args = ['--user', 'myuser', '--password', 'mypassword', '--ignore-cache', '--flush-cache', '--allow-empty-variables', 'test', 'dummy.yaml']
jenkins_jobs = entry.JenkinsJobs(args)
jjb_config = jenkins_jobs.jjb_config
self.assertEqual(jjb_config.jenkins['user'], 'myuser')
self.assertEqual(jjb_config.j... |
'Check that timeout is left unset
Test that the Jenkins object has the timeout set on it only when
provided via the config option.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager')
def test_update_timeout_not_set(self, jenkins_mock):
| path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
args = ['--conf', self.default_config_file, 'update', path]
jenkins_mock.return_value.update_jobs.return_value = ([], 0)
jenkins_mock.return_value.update_views.return_value = ([], 0)
self.execute_jenkins_jobs_with_args(args)
jjb_config = je... |
'Check that timeout is set correctly
Test that the Jenkins object has the timeout set on it only when
provided via the config option.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager')
def test_update_timeout_set(self, jenkins_mock):
| path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
config_file = os.path.join(self.fixtures_path, 'non-default-timeout.ini')
args = ['--conf', config_file, 'update', path]
jenkins_mock.return_value.update_jobs.return_value = ([], 0)
jenkins_mock.return_value.update_views.return_value = ([], 0)
... |
'Test handling the deletion of a single Jenkins job.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager.delete_jobs')
@mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager.delete_views')
def test_delete_single_job(self, delete_job_mock, delete_view_mock):
| args = ['--conf', self.default_config_file, 'delete', 'test_job']
self.execute_jenkins_jobs_with_args(args)
|
'Test handling the deletion of multiple Jenkins jobs.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager.delete_jobs')
@mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager.delete_views')
def test_delete_multiple_jobs(self, delete_job_mock, delete_view_mock):
| args = ['--conf', self.default_config_file, 'delete', 'test_job1', 'test_job2']
self.execute_jenkins_jobs_with_args(args)
|
'Test handling the deletion of multiple Jenkins jobs using the glob
parameters feature.'
| @mock.patch('jenkins_jobs.builder.JenkinsManager.delete_job')
def test_delete_using_glob_params(self, delete_job_mock):
| args = ['--conf', self.default_config_file, 'delete', '--path', os.path.join(self.fixtures_path, 'cmd-002.yaml'), '*bar*']
self.execute_jenkins_jobs_with_args(args)
calls = [mock.call('bar001'), mock.call('bar002')]
delete_job_mock.assert_has_calls(calls, any_order=True)
self.assertEqual(delete_job_... |
'Test handling the deletion of a single Jenkins job.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager.delete_all_jobs')
def test_delete_all_accept(self, delete_job_mock):
| args = ['--conf', self.default_config_file, 'delete-all']
with mock.patch('jenkins_jobs.utils.input', return_value='y'):
self.execute_jenkins_jobs_with_args(args)
|
'Test handling the deletion of a single Jenkins job.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.JenkinsManager.delete_all_jobs')
def test_delete_all_abort(self, delete_job_mock):
| args = ['--conf', self.default_config_file, 'delete-all']
with mock.patch('jenkins_jobs.utils.input', return_value='n'):
self.assertRaises(SystemExit, self.execute_jenkins_jobs_with_args, args)
|
'Run test mode and pass a non-existing job name
(probably better to fail here)'
| def test_non_existing_job(self):
| args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), 'invalid']
self.execute_jenkins_jobs_with_args(args)
|
'Run test mode and pass a valid job name'
| def test_valid_job(self):
| args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), 'foo-job']
self.execute_jenkins_jobs_with_args(args)
|
'Run test mode and verify that resulting XML gets sent to the console.'
| def test_console_output(self):
| console_out = io.BytesIO()
with mock.patch('sys.stdout', console_out):
args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]
self.execute_jenkins_jobs_with_args(args)
xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'), 'r', e... |
'Run test mode with output to directory and verify that output files are
generated.'
| def test_output_dir(self):
| tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmpdir)
args = ['test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), '-o', tmpdir]
self.execute_jenkins_jobs_with_args(args)
self.expectThat(os.path.join(tmpdir, 'foo-job'), testtools.matchers.FileExists())
|
'Run test mode with output to directory in "config.xml" mode and verify
that output files are generated.'
| def test_output_dir_config_xml(self):
| tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmpdir)
args = ['test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), '-o', tmpdir, '--config-xml']
self.execute_jenkins_jobs_with_args(args)
self.expectThat(os.path.join(tmpdir, 'foo-job', 'config.xml'), testtools.matchers.FileExists())... |
'Test that we don\'t have issues processing large number of jobs and
outputting the result if the encoding is not set.'
| def test_stream_input_output_no_encoding_exceed_recursion(self):
| console_out = io.BytesIO()
input_file = os.path.join(self.fixtures_path, 'large-number-of-jobs-001.yaml')
with io.open(input_file, 'r') as f:
with mock.patch('sys.stdout', console_out):
console_out.encoding = None
with mock.patch('sys.stdin', f):
args = ['test... |
'Run test mode simulating using pipes for input and output using
utf-8 encoding'
| def test_stream_input_output_utf8_encoding(self):
| console_out = io.BytesIO()
input_file = os.path.join(self.fixtures_path, 'cmd-001.yaml')
with io.open(input_file, 'r') as f:
with mock.patch('sys.stdout', console_out):
with mock.patch('sys.stdin', f):
args = ['--conf', self.default_config_file, 'test']
se... |
'Run test mode simulating using pipes for input and output using
ascii encoding with unicode input'
| def test_stream_input_output_ascii_encoding(self):
| console_out = io.BytesIO()
console_out.encoding = 'ascii'
input_file = os.path.join(self.fixtures_path, 'cmd-001.yaml')
with io.open(input_file, 'r') as f:
with mock.patch('sys.stdout', console_out):
with mock.patch('sys.stdin', f):
args = ['--conf', self.default_conf... |
'Run test mode simulating using pipes for input and output using
ascii encoding for output with include containing a character
that cannot be converted.'
| def test_stream_output_ascii_encoding_invalid_char(self):
| console_out = io.BytesIO()
console_out.encoding = 'ascii'
input_file = os.path.join(self.fixtures_path, 'unicode001.yaml')
with io.open(input_file, 'r', encoding='utf-8') as f:
with mock.patch('sys.stdout', console_out):
with mock.patch('sys.stdin', f):
args = ['--con... |
'Test handling of plugins_info stub option.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.XmlJobGenerator.generateXML')
@mock.patch('jenkins_jobs.cli.subcommand.update.ModuleRegistry')
def test_plugins_info_stub_option(self, registry_mock, generateXML_mock):
| plugins_info_stub_yaml_file = os.path.join(self.fixtures_path, 'plugins-info.yaml')
args = ['--conf', os.path.join(self.fixtures_path, 'cmd-001.conf'), 'test', '-p', plugins_info_stub_yaml_file, os.path.join(self.fixtures_path, 'cmd-001.yaml')]
self.execute_jenkins_jobs_with_args(args)
with io.open(plug... |
'Verify that a JenkinsJobException is raised if the plugins_info stub
file does not yield a list as its top-level object.'
| @mock.patch('jenkins_jobs.cli.subcommand.update.XmlJobGenerator.generateXML')
@mock.patch('jenkins_jobs.cli.subcommand.update.ModuleRegistry')
def test_bogus_plugins_info_stub_option(self, registry_mock, generateXML_mock):
| plugins_info_stub_yaml_file = os.path.join(self.fixtures_path, 'bogus-plugins-info.yaml')
args = ['--conf', os.path.join(self.fixtures_path, 'cmd-001.conf'), 'test', '-p', plugins_info_stub_yaml_file, os.path.join(self.fixtures_path, 'cmd-001.yaml')]
stderr = StringIO()
with mock.patch('sys.stderr', std... |
'Run test mode and verify that failed Jenkins connection attempt
exception does not bubble out of cmd.main. Ideally, we would also test
that an appropriate message is logged to stderr but it\'s somewhat
difficult to figure out how to actually enable stderr in this test
suite.'
| @mock.patch('jenkins.Jenkins.get_plugins')
def test_console_output_jenkins_connection_failure_warning(self, get_plugins_mock):
| get_plugins_mock.side_effect = jenkins.JenkinsException('Connection refused')
with mock.patch('sys.stdout'):
try:
args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]
self.execute_jenkins_jobs_with_args(args)
except jenk... |
'Verify that retrieval of information from Jenkins instance about its
plugins will be skipped when run if no config file provided.'
| @mock.patch('jenkins.Jenkins.get_plugins')
def test_skip_plugin_retrieval_if_no_config_provided(self, get_plugins_mock):
| with mock.patch('sys.stdout', new_callable=io.BytesIO):
args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]
entry.JenkinsJobs(args)
self.assertFalse(get_plugins_mock.called)
|
'Verify that retrieval of information from Jenkins instance about its
plugins will be skipped when run if a config file provided and disables
querying through a config option.'
| @mock.patch('jenkins.Jenkins.get_plugins_info')
def test_skip_plugin_retrieval_if_disabled(self, get_plugins_mock):
| with mock.patch('sys.stdout', new_callable=io.BytesIO):
args = ['--conf', os.path.join(self.fixtures_path, 'disable-query-plugins.conf'), 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]
entry.JenkinsJobs(args)
self.assertFalse(get_plugins_mock.called)
|
'Run test mode and pass multiple paths.'
| def test_multi_path(self):
| args = ['--conf', self.default_config_file, 'test', '-o', self.output_dir, self.multipath]
self.execute_jenkins_jobs_with_args(args)
self.check_dirs_match(os.path.join(self.fixtures_path, 'multi-path/output_simple'))
|
'Run test mode and pass multiple paths with recursive path option.'
| def test_recursive_multi_path_command_line(self):
| args = ['--conf', self.default_config_file, 'test', '-o', self.output_dir, '-r', self.multipath]
self.execute_jenkins_jobs_with_args(args)
self.check_dirs_match(os.path.join(self.fixtures_path, 'multi-path/output_recursive'))
|
'Run test mode and pass multiple paths with recursive path option.'
| def test_recursive_multi_path_with_excludes(self):
| exclude_path = os.path.join(self.fixtures_path, 'multi-path/yamldirs/dir2/dir1')
args = ['--conf', self.default_config_file, 'test', '-x', exclude_path, '-o', self.output_dir, '-r', self.multipath]
self.execute_jenkins_jobs_with_args(args)
self.check_dirs_match(os.path.join(self.fixtures_path, 'multi-pa... |
'Test update_job is called'
| @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.job_exists')
@mock.patch('jenkins_jobs.builder.jenkins.Jenkins.get_jobs')
@mock.patch('jenkins_jobs.builder.jenkins.Jenkins.reconfig_job')
def test_update_jobs(self, jenkins_reconfig_job, jenkins_get_jobs, jenkins_job_exists):
| path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
args = ['--conf', self.default_config_file, 'update', path]
self.execute_jenkins_jobs_with_args(args)
jenkins_reconfig_job.assert_has_calls([mock.call(job_name, mock.ANY) for job_name in ['bar001', 'bar002', 'baz001', 'bam001']], any_order=True)
|
'Test that job xml output has been decoded before attempting to update'
| @mock.patch('jenkins_jobs.builder.JenkinsManager.is_job', return_value=True)
@mock.patch('jenkins_jobs.builder.JenkinsManager.get_jobs')
@mock.patch('jenkins_jobs.builder.JenkinsManager.get_job_md5')
@mock.patch('jenkins_jobs.builder.JenkinsManager.update_job')
def test_update_jobs_decode_job_output(self, update_job_mo... | update_job_mock.return_value = ([], 0)
path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
args = ['--conf', self.default_config_file, 'update', path]
self.execute_jenkins_jobs_with_args(args)
self.assertTrue(isinstance(update_job_mock.call_args[0][1], six.text_type))
|
'Test update behaviour with --delete-old option
* mock out a call to jenkins.Jenkins.get_jobs() to return a known list
of job names.
* mock out a call to jenkins.Jenkins.reconfig_job() and
jenkins.Jenkins.delete_job() to detect calls being made to determine
that JJB does correctly delete the jobs it should delete when ... | @mock.patch('jenkins_jobs.builder.jenkins.Jenkins.job_exists')
@mock.patch('jenkins_jobs.builder.jenkins.Jenkins.get_jobs')
@mock.patch('jenkins_jobs.builder.jenkins.Jenkins.reconfig_job')
@mock.patch('jenkins_jobs.builder.jenkins.Jenkins.delete_job')
def test_update_jobs_and_delete_old(self, jenkins_delete_job, jenkin... | yaml_jobs = ['bar001', 'bar002', 'baz001', 'bam001']
extra_jobs = ['old_job001', 'old_job002', 'unmanaged']
path = os.path.join(self.fixtures_path, 'cmd-002.yaml')
args = ['--conf', self.default_config_file, 'update', '--delete-old', path]
jenkins_get_jobs.return_value = [{'name': name} for name in ... |
'Validate update timeout behavior when timeout not explicitly configured.'
| def test_update_timeout_not_set(self):
| self.skipTest('TODO: Develop actual update timeout test approach.')
|
'Validate update timeout behavior when timeout is explicitly configured.'
| def test_update_timeout_set(self):
| self.skipTest('TODO: Develop actual update timeout test approach.')
|
'Test paths returned by the recursive processing when using pattern
excludes.
testing paths
/jjb_configs/dir1/test1/
/jjb_configs/dir1/file
/jjb_configs/dir2/test2/
/jjb_configs/dir3/bar/
/jjb_configs/test3/bar/
/jjb_configs/test3/baz/'
| @mock.patch('jenkins_jobs.utils.os.walk')
def test_recursive_path_option_exclude_pattern(self, oswalk_mock):
| os_walk_paths = [('/jjb_configs', (['dir1', 'dir2', 'dir3', 'test3'], ())), ('/jjb_configs/dir1', (['test1'], 'file')), ('/jjb_configs/dir2', (['test2'], ())), ('/jjb_configs/dir3', (['bar'], ())), ('/jjb_configs/dir3/bar', ([], ())), ('/jjb_configs/test3/bar', None), ('/jjb_configs/test3/baz', None)]
paths = [... |
'Test paths returned by the recursive processing when using absolute
excludes.
testing paths
/jjb_configs/dir1/test1/
/jjb_configs/dir1/file
/jjb_configs/dir2/test2/
/jjb_configs/dir3/bar/
/jjb_configs/test3/bar/
/jjb_configs/test3/baz/'
| @mock.patch('jenkins_jobs.utils.os.walk')
def test_recursive_path_option_exclude_absolute(self, oswalk_mock):
| os_walk_paths = [('/jjb_configs', (['dir1', 'dir2', 'dir3', 'test3'], ())), ('/jjb_configs/dir1', None), ('/jjb_configs/dir2', (['test2'], ())), ('/jjb_configs/dir3', (['bar'], ())), ('/jjb_configs/test3', (['bar', 'baz'], ())), ('/jjb_configs/dir2/test2', ([], ())), ('/jjb_configs/dir3/bar', ([], ())), ('/jjb_conf... |
'Test paths returned by the recursive processing when using relative
excludes.
testing paths
./jjb_configs/dir1/test/
./jjb_configs/dir1/file
./jjb_configs/dir2/test/
./jjb_configs/dir3/bar/
./jjb_configs/test3/bar/
./jjb_configs/test3/baz/'
| @mock.patch('jenkins_jobs.utils.os.walk')
def test_recursive_path_option_exclude_relative(self, oswalk_mock):
| os_walk_paths = [('jjb_configs', (['dir1', 'dir2', 'dir3', 'test3'], ())), ('jjb_configs/dir1', (['test'], 'file')), ('jjb_configs/dir2', (['test2'], ())), ('jjb_configs/dir3', (['bar'], ())), ('jjb_configs/test3', (['bar', 'baz'], ())), ('jjb_configs/dir1/test', ([], ())), ('jjb_configs/dir2/test2', ([], ())), ('j... |
'User passes no args, should fail with SystemExit'
| def test_with_empty_args(self):
| with mock.patch('sys.stderr'):
self.assertRaises(SystemExit, entry.JenkinsJobs, [])
|
'Return a list of plugin_info dicts, one for each plugin on the
Jenkins instance.'
| def get_plugins_info(self):
| try:
plugins_list = self.jenkins.get_plugins().values()
except jenkins.JenkinsException as e:
if re.search('(Connection refused|Forbidden)', str(e)):
logger.warning('Unable to retrieve Jenkins Plugin Info from {0}, using default empty plugins in... |
'The JJBConfig class is intended to encapsulate and resolve priority
between all sources of configuration for the JJB library. This allows
the various sources of configuration to provide a consistent accessor
interface regardless of where they are used.
It also allows users of JJB-as-an-API to create minimally valid
co... | def __init__(self, config_filename=None, config_file_required=False, config_section='jenkins'):
| config_parser = self._init_defaults()
global_conf = '/etc/jenkins_jobs/jenkins_jobs.ini'
user_conf = os.path.join(os.path.expanduser('~'), '.config', 'jenkins_jobs', 'jenkins_jobs.ini')
local_conf = os.path.join(os.path.dirname(__file__), 'jenkins_jobs.ini')
conf = None
if (config_filename is no... |
'Initialize default configuration values using DEFAULT_CONF'
| def _init_defaults(self):
| config = configparser.ConfigParser()
if PY2:
config.readfp(StringIO(DEFAULT_CONF))
else:
config.read_file(StringIO(DEFAULT_CONF))
return config
|
'Given path to configuration file, read it in as a ConfigParser
object and return that object.'
| def _read_config_file(self, config_filename):
| if os.path.isfile(config_filename):
self.__config_file = config_filename
logger.debug('Reading config from {0}'.format(config_filename))
config_fp = io.open(config_filename, 'r', encoding='utf-8')
else:
raise JJBConfigException('A valid configuration file is ... |
'Given a section name and a key value, return the value assigned to
the key in the JJB .ini file if it exists, otherwise emit a warning
indicating that the value is not set. Default value returned if no
value is set in the file will be a blank string.'
| def get_module_config(self, section, key):
| result = ''
try:
result = self.config_parser.get(section, key)
except (configparser.NoSectionError, configparser.NoOptionError, JenkinsJobsException) as e:
logger.warning((((((("You didn't set a " + key) + ' neither in the yaml job definition nor in') + ' ... |
'Sets the option in target only if the given option was explicitly set'
| def _set_config(self, target, option):
| opt_val = getattr(self.options, option, None)
if (opt_val is not None):
target[option] = opt_val
|
'Add \'--recursive\' and \'--exclude\' arguments to given parser.'
| @staticmethod
def parse_option_recursive_exclude(parser):
| parser.add_argument('-r', '--recursive', action='store_true', dest='recursive', default=False, help='look for yaml files recursively')
parser.add_argument('-x', '--exclude', dest='exclude', action='append', default=[], help='paths to exclude when using recursive search, uses ... |
'This method is called before any XML is generated. By
overriding this method, a module may arbitrarily modify a data
structure which will probably be the JJB YamlParser\'s intermediate data
representation. If it has changed the data structure at all, it must
return ``True``, otherwise, it must return ``False``.
:arg ... | def handle_data(self, job_data):
| return False
|
'Update the XML element tree based on YAML data. Override
this method to add elements to the XML output. Create new
Element objects and add them to the xml_parent. The YAML data
structure must not be modified.
:arg YAMLParser parser: the global YAML Parser
:arg Element xml_parent: the parent XML element
:arg dict da... | def gen_xml(self, xml_parent, data):
| pass
|
'Load data from the global config object.
This is done lazily to avoid looking up the \'[hipchat]\' section
unless actually required.'
| def _load_global_data(self):
| jjb_config = self.registry.jjb_config
if (not self.authToken):
try:
self.authToken = jjb_config.get_plugin_config('hipchat', 'authtoken')
if (self.authToken == ''):
raise jenkins_jobs.errors.JenkinsJobsException('Hipchat authtoken must not be a b... |
'This method is intended to provide information about plugins within
a given module\'s implementation of Base.gen_xml. The return value is a
dictionary with data obtained directly from a running Jenkins instance.
This allows module authors to differentiate generated XML output based
on information such as specific plug... | def get_plugin_info(self, plugin_name):
| return self.plugins_dict.get(plugin_name, {})
|
'This is a method that you can call from your implementation of
Base.gen_xml or component. It allows modules to define a type
of component, and benefit from extensibility via Python
entry points and Jenkins Job Builder :ref:`Macros <macro>`.
:arg string component_type: the name of the component
(e.g., `builder`)
:arg ... | def dispatch(self, component_type, xml_parent, component, template_data={}):
| if (component_type not in self.modules_by_component_type):
raise JenkinsJobsException("Unknown component type: '{0}'.".format(component_type))
entry_point = self.modules_by_component_type[component_type]
component_list_type = entry_point.load().component_list_type
if isinstance(componen... |
'Transform a Python signature into RST nodes.
Return (fully qualified name of the thing, classname if any).
If inside a class, the current class name is handled intelligently:
* it is stripped from the displayed name if present
* it is added to the full name (return value) if not present'
| def handle_signature(self, sig, signode):
| name_prefix = None
name = sig
arglist = None
retann = None
modname = self.options.get('module', self.env.temp_data.get('py:module'))
classname = self.env.temp_data.get('py:class')
fullname = name
signode['module'] = modname
signode['class'] = classname
signode['fullname'] = fulln... |
'Return filter method based on whether we\'re excluding
or simply filtering.'
| def get_method(self, qs):
| return (qs.exclude if self.exclude else qs.filter)
|
'Filter method needs to be lazily resolved, as it may be dependent on
the \'parent\' FilterSet.'
| def method():
| def fget(self):
return self._method
def fset(self, value):
self._method = value
if isinstance(self.filter, FilterMethod):
del self.filter
if (value is not None):
self.filter = FilterMethod(self)
return locals()
|
'Return `True` to short-circuit unnecessary and potentially slow
filtering.'
| def is_noop(self, qs, value):
| if self.always_filter:
return False
if (self.required and (len(value) == len(self.field.choices))):
return True
return False
|
'Generate a suitable class name for the concrete field class. This is not
completely reliable, as not all field class names are of the format
<Type>Field.
ex::
BaseCSVFilter._field_class_name(DateTimeField, \'year__in\')
returns \'DateTimeYearInField\''
| @classmethod
def _field_class_name(cls, field_class, lookup_expr):
| type_name = field_class.__name__
if type_name.endswith(u'Field'):
type_name = type_name[:(-5)]
parts = lookup_expr.split(LOOKUP_SEP)
expression_name = u''.join((p.capitalize() for p in parts))
return str((u'%s%sField' % (type_name, expression_name)))
|
'``fields`` may be either a mapping or an iterable.
``field_labels`` must be a map of field names to display labels'
| def __init__(self, *args, **kwargs):
| fields = kwargs.pop(u'fields', {})
fields = self.normalize_fields(fields)
field_labels = kwargs.pop(u'field_labels', {})
self.param_map = {v: k for (k, v) in fields.items()}
if (u'choices' not in kwargs):
kwargs[u'choices'] = self.build_choices(fields, field_labels)
kwargs.setdefault(u'l... |
'Normalize the fields into an ordered map of {field name: param name}'
| @classmethod
def normalize_fields(cls, fields):
| if isinstance(fields, dict):
return OrderedDict(fields)
assert is_iterable(fields), u"'fields' must be an iterable (e.g., a list, tuple, or mapping)."
assert all(((isinstance(field, six.string_types) or (is_iterable(field) and (len(field) == 2))) for field in fields)), ... |
'Resolve the method on the parent filterset.'
| @property
def method(self):
| instance = self.f
if callable(instance.method):
return instance.method
assert hasattr(instance, u'parent'), (u"Filter '%s' must have a parent FilterSet to find '.%s()'" % (instance.name, instance.method))
parent = instance.parent
method = getattr(parent, instance.m... |
'Resolve the \'fields\' argument that should be used for generating filters on the
filterset. This is \'Meta.fields\' sans the fields in \'Meta.exclude\'.'
| @classmethod
def get_fields(cls):
| model = cls._meta.model
fields = cls._meta.fields
exclude = cls._meta.exclude
assert (not ((fields is None) and (exclude is None))), (u"Setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed.... |
'Get all filters for the filterset. This is the combination of declared and
generated filters.'
| @classmethod
def get_filters(cls):
| if (not cls._meta.model):
return cls.declared_filters.copy()
filters = OrderedDict()
fields = cls.get_fields()
undefined = []
for (field_name, lookups) in fields.items():
field = get_model_field(cls._meta.model, field_name)
if (field is None):
undefined.append(fie... |
'Generate a suitable class name for a concrete filter class. This is not
completely reliable, as not all filter class names are of the format
<Type>Filter.
ex::
FilterSet._csv_filter_class_name(DateTimeFilter, \'in\')
returns \'DateTimeInFilter\''
| @classmethod
def _csv_filter_class_name(cls, filter_class, lookup_type):
| type_name = filter_class.__name__
if type_name.endswith(u'Filter'):
type_name = type_name[:(-6)]
lookup_name = lookup_type.capitalize()
return str((u'%s%sFilter' % (type_name, lookup_name)))
|
'Return the django-filters `FilterSet` used to filter the queryset.'
| def get_filter_class(self, view, queryset=None):
| filter_class = getattr(view, 'filter_class', None)
filter_fields = getattr(view, 'filter_fields', None)
if filter_class:
filter_model = filter_class.Meta.model
assert issubclass(queryset.model, filter_model), ('FilterSet model %s does not match queryset model %s' % (f... |
'Returns the filterset class to use in this view'
| def get_filterset_class(self):
| if self.filterset_class:
return self.filterset_class
elif self.model:
return filterset_factory(model=self.model, fields=self.filter_fields)
else:
msg = u"'%s' must define 'filterset_class' or 'model'"
raise ImproperlyConfigured((msg % self.__class__.__name__))
|
'Returns an instance of the filterset to be used in this view.'
| def get_filterset(self, filterset_class):
| kwargs = self.get_filterset_kwargs(filterset_class)
return filterset_class(**kwargs)
|
'Returns the keyword arguments for instanciating the filterset.'
| def get_filterset_kwargs(self, filterset_class):
| kwargs = {u'data': (self.request.GET or None), u'request': self.request}
try:
kwargs.update({u'queryset': self.get_queryset()})
except ImproperlyConfigured:
if (filterset_class._meta.model is None):
msg = u"'%s' does not define a 'model' and the view '%... |
''
| def test_widget_value_from_datadict(self):
| w = BooleanWidget()
trueActive = {u'active': u'true'}
result = w.value_from_datadict(trueActive, {}, u'active')
self.assertEqual(result, True)
falseActive = {u'active': u'false'}
result = w.value_from_datadict(falseActive, {}, u'active')
self.assertEqual(result, False)
result = w.value_f... |
'Test for #30.
If you explicitly declare ChoiceFilter fields you **MUST** pass `choices`.'
| def test_filtering_on_explicitly_defined_field(self):
| class F(FilterSet, ):
status = ChoiceFilter(choices=STATUS_CHOICES)
class Meta:
model = User
fields = [u'status']
f = F()
self.assertQuerysetEqual(f.qs, [u'aaron', u'alex', u'jacob', u'carl'], (lambda o: o.username), False)
f = F({u'status': u'1'})
self.assert... |
'See:
* https://github.com/carltongibson/django-filter/issues/551'
| def test_filter_fields_list_with_bad_get_queryset(self):
| class BadGetQuerySetView(FilterFieldsRootView, ):
def get_queryset(self):
raise AttributeError(u"I don't have that")
backend = DjangoFilterBackend()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter(u'always')
fields = backend.get_schema_field... |
'Ensure backend renders default if template path does not exist'
| def test_backend_output(self):
| view = FilterFieldsRootView()
backend = view.filter_backends[0]
request = view.initialize_request(factory.get(u'/'))
html = backend().to_html(request, view.get_queryset(), view)
self.assertHTMLEqual(html, u'\n <h2>Field filters</h2>\n ... |
'Create 10 FilterableItem instances.'
| def setUp(self):
| base_data = (u'a', Decimal(u'0.25'), datetime.date(2012, 10, 8))
for i in range(10):
text = (chr((i + ord(base_data[0]))) * 3)
decimal = (base_data[1] + i)
date = (base_data[2] - datetime.timedelta(days=(i * 2)))
FilterableItem(text=text, decimal=decimal, date=date).save()
se... |
'GET requests to paginated ListCreateAPIView should return paginated results.'
| def test_get_filtered_fields_root_view(self):
| view = FilterFieldsRootView.as_view()
request = factory.get(u'/')
response = view(request).render()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, self.data)
search_decimal = Decimal(u'2.25')
request = factory.get(u'/', {u'decimal': (u'%s' % search... |
'Regression test for #814.'
| def test_filter_with_queryset(self):
| view = FilterFieldsQuerysetView.as_view()
search_decimal = Decimal(u'2.25')
request = factory.get(u'/', {u'decimal': (u'%s' % search_decimal)})
response = view(request).render()
self.assertEqual(response.status_code, status.HTTP_200_OK)
expected_data = [f for f in self.data if (Decimal(f[u'decim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.